@capxul/mcp 1.0.0-alpha.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.
@@ -0,0 +1,2 @@
1
+ import { r as fetchCommitmentCreatedLog } from "./alchemy-rpc-DEpqt2Jx.mjs";
2
+ export { fetchCommitmentCreatedLog };
@@ -0,0 +1,323 @@
1
+ import { H as ENTRY_POINT_07_ADDRESS, b as CAPXUL_PAYMENTS_ADDRESS, lt as Errors, x as CAPXUL_PAYMENTS_COMMITMENT_ABI } from "./src-CJVATdCb.mjs";
2
+ import { decodeFunctionResult, encodeFunctionData, isHex, toHex } from "viem";
3
+ //#region ../../packages/backend/convex/_shared/env.ts
4
+ function requireEnvOrThrow(name) {
5
+ const value = process.env[name];
6
+ if (!value || value.length === 0) throw Errors.envMissing(name);
7
+ return value;
8
+ }
9
+ function optionalEnv(name) {
10
+ const value = process.env[name];
11
+ return value && value.length > 0 ? value : void 0;
12
+ }
13
+ //#endregion
14
+ //#region ../../packages/backend/convex/_shared/alchemyRpc.ts
15
+ const TX_HASH_HEX = /^0x[0-9a-fA-F]{64}$/;
16
+ function rethrowProvider(method) {
17
+ return (e) => {
18
+ throw Errors.providerError("alchemy", method, e);
19
+ };
20
+ }
21
+ function parseAlchemyQuantity(value, operation, field) {
22
+ try {
23
+ return BigInt(value);
24
+ } catch (cause) {
25
+ throw Errors.providerError("alchemy", `${operation} ${field}`, `invalid ${field} ${value} (${String(cause)})`);
26
+ }
27
+ }
28
+ /**
29
+ * Construct the Alchemy URL for a given chain. Single endpoint for both
30
+ * node (eth_*) and bundler (eth_getUserOperationReceipt) RPCs — Alchemy
31
+ * routes by method.
32
+ */
33
+ function alchemyUrl(chainId) {
34
+ switch (chainId) {
35
+ case 84532: {
36
+ const baseSepoliaRpcUrl = optionalEnv("BASE_SEPOLIA_RPC_URL");
37
+ if (baseSepoliaRpcUrl !== void 0) return baseSepoliaRpcUrl.replace(/\/+$/, "");
38
+ return `https://base-sepolia.g.alchemy.com/v2/${requireEnvOrThrow("ALCHEMY_API_KEY")}`;
39
+ }
40
+ case 8453: return `https://base-mainnet.g.alchemy.com/v2/${requireEnvOrThrow("ALCHEMY_API_KEY")}`;
41
+ default: throw Errors.invalidInput("chainId", `unsupported chainId ${String(chainId)}`);
42
+ }
43
+ }
44
+ async function alchemyRpc(chainId, method, params) {
45
+ const url = alchemyUrl(chainId);
46
+ const res = await fetch(url, {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/json" },
49
+ body: JSON.stringify({
50
+ jsonrpc: "2.0",
51
+ id: 1,
52
+ method,
53
+ params
54
+ })
55
+ }).catch(rethrowProvider(method));
56
+ if (!res.ok) {
57
+ const body = await res.text().catch(() => "<no body>");
58
+ throw Errors.providerError("alchemy", `${method} ${res.status}`, body);
59
+ }
60
+ let json;
61
+ try {
62
+ json = await res.json();
63
+ } catch (cause) {
64
+ throw Errors.providerError("alchemy", `${method} json`, cause);
65
+ }
66
+ if (json.error !== void 0) throw Errors.providerError("alchemy", method, json.error.message);
67
+ if (json.result === void 0) throw Errors.providerError("alchemy", method, "missing result");
68
+ return json.result;
69
+ }
70
+ function parseReceiptLogs(raw) {
71
+ if (raw === void 0 || raw === null) return [];
72
+ if (!Array.isArray(raw)) throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", "logs is not an array");
73
+ return raw.map((entry) => {
74
+ if (typeof entry !== "object" || entry === null || typeof entry.address !== "string" || !Array.isArray(entry.topics) || typeof entry.data !== "string") throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", `malformed receipt log: ${JSON.stringify(entry)}`);
75
+ const log = entry;
76
+ return {
77
+ address: log.address,
78
+ topics: log.topics.map((t) => {
79
+ if (typeof t !== "string") throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", "non-string log topic");
80
+ return t;
81
+ }),
82
+ data: log.data,
83
+ ...typeof log.logIndex === "string" ? { logIndex: hexToSafeInteger(log.logIndex, "eth_getUserOperationReceipt") } : {}
84
+ };
85
+ });
86
+ }
87
+ async function fetchUserOperationReceipt(args) {
88
+ const raw = await alchemyRpc(args.chainId, "eth_getUserOperationReceipt", [args.userOpHash]);
89
+ if (raw === null) return null;
90
+ if (typeof raw !== "object" || typeof raw.userOpHash !== "string" || typeof raw.sender !== "string" || typeof raw.success !== "boolean" || typeof raw.receipt !== "object" || typeof raw.receipt.blockNumber !== "string" || typeof raw.receipt.transactionHash !== "string") throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", `unexpected shape: ${JSON.stringify(raw)}`);
91
+ return {
92
+ userOpHash: raw.userOpHash,
93
+ sender: raw.sender,
94
+ success: raw.success,
95
+ receipt: {
96
+ blockNumber: hexToSafeInteger(raw.receipt.blockNumber, "eth_getUserOperationReceipt"),
97
+ transactionHash: raw.receipt.transactionHash,
98
+ logs: parseReceiptLogs(raw.receipt.logs)
99
+ }
100
+ };
101
+ }
102
+ /**
103
+ * Parse a hex-encoded JSON-RPC integer into a safe JS number. Throws
104
+ * `Errors.providerError` if the value exceeds `Number.MAX_SAFE_INTEGER`
105
+ * (would silently round under `parseInt` per `.claude/rules/numeric-parsing.md`).
106
+ */
107
+ function hexToSafeInteger(hex, op) {
108
+ if (typeof hex !== "string" || !hex.startsWith("0x")) throw Errors.providerError("alchemy", op, `expected 0x-prefixed hex, got ${String(hex)}`);
109
+ let big;
110
+ try {
111
+ big = BigInt(hex);
112
+ } catch (cause) {
113
+ throw Errors.providerError("alchemy", op, `invalid hex integer: ${hex} (${String(cause)})`);
114
+ }
115
+ const n = Number(big);
116
+ if (!Number.isSafeInteger(n)) throw Errors.providerError("alchemy", op, `hex value ${hex} exceeds MAX_SAFE_INTEGER`);
117
+ return n;
118
+ }
119
+ /**
120
+ * Read an ERC-20 `balanceOf(holder)` via `eth_call` (canon §2 — RPC pull, no
121
+ * indexer). Returns the raw on-chain integer as a base-10 string so the SDK
122
+ * boundary owns the `fromWei` lift into a `Money` (canon §10). A `bigint`-safe
123
+ * string is returned rather than a `number` because token balances routinely
124
+ * exceed `Number.MAX_SAFE_INTEGER`.
125
+ */
126
+ async function fetchErc20Balance(args) {
127
+ const BALANCE_OF_SELECTOR = "0x70a08231";
128
+ const holderHex = args.holderAddress.toLowerCase().replace(/^0x/, "");
129
+ if (!/^[0-9a-f]{40}$/.test(holderHex)) throw Errors.invalidInput("holderAddress", "must be 0x + 40 hex chars");
130
+ const calldata = `${BALANCE_OF_SELECTOR}${"0".repeat(24)}${holderHex}`;
131
+ const raw = await alchemyRpc(args.chainId, "eth_call", [{
132
+ to: args.tokenAddress,
133
+ data: calldata
134
+ }, "latest"]);
135
+ if (typeof raw !== "string" || !raw.startsWith("0x")) throw Errors.providerError("alchemy", "eth_call", `unexpected shape: ${String(raw)}`);
136
+ if (raw === "0x") throw Errors.providerError("alchemy", "eth_call", "empty balanceOf return (0x)");
137
+ let big;
138
+ try {
139
+ big = BigInt(raw);
140
+ } catch (cause) {
141
+ throw Errors.providerError("alchemy", "eth_call", `invalid balanceOf hex: ${raw} (${String(cause)})`);
142
+ }
143
+ return { rawBalance: big.toString(10) };
144
+ }
145
+ /**
146
+ * Look up the first `CapxulPayments.CommitmentCreated` log emitted by a given
147
+ * creator at/after `fromBlock` (G3 · #546). The event is:
148
+ *
149
+ * event CommitmentCreated(uint256 indexed id, address indexed creator,
150
+ * address indexed recipient, address token, uint256 totalAmount,
151
+ * uint48 startTime, uint48 cliffTime, uint48 endTime, bytes32 documentHash,
152
+ * uint8 paymentType);
153
+ *
154
+ * `id` is the indexed first topic (`topics[1]`); `creator` is `topics[2]`.
155
+ * Filtering by `[topic0, null, paddedCreator]` narrows to this creator's
156
+ * commitments — the caller decodes `topics[1]` as the commitment id.
157
+ */
158
+ async function fetchCommitmentCreatedLog(args) {
159
+ const creatorHex = args.creatorAddress.toLowerCase().replace(/^0x/, "");
160
+ if (!/^[0-9a-f]{40}$/.test(creatorHex)) throw Errors.invalidInput("creatorAddress", "must be 0x + 40 hex chars");
161
+ const paddedCreatorTopic = `0x${"0".repeat(24)}${creatorHex}`;
162
+ const logs = await alchemyRpc(args.chainId, "eth_getLogs", [{
163
+ address: args.contractAddress,
164
+ topics: [
165
+ args.topic0,
166
+ null,
167
+ paddedCreatorTopic
168
+ ],
169
+ fromBlock: `0x${args.fromBlock.toString(16)}`,
170
+ toBlock: "latest"
171
+ }]);
172
+ if (!Array.isArray(logs)) throw Errors.providerError("alchemy", "eth_getLogs", "expected array");
173
+ for (const log of logs) {
174
+ if (typeof log.blockNumber !== "string" || typeof log.transactionHash !== "string") throw Errors.providerError("alchemy", "eth_getLogs", `malformed log entry: ${JSON.stringify(log)}`);
175
+ return {
176
+ address: log.address,
177
+ topics: log.topics,
178
+ data: log.data,
179
+ blockNumber: hexToSafeInteger(log.blockNumber, "eth_getLogs"),
180
+ transactionHash: log.transactionHash
181
+ };
182
+ }
183
+ return null;
184
+ }
185
+ /**
186
+ * Read the on-chain `commitments(id)` struct from CapxulPayments via `eth_call`.
187
+ * Used to bind lifecycle evidence (claim/cancel/redirect) to the actual on-chain
188
+ * STATE — `requireSuccessfulUserOp` proves a UserOp succeeded from the expected
189
+ * Safe, but only this state read proves the UserOp performed the expected op on
190
+ * THIS commitment id. A never-created id reads back as the zero struct (creator
191
+ * == address(0)), so callers must treat a zero `creator` as "not found".
192
+ */
193
+ async function fetchCommitmentState(args) {
194
+ const data = encodeFunctionData({
195
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
196
+ functionName: "commitments",
197
+ args: [args.onchainCommitmentId]
198
+ });
199
+ const raw = await alchemyRpc(args.chainId, "eth_call", [{
200
+ to: CAPXUL_PAYMENTS_ADDRESS,
201
+ data
202
+ }, "latest"]);
203
+ if (typeof raw !== "string" || !raw.startsWith("0x")) throw Errors.providerError("alchemy", "eth_call commitments", `unexpected shape: ${String(raw)}`);
204
+ if (raw === "0x") throw Errors.providerError("alchemy", "eth_call commitments", "empty commitments() return (0x)");
205
+ let decoded;
206
+ try {
207
+ decoded = decodeFunctionResult({
208
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
209
+ functionName: "commitments",
210
+ data: raw
211
+ });
212
+ } catch (cause) {
213
+ throw Errors.providerError("alchemy", "eth_call commitments", `decode failed: ${String(cause)}`);
214
+ }
215
+ const [creator, token, recipient, totalAmount, claimed, startTime, cliffTime, endTime, documentHash, paymentType, cancelled] = decoded;
216
+ return {
217
+ creator,
218
+ token,
219
+ recipient,
220
+ totalAmount,
221
+ claimed,
222
+ startTime: Number(startTime),
223
+ cliffTime: Number(cliffTime),
224
+ endTime: Number(endTime),
225
+ documentHash,
226
+ paymentType: Number(paymentType),
227
+ cancelled
228
+ };
229
+ }
230
+ const getNonceAbi = [{
231
+ type: "function",
232
+ name: "getNonce",
233
+ stateMutability: "view",
234
+ inputs: [{
235
+ name: "sender",
236
+ type: "address"
237
+ }, {
238
+ name: "key",
239
+ type: "uint192"
240
+ }],
241
+ outputs: [{
242
+ name: "nonce",
243
+ type: "uint256"
244
+ }]
245
+ }];
246
+ const EIP1559_BASE_FEE_BUFFER_MULTIPLIER = 2n;
247
+ /** Read the EntryPoint v0.7 nonce (key 0) for a sender — 0 for a fresh account. */
248
+ async function fetchEntryPointNonce(args) {
249
+ const data = encodeFunctionData({
250
+ abi: getNonceAbi,
251
+ functionName: "getNonce",
252
+ args: [args.sender, 0n]
253
+ });
254
+ const result = await alchemyRpc(args.chainId, "eth_call", [{
255
+ to: ENTRY_POINT_07_ADDRESS,
256
+ data
257
+ }, "latest"]);
258
+ try {
259
+ return BigInt(result);
260
+ } catch (cause) {
261
+ throw Errors.providerError("alchemy", "eth_call getNonce", `invalid nonce ${result} (${String(cause)})`);
262
+ }
263
+ }
264
+ /** EIP-1559 max + priority fees with a 2x base-fee inclusion buffer. */
265
+ async function fetchUserOperationFees(args) {
266
+ const priority = parseAlchemyQuantity(await alchemyRpc(args.chainId, "eth_maxPriorityFeePerGas", []), "eth_maxPriorityFeePerGas", "maxPriorityFeePerGas");
267
+ const block = await alchemyRpc(args.chainId, "eth_getBlockByNumber", ["latest", false]);
268
+ if (block.baseFeePerGas === void 0) {
269
+ const blockRef = block.number ?? block.hash ?? "<unknown>";
270
+ throw Errors.providerError("alchemy", "eth_getBlockByNumber baseFeePerGas", `missing baseFeePerGas in latest block ${blockRef}: ${JSON.stringify(block)}`);
271
+ }
272
+ return {
273
+ maxFeePerGas: parseAlchemyQuantity(block.baseFeePerGas, "eth_getBlockByNumber", "baseFeePerGas") * EIP1559_BASE_FEE_BUFFER_MULTIPLIER + priority,
274
+ maxPriorityFeePerGas: priority
275
+ };
276
+ }
277
+ async function estimateUserOperationGas(args) {
278
+ const raw = await alchemyRpc(args.chainId, "eth_estimateUserOperationGas", [args.userOp, ENTRY_POINT_07_ADDRESS]);
279
+ if (typeof raw !== "object" || typeof raw.preVerificationGas !== "string" || typeof raw.verificationGasLimit !== "string" || typeof raw.callGasLimit !== "string") throw Errors.providerError("alchemy", "eth_estimateUserOperationGas", `unexpected shape: ${JSON.stringify(raw)}`);
280
+ return raw;
281
+ }
282
+ function optionalPaymasterHex(raw, method, field) {
283
+ const value = raw[field];
284
+ if (value === void 0) return void 0;
285
+ if (typeof value !== "string" || !isHex(value)) throw Errors.providerError("alchemy", method, `unexpected ${field}: expected hex string`);
286
+ return value;
287
+ }
288
+ async function paymasterRpc(method, args) {
289
+ const raw = await alchemyRpc(args.chainId, method, [
290
+ args.userOp,
291
+ ENTRY_POINT_07_ADDRESS,
292
+ toHex(args.chainId),
293
+ { policyId: args.policyId }
294
+ ]);
295
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw Errors.providerError("alchemy", method, `unexpected shape: ${JSON.stringify(raw)}`);
296
+ const result = raw;
297
+ const paymaster = optionalPaymasterHex(result, method, "paymaster");
298
+ const paymasterData = optionalPaymasterHex(result, method, "paymasterData");
299
+ const paymasterVerificationGasLimit = optionalPaymasterHex(result, method, "paymasterVerificationGasLimit");
300
+ const paymasterPostOpGasLimit = optionalPaymasterHex(result, method, "paymasterPostOpGasLimit");
301
+ return {
302
+ ...paymaster === void 0 ? {} : { paymaster },
303
+ ...paymasterData === void 0 ? {} : { paymasterData },
304
+ ...paymasterVerificationGasLimit === void 0 ? {} : { paymasterVerificationGasLimit },
305
+ ...paymasterPostOpGasLimit === void 0 ? {} : { paymasterPostOpGasLimit }
306
+ };
307
+ }
308
+ /** ERC-7677 stub paymaster data (for gas estimation). */
309
+ function getPaymasterStubData(args) {
310
+ return paymasterRpc("pm_getPaymasterStubData", args);
311
+ }
312
+ /** ERC-7677 final paymaster data (after gas estimation). */
313
+ function getPaymasterData(args) {
314
+ return paymasterRpc("pm_getPaymasterData", args);
315
+ }
316
+ /** Submit the signed UserOperation through the bundler — returns the userOpHash. */
317
+ async function sendUserOperation(args) {
318
+ const hash = await alchemyRpc(args.chainId, "eth_sendUserOperation", [args.userOp, ENTRY_POINT_07_ADDRESS]);
319
+ if (typeof hash !== "string" || !TX_HASH_HEX.test(hash)) throw Errors.providerError("alchemy", "eth_sendUserOperation", `unexpected hash: ${String(hash)}; expected 0x-prefixed 32-byte hex`);
320
+ return hash;
321
+ }
322
+ //#endregion
323
+ export { fetchEntryPointNonce as a, fetchUserOperationReceipt as c, sendUserOperation as d, fetchCommitmentState as i, getPaymasterData as l, estimateUserOperationGas as n, fetchErc20Balance as o, fetchCommitmentCreatedLog as r, fetchUserOperationFees as s, alchemyUrl as t, getPaymasterStubData as u };
@@ -0,0 +1,34 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
27
+ };
28
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
+ value: mod,
31
+ enumerable: true
32
+ }) : target, mod));
33
+ //#endregion
34
+ export { __toESM as i, __exportAll as n, __reExport as r, __commonJSMin as t };