@pay-skill/sdk 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.
Files changed (53) hide show
  1. package/README.md +154 -0
  2. package/dist/auth.d.ts +47 -0
  3. package/dist/auth.d.ts.map +1 -0
  4. package/dist/auth.js +121 -0
  5. package/dist/auth.js.map +1 -0
  6. package/dist/client.d.ts +93 -0
  7. package/dist/client.d.ts.map +1 -0
  8. package/dist/client.js +391 -0
  9. package/dist/client.js.map +1 -0
  10. package/dist/errors.d.ts +24 -0
  11. package/dist/errors.d.ts.map +1 -0
  12. package/dist/errors.js +42 -0
  13. package/dist/errors.js.map +1 -0
  14. package/dist/index.d.ts +13 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +7 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/models.d.ts +69 -0
  19. package/dist/models.d.ts.map +1 -0
  20. package/dist/models.js +2 -0
  21. package/dist/models.js.map +1 -0
  22. package/dist/ows-signer.d.ts +75 -0
  23. package/dist/ows-signer.d.ts.map +1 -0
  24. package/dist/ows-signer.js +130 -0
  25. package/dist/ows-signer.js.map +1 -0
  26. package/dist/signer.d.ts +46 -0
  27. package/dist/signer.d.ts.map +1 -0
  28. package/dist/signer.js +112 -0
  29. package/dist/signer.js.map +1 -0
  30. package/dist/wallet.d.ts +121 -0
  31. package/dist/wallet.d.ts.map +1 -0
  32. package/dist/wallet.js +328 -0
  33. package/dist/wallet.js.map +1 -0
  34. package/eslint.config.js +22 -0
  35. package/package.json +44 -0
  36. package/src/auth.ts +200 -0
  37. package/src/client.ts +644 -0
  38. package/src/eip3009.ts +79 -0
  39. package/src/errors.ts +48 -0
  40. package/src/index.ts +51 -0
  41. package/src/models.ts +77 -0
  42. package/src/ows-signer.ts +223 -0
  43. package/src/signer.ts +147 -0
  44. package/src/wallet.ts +445 -0
  45. package/tests/test_auth_rejection.ts +154 -0
  46. package/tests/test_crypto.ts +251 -0
  47. package/tests/test_e2e.ts +158 -0
  48. package/tests/test_errors.ts +36 -0
  49. package/tests/test_ows_integration.ts +92 -0
  50. package/tests/test_ows_signer.ts +365 -0
  51. package/tests/test_signer.ts +47 -0
  52. package/tests/test_validation.ts +66 -0
  53. package/tsconfig.json +19 -0
package/src/eip3009.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * EIP-3009 TransferWithAuthorization signing for x402 direct settlement.
3
+ *
4
+ * Unlike EIP-2612 permits (which need a nonce from the USDC contract),
5
+ * EIP-3009 uses a random nonce chosen by the signer. Fully local — no
6
+ * server round-trip needed.
7
+ *
8
+ * Domain: { name: "USD Coin", version: "2", chainId, verifyingContract: usdcAddress }
9
+ * Type: TransferWithAuthorization(address from, address to, uint256 value,
10
+ * uint256 validAfter, uint256 validBefore, bytes32 nonce)
11
+ */
12
+
13
+ import { type Hex, type Address } from "viem";
14
+ import { privateKeyToAccount } from "viem/accounts";
15
+ import { randomBytes } from "node:crypto";
16
+
17
+ export interface TransferAuthorization {
18
+ from: string;
19
+ to: string;
20
+ amount: number;
21
+ nonce: string;
22
+ v: number;
23
+ r: string;
24
+ s: string;
25
+ }
26
+
27
+ const TRANSFER_AUTH_TYPES = {
28
+ TransferWithAuthorization: [
29
+ { name: "from", type: "address" },
30
+ { name: "to", type: "address" },
31
+ { name: "value", type: "uint256" },
32
+ { name: "validAfter", type: "uint256" },
33
+ { name: "validBefore", type: "uint256" },
34
+ { name: "nonce", type: "bytes32" },
35
+ ],
36
+ } as const;
37
+
38
+ export async function signTransferAuthorization(
39
+ privateKey: Hex,
40
+ to: Address,
41
+ amount: number,
42
+ chainId: number,
43
+ usdcAddress: Address,
44
+ ): Promise<TransferAuthorization> {
45
+ const account = privateKeyToAccount(privateKey);
46
+ const nonce = ("0x" + randomBytes(32).toString("hex")) as Hex;
47
+
48
+ const signature = await account.signTypedData({
49
+ domain: {
50
+ name: "USD Coin",
51
+ version: "2",
52
+ chainId,
53
+ verifyingContract: usdcAddress,
54
+ },
55
+ types: TRANSFER_AUTH_TYPES,
56
+ primaryType: "TransferWithAuthorization",
57
+ message: {
58
+ from: account.address,
59
+ to,
60
+ value: BigInt(amount),
61
+ validAfter: 0n,
62
+ validBefore: 0n,
63
+ nonce,
64
+ },
65
+ });
66
+
67
+ const sigHex = signature.slice(2);
68
+ const r = `0x${sigHex.slice(0, 64)}`;
69
+ const s = `0x${sigHex.slice(64, 128)}`;
70
+ const v = parseInt(sigHex.slice(128, 130), 16);
71
+
72
+ return { from: account.address, to, amount, nonce, v, r, s };
73
+ }
74
+
75
+ export function combinedSignature(auth: TransferAuthorization): string {
76
+ const r = auth.r.startsWith("0x") ? auth.r.slice(2) : auth.r;
77
+ const s = auth.s.startsWith("0x") ? auth.s.slice(2) : auth.s;
78
+ return `0x${r}${s}${auth.v.toString(16).padStart(2, "0")}`;
79
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,48 @@
1
+ /** Base error for all pay SDK errors. */
2
+ export class PayError extends Error {
3
+ readonly code: string;
4
+
5
+ constructor(message: string, code = "pay_error") {
6
+ super(message);
7
+ this.name = "PayError";
8
+ this.code = code;
9
+ }
10
+ }
11
+
12
+ /** Input validation failed. */
13
+ export class PayValidationError extends PayError {
14
+ readonly field?: string;
15
+
16
+ constructor(message: string, field?: string) {
17
+ super(message, "validation_error");
18
+ this.name = "PayValidationError";
19
+ this.field = field;
20
+ }
21
+ }
22
+
23
+ /** Network or server communication failed. */
24
+ export class PayNetworkError extends PayError {
25
+ constructor(message: string) {
26
+ super(message, "network_error");
27
+ this.name = "PayNetworkError";
28
+ }
29
+ }
30
+
31
+ /** Server returned an error response. */
32
+ export class PayServerError extends PayError {
33
+ readonly statusCode: number;
34
+
35
+ constructor(message: string, statusCode: number) {
36
+ super(message, "server_error");
37
+ this.name = "PayServerError";
38
+ this.statusCode = statusCode;
39
+ }
40
+ }
41
+
42
+ /** Insufficient USDC balance. */
43
+ export class PayInsufficientFundsError extends PayError {
44
+ constructor(message = "Insufficient USDC balance") {
45
+ super(message, "insufficient_funds");
46
+ this.name = "PayInsufficientFundsError";
47
+ }
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,51 @@
1
+ export { PayClient, DEFAULT_API_URL } from "./client.js";
2
+ export type { PayClientOptions } from "./client.js";
3
+
4
+ export {
5
+ PayError,
6
+ PayValidationError,
7
+ PayNetworkError,
8
+ PayServerError,
9
+ PayInsufficientFundsError,
10
+ } from "./errors.js";
11
+
12
+ export type {
13
+ DirectPaymentResult,
14
+ DiscoverOptions,
15
+ DiscoverService,
16
+ Tab,
17
+ TabStatus,
18
+ StatusResponse,
19
+ WebhookRegistration,
20
+ } from "./models.js";
21
+
22
+ export type { Signer } from "./signer.js";
23
+ export {
24
+ CliSigner,
25
+ RawKeySigner,
26
+ CallbackSigner,
27
+ createSigner,
28
+ } from "./signer.js";
29
+
30
+ export { OwsSigner } from "./ows-signer.js";
31
+ export type { OwsSignerOptions } from "./ows-signer.js";
32
+
33
+ export { Wallet, PrivateKeySigner } from "./wallet.js";
34
+ export type {
35
+ WalletOptions,
36
+ FundLinkOptions,
37
+ PermitResult,
38
+ } from "./wallet.js";
39
+
40
+ export {
41
+ buildAuthHeaders,
42
+ buildAuthHeadersWithSigner,
43
+ computeEip712Hash,
44
+ } from "./auth.js";
45
+ export type { AuthConfig, AuthHeaders } from "./auth.js";
46
+
47
+ export {
48
+ signTransferAuthorization,
49
+ combinedSignature,
50
+ } from "./eip3009.js";
51
+ export type { TransferAuthorization } from "./eip3009.js";
package/src/models.ts ADDED
@@ -0,0 +1,77 @@
1
+ /** Tab lifecycle states. */
2
+ export type TabStatus = "open" | "closed";
3
+
4
+ /** Result of a direct payment. */
5
+ export interface DirectPaymentResult {
6
+ txHash: string;
7
+ status: string;
8
+ /** Amount in USDC micro-units (6 decimals). */
9
+ amount: number;
10
+ /** Fee deducted in USDC micro-units. */
11
+ fee: number;
12
+ }
13
+
14
+ /** Tab state. */
15
+ export interface Tab {
16
+ tabId: string;
17
+ provider: string;
18
+ /** Total locked amount in USDC micro-units. */
19
+ amount: number;
20
+ /** Remaining balance in USDC micro-units. */
21
+ balanceRemaining: number;
22
+ /** Total charged so far in USDC micro-units. */
23
+ totalCharged: number;
24
+ /** Number of charges made. */
25
+ chargeCount: number;
26
+ /** Max per-charge limit in USDC micro-units. */
27
+ maxChargePerCall: number;
28
+ /** Total withdrawn so far in USDC micro-units. */
29
+ totalWithdrawn: number;
30
+ status: TabStatus;
31
+ /** Number of charges buffered awaiting batch settlement. */
32
+ pendingChargeCount: number;
33
+ /** Total amount of pending charges in USDC micro-units. */
34
+ pendingChargeTotal: number;
35
+ /** balance_remaining minus pending charges — the true available balance. */
36
+ effectiveBalance: number;
37
+ }
38
+
39
+ /** Wallet status. */
40
+ export interface StatusResponse {
41
+ address: string;
42
+ /** USDC balance in micro-units. */
43
+ balance: number;
44
+ openTabs: Tab[];
45
+ }
46
+
47
+ /** Discoverable service from the facilitator catalog. */
48
+ export interface DiscoverService {
49
+ name: string;
50
+ description: string;
51
+ /** Public base URL for pay request (e.g. "https://weather.example.com"). */
52
+ baseUrl: string;
53
+ category: string;
54
+ keywords: string[];
55
+ routes: { path: string; method?: string; price?: string; settlement?: string; free?: boolean }[];
56
+ /** URL to API documentation (OpenAPI spec, docs page, etc). */
57
+ docsUrl?: string;
58
+ }
59
+
60
+ /** Options for discover search. */
61
+ export interface DiscoverOptions {
62
+ /** Search query (matches keywords and description). */
63
+ query?: string;
64
+ /** Sort order: "volume" (default), "newest", "price_asc", "price_desc". */
65
+ sort?: string;
66
+ /** Filter by category. */
67
+ category?: string;
68
+ /** Filter by settlement mode: "direct" or "tab". */
69
+ settlement?: string;
70
+ }
71
+
72
+ /** Registered webhook. */
73
+ export interface WebhookRegistration {
74
+ webhookId: string;
75
+ url: string;
76
+ events: string[];
77
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * OWS (Open Wallet Standard) signer adapter.
3
+ *
4
+ * Wraps the @open-wallet-standard/core FFI module to implement the Pay
5
+ * Signer interface. OWS handles encrypted key storage + policy-gated signing;
6
+ * this adapter translates between Pay's (domain, types, value) EIP-712
7
+ * calling convention and OWS's JSON string convention.
8
+ *
9
+ * Priority: Pay's own CLI signer is #1, OWS is #2. OWS only activates when
10
+ * OWS_WALLET_ID is set AND @open-wallet-standard/core is installed. If the
11
+ * env var is set but the package is missing, creation fails loud with
12
+ * install instructions.
13
+ *
14
+ * Usage:
15
+ * const signer = await OwsSigner.create({ walletId: "pay-my-agent" });
16
+ * const wallet = new Wallet({ signer });
17
+ */
18
+
19
+ import type { Signer } from "./signer.js";
20
+
21
+ /** Subset of @open-wallet-standard/core we call at runtime. */
22
+ interface OwsModule {
23
+ getWallet(nameOrId: string, vaultPath?: string): {
24
+ id: string;
25
+ name: string;
26
+ accounts: Array<{
27
+ chainId: string;
28
+ address: string;
29
+ derivationPath: string;
30
+ }>;
31
+ createdAt: string;
32
+ };
33
+ signTypedData(
34
+ wallet: string,
35
+ chain: string,
36
+ typedDataJson: string,
37
+ passphrase?: string,
38
+ index?: number,
39
+ vaultPath?: string,
40
+ ): { signature: string; recoveryId?: number };
41
+ }
42
+
43
+ /** EIP-712 domain fields. */
44
+ export interface TypedDataDomain {
45
+ name?: string;
46
+ version?: string;
47
+ chainId?: number | bigint;
48
+ verifyingContract?: string;
49
+ }
50
+
51
+ /** EIP-712 type definitions. */
52
+ export interface TypedDataTypes {
53
+ [typeName: string]: Array<{ name: string; type: string }>;
54
+ }
55
+
56
+ /** Options for {@link OwsSigner.create}. */
57
+ export interface OwsSignerOptions {
58
+ /** OWS wallet name or UUID (e.g. "pay-my-agent"). */
59
+ walletId: string;
60
+ /** Chain name - only used for logging, not passed to OWS. Default: "base". */
61
+ chain?: string;
62
+ /** OWS API key token (passed as passphrase to OWS signing calls). */
63
+ owsApiKey?: string;
64
+ /** @internal Inject OWS module for testing - bypasses dynamic import. */
65
+ _owsModule?: unknown;
66
+ }
67
+
68
+ /**
69
+ * Signer backed by the Open Wallet Standard.
70
+ *
71
+ * - Keys live in OWS's encrypted vault (~/.ows/wallets/), never in env vars.
72
+ * - Signing calls go through OWS FFI, which evaluates policy rules before signing.
73
+ * - Use the static {@link create} factory - the constructor is private because
74
+ * address resolution requires a synchronous FFI call that must happen before
75
+ * sign() can work.
76
+ */
77
+ export class OwsSigner implements Signer {
78
+ readonly #walletId: string;
79
+ readonly #address: string;
80
+ readonly #owsApiKey: string | undefined;
81
+ readonly #ows: OwsModule;
82
+
83
+ private constructor(
84
+ walletId: string,
85
+ address: string,
86
+ owsModule: OwsModule,
87
+ owsApiKey?: string,
88
+ ) {
89
+ this.#walletId = walletId;
90
+ this.#address = address;
91
+ this.#ows = owsModule;
92
+ this.#owsApiKey = owsApiKey;
93
+ }
94
+
95
+ /**
96
+ * Create an OwsSigner by resolving the wallet address from OWS.
97
+ *
98
+ * Lazily imports @open-wallet-standard/core so the module is only required
99
+ * when OWS is actually used (keeps it an optional peer dependency).
100
+ */
101
+ static async create(options: OwsSignerOptions): Promise<OwsSigner> {
102
+ let owsModule: OwsModule;
103
+ if (options._owsModule) {
104
+ owsModule = options._owsModule as OwsModule;
105
+ } else {
106
+ try {
107
+ // Dynamic string prevents TypeScript from statically resolving this
108
+ // optional peer dependency at compile time.
109
+ const moduleName = "@open-wallet-standard/core";
110
+ owsModule = (await import(moduleName)) as unknown as OwsModule;
111
+ } catch {
112
+ throw new Error(
113
+ "OWS_WALLET_ID is set but @open-wallet-standard/core is not installed. " +
114
+ "Install it with: npm install @open-wallet-standard/core",
115
+ );
116
+ }
117
+ }
118
+
119
+ const walletInfo = owsModule.getWallet(options.walletId);
120
+ const evmAccount = walletInfo.accounts.find(
121
+ (a) => a.chainId === "evm" || a.chainId.startsWith("eip155:"),
122
+ );
123
+ if (!evmAccount) {
124
+ throw new Error(
125
+ `No EVM account found in OWS wallet '${options.walletId}'. ` +
126
+ `Available chains: ${walletInfo.accounts.map((a) => a.chainId).join(", ") || "none"}.`,
127
+ );
128
+ }
129
+
130
+ return new OwsSigner(
131
+ options.walletId,
132
+ evmAccount.address,
133
+ owsModule,
134
+ options.owsApiKey,
135
+ );
136
+ }
137
+
138
+ get address(): string {
139
+ return this.#address;
140
+ }
141
+
142
+ sign(_hash: Uint8Array): Uint8Array {
143
+ throw new Error(
144
+ "OwsSigner does not support raw hash signing. " +
145
+ "OWS only supports EIP-712 typed data signing. " +
146
+ "Use CliSigner or RawKeySigner for operations that require sign().",
147
+ );
148
+ }
149
+
150
+ /**
151
+ * Sign EIP-712 typed data via OWS FFI.
152
+ *
153
+ * This is the primary signing method for OWS. Pay's auth module should
154
+ * call this instead of sign() when an OwsSigner is detected.
155
+ */
156
+ async signTypedData(
157
+ domain: TypedDataDomain,
158
+ types: TypedDataTypes,
159
+ value: Record<string, unknown>,
160
+ ): Promise<string> {
161
+ // 1. Derive primaryType: first key in types that is NOT "EIP712Domain".
162
+ const primaryType =
163
+ Object.keys(types).filter((k) => k !== "EIP712Domain")[0] ?? "Request";
164
+
165
+ // 2. Build EIP712Domain type array dynamically from domain object fields.
166
+ const eip712DomainType: Array<{ name: string; type: string }> = [];
167
+ if (domain.name !== undefined)
168
+ eip712DomainType.push({ name: "name", type: "string" });
169
+ if (domain.version !== undefined)
170
+ eip712DomainType.push({ name: "version", type: "string" });
171
+ if (domain.chainId !== undefined)
172
+ eip712DomainType.push({ name: "chainId", type: "uint256" });
173
+ if (domain.verifyingContract !== undefined)
174
+ eip712DomainType.push({
175
+ name: "verifyingContract",
176
+ type: "address",
177
+ });
178
+
179
+ // 3. Assemble full EIP-712 typed data structure.
180
+ const fullTypedData = {
181
+ types: { EIP712Domain: eip712DomainType, ...types },
182
+ primaryType,
183
+ domain,
184
+ message: value,
185
+ };
186
+
187
+ // 4. Serialize - handle BigInt values.
188
+ const json = JSON.stringify(fullTypedData, (_key, v) =>
189
+ typeof v === "bigint" ? v.toString() : (v as unknown),
190
+ );
191
+
192
+ // 5. Call OWS FFI. Chain is always "evm" for EVM signing.
193
+ const result = this.#ows.signTypedData(
194
+ this.#walletId,
195
+ "evm",
196
+ json,
197
+ this.#owsApiKey,
198
+ );
199
+
200
+ // 6. Concatenate r+s+v into 65-byte Ethereum signature.
201
+ const sig = result.signature.startsWith("0x")
202
+ ? result.signature.slice(2)
203
+ : result.signature;
204
+
205
+ // If OWS already returns r+s+v (130 hex chars), use as-is.
206
+ if (sig.length === 130) {
207
+ return `0x${sig}`;
208
+ }
209
+
210
+ // Otherwise it's r+s (128 hex chars), append v.
211
+ const v = (result.recoveryId ?? 0) + 27;
212
+ return `0x${sig}${v.toString(16).padStart(2, "0")}`;
213
+ }
214
+
215
+ /** Prevent wallet ID / key leakage in serialization. */
216
+ toJSON(): Record<string, string> {
217
+ return { address: this.#address, walletId: this.#walletId };
218
+ }
219
+
220
+ [Symbol.for("nodejs.util.inspect.custom")](): string {
221
+ return `OwsSigner { address: '${this.#address}', wallet: '${this.#walletId}' }`;
222
+ }
223
+ }
package/src/signer.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Signer interface and implementations.
3
+ *
4
+ * Three modes:
5
+ * 1. CLI signer (default): subprocess call to `pay sign`
6
+ * 2. Raw key: from PAYSKILL_KEY environment variable (dev/testing only)
7
+ * 3. Custom: user provides a sign(hash) -> signature callback
8
+ */
9
+
10
+ import { execFileSync } from "node:child_process";
11
+ import { type Hex } from "viem";
12
+ import {
13
+ privateKeyToAccount,
14
+ sign as viemSign,
15
+ serializeSignature,
16
+ } from "viem/accounts";
17
+
18
+ /** Abstract signer interface. */
19
+ export interface Signer {
20
+ /** Sign a 32-byte hash. Returns 65-byte signature (r || s || v). */
21
+ sign(hash: Uint8Array): Uint8Array;
22
+ /** The signer's Ethereum address (0x-prefixed, checksummed). */
23
+ readonly address: string;
24
+ }
25
+
26
+ /** Signs via the `pay sign` CLI subprocess. */
27
+ export class CliSigner implements Signer {
28
+ private readonly command: string;
29
+ readonly address: string;
30
+
31
+ constructor(command = "pay", address = "") {
32
+ this.command = command;
33
+ if (address) {
34
+ this.address = address;
35
+ } else {
36
+ try {
37
+ this.address = execFileSync(this.command, ["address"], {
38
+ encoding: "utf-8",
39
+ timeout: 10_000,
40
+ }).trim();
41
+ } catch {
42
+ this.address = "";
43
+ }
44
+ }
45
+ }
46
+
47
+ sign(hash: Uint8Array): Uint8Array {
48
+ const hexHash = Buffer.from(hash).toString("hex");
49
+ const result = execFileSync(this.command, ["sign"], {
50
+ input: hexHash,
51
+ encoding: "utf-8",
52
+ timeout: 30_000,
53
+ });
54
+ return Buffer.from(result.trim(), "hex");
55
+ }
56
+ }
57
+
58
+ /** Signs with a raw private key using viem. Dev/testing only. */
59
+ export class RawKeySigner implements Signer {
60
+ private readonly _key: Hex;
61
+ readonly address: string;
62
+
63
+ constructor(key?: string) {
64
+ const rawKey = key ?? process.env.PAYSKILL_KEY ?? "";
65
+ if (!rawKey) {
66
+ throw new Error("No key provided and PAYSKILL_KEY not set");
67
+ }
68
+ this._key = rawKey.startsWith("0x")
69
+ ? (rawKey as Hex)
70
+ : (`0x${rawKey}` as Hex);
71
+ const account = privateKeyToAccount(this._key);
72
+ this.address = account.address;
73
+ }
74
+
75
+ sign(_hash: Uint8Array): Uint8Array {
76
+ // viem's sign() does raw ECDSA signing (no EIP-191 prefix)
77
+ // sign() is async but Signer interface is sync — we use the sync internal
78
+ // For the sync interface, we need a workaround. Since RawKeySigner is
79
+ // dev/testing only, we'll do a sync computation via signSync.
80
+ // viem doesn't expose sync sign, but we can construct manually.
81
+ // Use the async path via signAsync helper pattern.
82
+ throw new Error(
83
+ "RawKeySigner.sign() is synchronous but viem signing is async. " +
84
+ "Use RawKeySigner.signAsync() or use buildAuthHeaders() directly with the private key."
85
+ );
86
+ }
87
+
88
+ /** Async sign — preferred over sync sign(). */
89
+ async signAsync(hash: Uint8Array): Promise<Uint8Array> {
90
+ const hashHex = ("0x" + Buffer.from(hash).toString("hex")) as Hex;
91
+ const raw = await viemSign({ hash: hashHex, privateKey: this._key });
92
+ const sigHex = serializeSignature(raw);
93
+ return hexToBytes(sigHex);
94
+ }
95
+ }
96
+
97
+ /** Delegates signing to a user-provided callback. */
98
+ export class CallbackSigner implements Signer {
99
+ private readonly callback: (hash: Uint8Array) => Uint8Array;
100
+ readonly address: string;
101
+
102
+ constructor(
103
+ callback: (hash: Uint8Array) => Uint8Array,
104
+ address = ""
105
+ ) {
106
+ this.callback = callback;
107
+ this.address = address;
108
+ }
109
+
110
+ sign(hash: Uint8Array): Uint8Array {
111
+ return this.callback(hash);
112
+ }
113
+ }
114
+
115
+ /** Factory for creating signers. */
116
+ export function createSigner(
117
+ mode: "cli" | "raw" | "custom" = "cli",
118
+ options: {
119
+ command?: string;
120
+ key?: string;
121
+ address?: string;
122
+ callback?: (hash: Uint8Array) => Uint8Array;
123
+ } = {}
124
+ ): Signer {
125
+ switch (mode) {
126
+ case "cli":
127
+ return new CliSigner(options.command, options.address);
128
+ case "raw":
129
+ return new RawKeySigner(options.key);
130
+ case "custom":
131
+ if (!options.callback) {
132
+ throw new Error("custom signer requires a callback");
133
+ }
134
+ return new CallbackSigner(options.callback, options.address);
135
+ default:
136
+ throw new Error(`Unknown signer mode: ${mode as string}`);
137
+ }
138
+ }
139
+
140
+ function hexToBytes(hex: string): Uint8Array {
141
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
142
+ const bytes = new Uint8Array(clean.length / 2);
143
+ for (let i = 0; i < bytes.length; i++) {
144
+ bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
145
+ }
146
+ return bytes;
147
+ }