@capxul/mcp 1.0.0-alpha.16 → 1.0.0-alpha.18

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.
@@ -1,4 +1,4 @@
1
- import { concat, encodeAbiParameters, encodeFunctionData, encodePacked, getContractAddress, hashTypedData, isAddress, keccak256, pad, padHex, parseAbiParameters, stringToHex, toBytes, toHex } from "viem";
1
+ import { concat, encodeAbiParameters, encodeFunctionData, encodePacked, getContractAddress, hashTypedData, isAddress, keccak256, pad, padHex, parseAbiParameters, stringToHex, toBytes, toEventSelector, toFunctionSelector, toHex } from "viem";
2
2
  //#region ../../packages/errors/src/errors.ts
3
3
  const CAPXUL_ERROR_CODES = [
4
4
  "NOT_AUTHENTICATED",
@@ -156,8 +156,8 @@ const Errors = {
156
156
  * Method called from a flow state where its precondition fails (TA16). The
157
157
  * SDK's method API short-circuits with this error before driving the
158
158
  * internal state machine. `currentState` is the Effect-machine snapshot
159
- * tag (stringified — substrate is `@effect/experimental/Machine` per
160
- * `docs/canon/decisions/state-machine-substrate.md`); `validStates`
159
+ * tag (stringified — substrate is `@effect/experimental/Machine`; see
160
+ * `packages/errors/CONTEXT.md`); `validStates`
161
161
  * enumerates the states the method accepts.
162
162
  */
163
163
  wrongState: (details) => new CapxulError("WRONG_STATE", `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(", ")}`, { details: {
@@ -212,122 +212,62 @@ function isExactTransferTokenAllowed(tokenAddress) {
212
212
  return EXACT_TRANSFER_TOKEN_ALLOWLIST.includes(tokenAddress.toLowerCase());
213
213
  }
214
214
  //#endregion
215
- //#region ../../packages/config/src/safe.ts
216
- const BASE_SEPOLIA_CHAIN_ID = 84532;
217
- const SAFE_PROXY_FACTORY = "0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67";
218
- const SAFE_L2_SINGLETON = "0x29fcB43b46531BcA003ddC8FCB67FFE91900C762";
219
- const SAFE_MODULE_SETUP = "0x2dd68b007B46fBe91B9A7c3EDa5A7a1063cB5b47";
220
- const SAFE_4337_MODULE = "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226";
221
- const MULTI_SEND = "0x38869bf66a61cF6bDB996A6aE40D5853Fd43B526";
222
- /**
223
- * Canonical personal-Safe salt namespace — **v2** (PRD #462). v2 derives the
224
- * address from the email ONLY: the initializer's sole owner is the fixed
225
- * `CAPXUL_BOOTSTRAP_OWNER`, so the address exists before any user signer does
226
- * and can never rotate with one. The user's signer is installed at claim time
227
- * via `swapOwner` (see `capxulClaimOwnerCallData`).
228
- */
229
- const CAPXUL_SAFE_SALT_NAMESPACE = "capxul:safe:email:v2";
230
- /**
231
- * The Capxul bootstrap owner — the sole `setup()` owner of every unclaimed
232
- * personal Safe under derivation v2. This address is part of the CREATE2
233
- * preimage of EVERY personal Safe address: treat it exactly like
234
- * `SAFE_PROXY_FACTORY` (changing it is a derivation-version event → v3).
235
- * The private key lives backend-only (`CAPXUL_BOOTSTRAP_OWNER_PRIVATE_KEY`)
236
- * and signs exactly one kind of operation: the claim userOp that deploys the
237
- * Safe and swaps this owner out for the user's signer (PRD #462). The earlier
238
- * ClaimGuard derivation-v3 placeholder (#461) is closed; future mainnet-scale
239
- * hardening should be filed against the current payments/claim architecture.
240
- */
241
- const CAPXUL_BOOTSTRAP_OWNER = "0x425fca96f4a3e18fb80974e38096b5da460f2704";
242
- const UINT48_MAX = 0xffffffffffff;
243
- const SAFE_PROXY_CREATION_CODE = "0x608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea264697066735822122003d1488ee65e08fa41e58e888a9865554c535f2c77126a82cb4c0f917f31441364736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564";
244
- /**
245
- * Normalize an email for use as a Capxul Safe salt input.
246
- *
247
- * Trims surrounding whitespace and lowercases the address so that
248
- * `" User+Demo@Example.COM "` and `"user+demo@example.com"` derive
249
- * the same `safeAddress`. This is the canonical normalization rule —
250
- * any future change here would shift every existing user's Safe
251
- * address, so the rule is pinned by the fixture matrix in
252
- * `packages/config/tests/safe-address-conformance.test.ts`.
253
- *
254
- * @param email - The raw email address to normalize
255
- * @returns The trimmed, lowercased email
256
- */
257
- function normalizeSafeSaltEmail(email) {
258
- return email.trim().toLowerCase();
259
- }
260
- /**
261
- * Compute the deterministic Safe salt nonce for a `(namespace, email)`
262
- * pair. The salt nonce is the `bigint` reading of
263
- * `keccak256(namespace + ":" + normalizeSafeSaltEmail(email))`.
264
- *
265
- * Namespace defaults to `CAPXUL_SAFE_SALT_NAMESPACE`
266
- * (`"capxul:safe:email:v2"`) — the per-version Capxul scheme. Pass a
267
- * different namespace only for pinned pre-v2 artifacts
268
- * (`CAPXUL_SAFE_SALT_NAMESPACE_V1`, faucet Safe) or when bumping the scheme.
269
- *
270
- * @param input.email - The email to derive the salt nonce from
271
- * @param input.namespace - Optional namespace override (defaults to `CAPXUL_SAFE_SALT_NAMESPACE`)
272
- * @returns The Capxul-namespaced salt nonce as a `bigint`
273
- */
274
- function computeCapxulSafeSaltNonce(input) {
275
- const namespace = input.namespace ?? "capxul:safe:email:v2";
276
- const normalizedEmail = normalizeSafeSaltEmail(input.email);
277
- return BigInt(keccak256(toBytes(`${namespace}:${normalizedEmail}`)));
278
- }
279
- const ZERO_ADDRESS$1 = "0x0000000000000000000000000000000000000000";
280
- const safeSetupAbi$1 = [{
215
+ //#region ../../packages/config/src/org-payments.ts
216
+ /** Zodiac MultiSendCallOnly module on Base Sepolia. */
217
+ const MULTI_SEND_CALL_ONLY = "0x9641d764fc13c8b624c04430c7356c1c7c8102e2";
218
+ /** Zodiac Roles v2 mastercopy on Base Sepolia. */
219
+ const ROLES_MASTERCOPY = "0x9646fdad06d3e24444381f44362a3b0eb343d337";
220
+ /** Zodiac ModuleProxyFactory on Base Sepolia. */
221
+ const ZODIAC_MODULE_PROXY_FACTORY = "0x000000000000addb49795b0f9ba5bc298cdda236";
222
+ /** Zodiac MultiSend unwrapper on Base Sepolia. */
223
+ const ZODIAC_MULTI_SEND_UNWRAPPER = "0x93b7fcbc63ed8a3a24b59e1c3e6649d50b7427c0";
224
+ /** CapxulPayments proxy on Base Sepolia. */
225
+ const CAPXUL_PAYMENTS_ADDRESS = "0xe740ea65521edc9bef0ea75d30b5334711db99f4";
226
+ const CAPXUL_PAYMENTS_SEND_ABI = [{
281
227
  type: "function",
282
- name: "setup",
228
+ name: "send",
283
229
  stateMutability: "nonpayable",
284
230
  inputs: [
285
231
  {
286
- name: "_owners",
287
- type: "address[]"
288
- },
289
- {
290
- name: "_threshold",
291
- type: "uint256"
292
- },
293
- {
294
- name: "to",
232
+ name: "token",
295
233
  type: "address"
296
234
  },
297
235
  {
298
- name: "data",
299
- type: "bytes"
300
- },
301
- {
302
- name: "fallbackHandler",
236
+ name: "recipient",
303
237
  type: "address"
304
238
  },
305
239
  {
306
- name: "paymentToken",
307
- type: "address"
240
+ name: "amount",
241
+ type: "uint256"
308
242
  },
309
243
  {
310
- name: "payment",
311
- type: "uint256"
244
+ name: "documentHash",
245
+ type: "bytes32"
312
246
  },
313
247
  {
314
- name: "paymentReceiver",
315
- type: "address"
248
+ name: "paymentType",
249
+ type: "uint8"
316
250
  }
317
251
  ],
318
252
  outputs: []
319
253
  }];
320
- const enableModulesAbi$1 = [{
254
+ const ERC20_APPROVE_ABI = [{
321
255
  type: "function",
322
- name: "enableModules",
256
+ name: "approve",
323
257
  stateMutability: "nonpayable",
324
258
  inputs: [{
325
- name: "modules",
326
- type: "address[]"
259
+ name: "spender",
260
+ type: "address"
261
+ }, {
262
+ name: "amount",
263
+ type: "uint256"
327
264
  }],
328
- outputs: []
265
+ outputs: [{
266
+ name: "",
267
+ type: "bool"
268
+ }]
329
269
  }];
330
- const multiSendAbi$1 = [{
270
+ const MULTI_SEND_CALL_ONLY_ABI = [{
331
271
  type: "function",
332
272
  name: "multiSend",
333
273
  stateMutability: "payable",
@@ -337,299 +277,657 @@ const multiSendAbi$1 = [{
337
277
  }],
338
278
  outputs: []
339
279
  }];
340
- function buildCapxulSafeInitializer(owner) {
341
- const enableModulesCall = encodeFunctionData({
342
- abi: enableModulesAbi$1,
343
- functionName: "enableModules",
344
- args: [[SAFE_4337_MODULE]]
345
- });
346
- const setupData = encodeFunctionData({
347
- abi: multiSendAbi$1,
348
- functionName: "multiSend",
349
- args: [encodePacked([
350
- "uint8",
351
- "address",
352
- "uint256",
353
- "uint256",
354
- "bytes"
355
- ], [
356
- 1,
357
- SAFE_MODULE_SETUP,
358
- 0n,
359
- BigInt((enableModulesCall.length - 2) / 2),
360
- enableModulesCall
361
- ])]
362
- });
363
- return encodeFunctionData({
364
- abi: safeSetupAbi$1,
365
- functionName: "setup",
366
- args: [
367
- [owner],
368
- 1n,
369
- MULTI_SEND,
370
- setupData,
371
- SAFE_4337_MODULE,
372
- ZERO_ADDRESS$1,
373
- 0n,
374
- ZERO_ADDRESS$1
375
- ]
376
- });
280
+ const ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI$1 = [{
281
+ type: "function",
282
+ name: "execTransactionWithRole",
283
+ stateMutability: "nonpayable",
284
+ inputs: [
285
+ {
286
+ name: "to",
287
+ type: "address"
288
+ },
289
+ {
290
+ name: "value",
291
+ type: "uint256"
292
+ },
293
+ {
294
+ name: "data",
295
+ type: "bytes"
296
+ },
297
+ {
298
+ name: "operation",
299
+ type: "uint8"
300
+ },
301
+ {
302
+ name: "roleKey",
303
+ type: "bytes32"
304
+ },
305
+ {
306
+ name: "shouldRevert",
307
+ type: "bool"
308
+ }
309
+ ],
310
+ outputs: [{
311
+ name: "success",
312
+ type: "bool"
313
+ }]
314
+ }];
315
+ const SAFE4337_EXECUTE_USEROP_ABI = [{
316
+ type: "function",
317
+ name: "executeUserOpWithErrorString",
318
+ stateMutability: "nonpayable",
319
+ inputs: [
320
+ {
321
+ name: "to",
322
+ type: "address"
323
+ },
324
+ {
325
+ name: "value",
326
+ type: "uint256"
327
+ },
328
+ {
329
+ name: "data",
330
+ type: "bytes"
331
+ },
332
+ {
333
+ name: "operation",
334
+ type: "uint8"
335
+ }
336
+ ],
337
+ outputs: []
338
+ }];
339
+ const OPERATION_CALL = 0;
340
+ const OPERATION_DELEGATECALL = 1;
341
+ const BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;
342
+ function normalizeAddress(address, field) {
343
+ if (!isAddress(address)) throw new RangeError(`${field} must be a valid EVM address`);
344
+ return address.toLowerCase();
377
345
  }
378
- const ADDRESS_REGEX$1 = /^0x[0-9a-fA-F]{40}$/;
379
- function validateAndNormalizeAddress(field, value) {
380
- const address = value.toLowerCase();
381
- if (!ADDRESS_REGEX$1.test(address)) throw Errors.invalidInput(field, `must be 0x + 40 hex chars, got ${value}`);
382
- return address;
346
+ function normalizeBytes32(value, field) {
347
+ if (!BYTES32_RE.test(value)) throw new RangeError(`${field} must be a 32-byte 0x-prefixed hex string`);
348
+ return value.toLowerCase();
383
349
  }
384
- /**
385
- * Pure derivation of the Capxul personal Safe address — **v2: email only**
386
- * (PRD #462). The Safe v1.4.1 (SafeL2) + 4337-module initializer's sole owner
387
- * is the fixed `CAPXUL_BOOTSTRAP_OWNER`, so the address is a pure function of
388
- * the (normalized) email and exists before any user signer does. The user's
389
- * signer is installed at claim time via `swapOwner` — signer rotation can
390
- * never move the address (org-domain rule D7, now system-wide).
391
- *
392
- * Returns the lowercased `0x` + 40 hex string (raw — no brand applied so this
393
- * function is callable from both `@capxul/config` consumers that don't have
394
- * `@capxul/types` available, and from packages that re-brand at their own
395
- * boundary).
396
- *
397
- * Algorithm: exactly mirrors `permissionless.toSafeSmartAccount({ version:
398
- * "1.4.1", safeSingletonAddress: SAFE_L2_SINGLETON, owners: [BOOTSTRAP] })`
399
- * + the Capxul-canonical module setup (delegatecall into
400
- * `SafeModuleSetup.enableModules([SAFE_4337_MODULE])` via the MultiSend lane
401
- * during proxy setup). The proxy creation code is pinned at
402
- * `SAFE_PROXY_CREATION_CODE`; the salt is Capxul-namespaced (v2) via
403
- * `computeCapxulSafeSaltNonce({ email })`.
404
- *
405
- * Canonical: SDK deployment adapters and
406
- * `packages/backend/convex/smartAccount/mutations.ts:provision` import this
407
- * function; the conformance test at
408
- * `packages/config/tests/safe-address-conformance.test.ts` pins the matrix.
350
+ function normalizeUint8(value, field) {
351
+ if (!Number.isInteger(value) || value < 0 || value > 255) throw new RangeError(`${field} must be an integer between 0 and 255`);
352
+ return value;
353
+ }
354
+ function normalizePositiveAmount(value, field) {
355
+ if (value <= 0n) throw new RangeError(`${field} must be positive`);
356
+ return value;
357
+ }
358
+ function buildCapxulPaymentsSendCalls(input) {
359
+ const tokenAddress = normalizeAddress(input.tokenAddress, "tokenAddress");
360
+ const recipientAddress = normalizeAddress(input.recipientAddress, "recipientAddress");
361
+ const amount = normalizePositiveAmount(input.amount, "amount");
362
+ const documentHash = normalizeBytes32(input.documentHash ?? `0x${"0".repeat(64)}`, "documentHash");
363
+ const paymentType = normalizeUint8(input.paymentType ?? 0, "paymentType");
364
+ return [{
365
+ to: tokenAddress,
366
+ data: encodeFunctionData({
367
+ abi: ERC20_APPROVE_ABI,
368
+ functionName: "approve",
369
+ args: [CAPXUL_PAYMENTS_ADDRESS, amount]
370
+ }),
371
+ value: 0n
372
+ }, {
373
+ to: CAPXUL_PAYMENTS_ADDRESS,
374
+ data: encodeFunctionData({
375
+ abi: CAPXUL_PAYMENTS_SEND_ABI,
376
+ functionName: "send",
377
+ args: [
378
+ tokenAddress,
379
+ recipientAddress,
380
+ amount,
381
+ documentHash,
382
+ paymentType
383
+ ]
384
+ }),
385
+ value: 0n
386
+ }];
387
+ }
388
+ function buildCapxulCreateCommitmentCalls(input) {
389
+ const tokenAddress = normalizeAddress(input.tokenAddress, "tokenAddress");
390
+ const recipientAddress = normalizeAddress(input.recipientAddress, "recipientAddress");
391
+ const totalAmount = normalizePositiveAmount(input.totalAmount, "totalAmount");
392
+ const startTime = normalizeUint48(input.startTime, "startTime");
393
+ const cliffTime = normalizeUint48(input.cliffTime, "cliffTime");
394
+ const endTime = normalizeUint48(input.endTime, "endTime");
395
+ if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) throw new RangeError("commitment times must satisfy start <= cliff <= end");
396
+ const documentHash = normalizeBytes32(input.documentHash ?? `0x${"0".repeat(64)}`, "documentHash");
397
+ const paymentType = normalizeUint8(input.paymentType ?? 0, "paymentType");
398
+ return [{
399
+ to: tokenAddress,
400
+ data: encodeFunctionData({
401
+ abi: ERC20_APPROVE_ABI,
402
+ functionName: "approve",
403
+ args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount]
404
+ }),
405
+ value: 0n
406
+ }, {
407
+ to: CAPXUL_PAYMENTS_ADDRESS,
408
+ data: encodeFunctionData({
409
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
410
+ functionName: "createCommitment",
411
+ args: [
412
+ tokenAddress,
413
+ recipientAddress,
414
+ totalAmount,
415
+ startTime,
416
+ cliffTime,
417
+ endTime,
418
+ documentHash,
419
+ paymentType
420
+ ]
421
+ }),
422
+ value: 0n
423
+ }];
424
+ }
425
+ /**
426
+ * Wrap an org Roles `execTransactionWithRole` call (from `*RoleSpendCall` /
427
+ * `*RoleBatchSpendCall`) into the member Safe's `executeUserOpWithErrorString`
428
+ * (operation = CALL into the Roles module) — the full Safe callData a sponsored
429
+ * UserOp from the member's personal Safe carries (G4 · #547).
409
430
  */
410
- function deriveCapxulSafeAddress(input) {
411
- return deriveCapxulSafeAddressForOwner({
412
- ownerAddress: CAPXUL_BOOTSTRAP_OWNER,
413
- email: input.email
431
+ function buildOrgRoleSpendPersonalCallData(roleSpendCall) {
432
+ return encodeFunctionData({
433
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
434
+ functionName: "executeUserOpWithErrorString",
435
+ args: [
436
+ normalizeAddress(roleSpendCall.to, "rolesModuleAddress"),
437
+ 0n,
438
+ roleSpendCall.data,
439
+ OPERATION_CALL
440
+ ]
414
441
  });
415
442
  }
416
443
  /**
417
- * Owner-parametrized derivation core. Two callers only:
418
- * 1. `deriveCapxulSafeAddress` (canonical v2: owner = bootstrap, namespace v2);
419
- * 2. the backend faucet Safe (`testUsdcMint.ts`: owner = deployer EOA,
420
- * namespace pinned to `CAPXUL_SAFE_SALT_NAMESPACE_V1` so its deployed
421
- * address never moves).
422
- * Do NOT introduce new owner-parametrized lanes — per-user owners in the
423
- * derivation is exactly the v1 mistake v2 removes.
444
+ * Wrap an ARBITRARY batch of calls into a member Safe's
445
+ * `executeUserOpWithErrorString` via a delegatecall into MultiSendCallOnly
446
+ * (G4 · #547 dev seam). Used by the dev MCP proof to drive the org's Zodiac
447
+ * Roles DEPLOY (deployModule + enableModule + setUpRoles) and role GRANT
448
+ * (assignRoles) as ONE sponsored UserOp from the founder's personal Safe —
449
+ * the same `buildSponsoredSafeUserOp` mechanism the spend path uses. A single
450
+ * call is still wrapped (MultiSend of length 1) so the caller need not branch.
424
451
  */
425
- function deriveCapxulSafeAddressForOwner(input) {
426
- const initializer = buildCapxulSafeInitializer(validateAndNormalizeAddress("ownerAddress", input.ownerAddress));
427
- const saltNonce = computeCapxulSafeSaltNonce(input.namespace === void 0 ? { email: input.email } : {
428
- email: input.email,
429
- namespace: input.namespace
452
+ function buildOrgPersonalMultiCallData(calls) {
453
+ if (calls.length === 0) throw new RangeError("multi-call batch must include at least one call");
454
+ return encodeFunctionData({
455
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
456
+ functionName: "executeUserOpWithErrorString",
457
+ args: [
458
+ MULTI_SEND_CALL_ONLY,
459
+ 0n,
460
+ encodeFunctionData({
461
+ abi: MULTI_SEND_CALL_ONLY_ABI,
462
+ functionName: "multiSend",
463
+ args: [concat(calls.map(encodeMultiSendCallTransaction))]
464
+ }),
465
+ OPERATION_DELEGATECALL
466
+ ]
430
467
  });
431
- return getContractAddress({
432
- opcode: "CREATE2",
433
- from: SAFE_PROXY_FACTORY,
434
- salt: keccak256(encodePacked(["bytes32", "uint256"], [keccak256(initializer), saltNonce])),
435
- bytecodeHash: keccak256(concat([SAFE_PROXY_CREATION_CODE, encodeAbiParameters([{ type: "uint256" }], [BigInt(SAFE_L2_SINGLETON)])]))
436
- }).toLowerCase();
437
468
  }
438
- /** Canonical ERC-4337 EntryPoint v0.7 address (same on every chain). */
439
- const ENTRY_POINT_07_ADDRESS = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
440
- /** EIP-712 `SafeOp` typed-data fields for EntryPoint v0.7 (Safe4337Module). */
441
- const EIP712_SAFE_OPERATION_TYPE_V07 = { SafeOp: [
442
- {
443
- type: "address",
444
- name: "safe"
445
- },
446
- {
447
- type: "uint256",
448
- name: "nonce"
449
- },
450
- {
451
- type: "bytes",
452
- name: "initCode"
453
- },
454
- {
455
- type: "bytes",
456
- name: "callData"
457
- },
458
- {
459
- type: "uint128",
460
- name: "verificationGasLimit"
461
- },
462
- {
463
- type: "uint128",
464
- name: "callGasLimit"
465
- },
466
- {
467
- type: "uint256",
468
- name: "preVerificationGas"
469
- },
469
+ /**
470
+ * Encode an org PAYROLL BATCH (G4 · #547): one `execTransactionWithRole`
471
+ * (the member's role key) → MultiSendCallOnly → N × (approve + CapxulPayments
472
+ * settlement call), one call per employee. Instant lines use `send`; scheduled
473
+ * and stream salary lines use `createCommitment`. Each line keeps its own
474
+ * recipient + amount, so each is bounded independently by the role's on-chain
475
+ * Zodiac conditions (per-tx cap, per-day allowance, allowed recipient). One
476
+ * sponsored UserOp settles the batch.
477
+ */
478
+ function buildCapxulPaymentsRoleBatchSpendCall(input) {
479
+ if (input.runs.length === 0) throw new RangeError("payroll batch must include at least one run");
480
+ const roleKey = normalizeBytes32(input.roleKey, "roleKey");
481
+ const paymentType = input.paymentType ?? 0;
482
+ const multiSendData = encodeFunctionData({
483
+ abi: MULTI_SEND_CALL_ONLY_ABI,
484
+ functionName: "multiSend",
485
+ args: [concat(input.runs.flatMap((run) => {
486
+ if (run.timing !== void 0) return [...buildCapxulCreateCommitmentCalls({
487
+ tokenAddress: input.tokenAddress,
488
+ recipientAddress: run.recipientAddress,
489
+ totalAmount: run.amount,
490
+ startTime: run.timing.startTime,
491
+ cliffTime: run.timing.cliffTime,
492
+ endTime: run.timing.endTime,
493
+ paymentType,
494
+ ...run.documentHash === void 0 ? {} : { documentHash: run.documentHash }
495
+ })];
496
+ return [...buildCapxulPaymentsSendCalls({
497
+ tokenAddress: input.tokenAddress,
498
+ recipientAddress: run.recipientAddress,
499
+ amount: run.amount,
500
+ paymentType,
501
+ ...run.documentHash === void 0 ? {} : { documentHash: run.documentHash }
502
+ })];
503
+ }).map(encodeMultiSendCallTransaction))]
504
+ });
505
+ return {
506
+ to: normalizeAddress(input.rolesModuleAddress, "rolesModuleAddress"),
507
+ data: encodeFunctionData({
508
+ abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI$1,
509
+ functionName: "execTransactionWithRole",
510
+ args: [
511
+ MULTI_SEND_CALL_ONLY,
512
+ 0n,
513
+ multiSendData,
514
+ OPERATION_DELEGATECALL,
515
+ roleKey,
516
+ true
517
+ ]
518
+ }),
519
+ value: 0n
520
+ };
521
+ }
522
+ function encodeMultiSendCallTransaction(call) {
523
+ return encodePacked([
524
+ "uint8",
525
+ "address",
526
+ "uint256",
527
+ "uint256",
528
+ "bytes"
529
+ ], [
530
+ OPERATION_CALL,
531
+ call.to,
532
+ call.value,
533
+ BigInt((call.data.length - 2) / 2),
534
+ call.data
535
+ ]);
536
+ }
537
+ /**
538
+ * Encode a personal Safe's `executeUserOpWithErrorString` callData that pays via
539
+ * CapxulPayments in one UserOp: approve + send batched through a delegatecall
540
+ * into MultiSendCallOnly. The Safe4337Module invokes this on the Safe; the
541
+ * MultiSend then CALLs each sub-transaction from the Safe's own context.
542
+ */
543
+ function buildCapxulPaymentsPersonalSendCallData(input) {
544
+ return encodeFunctionData({
545
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
546
+ functionName: "executeUserOpWithErrorString",
547
+ args: [
548
+ MULTI_SEND_CALL_ONLY,
549
+ 0n,
550
+ encodeFunctionData({
551
+ abi: MULTI_SEND_CALL_ONLY_ABI,
552
+ functionName: "multiSend",
553
+ args: [concat(buildCapxulPaymentsSendCalls(input).map(encodeMultiSendCallTransaction))]
554
+ }),
555
+ OPERATION_DELEGATECALL
556
+ ]
557
+ });
558
+ }
559
+ const CAPXUL_PAYMENTS_COMMITMENT_ABI = [
470
560
  {
471
- type: "uint128",
472
- name: "maxPriorityFeePerGas"
561
+ type: "function",
562
+ name: "createCommitment",
563
+ stateMutability: "nonpayable",
564
+ inputs: [
565
+ {
566
+ name: "token",
567
+ type: "address"
568
+ },
569
+ {
570
+ name: "recipient",
571
+ type: "address"
572
+ },
573
+ {
574
+ name: "totalAmount",
575
+ type: "uint256"
576
+ },
577
+ {
578
+ name: "startTime",
579
+ type: "uint48"
580
+ },
581
+ {
582
+ name: "cliffTime",
583
+ type: "uint48"
584
+ },
585
+ {
586
+ name: "endTime",
587
+ type: "uint48"
588
+ },
589
+ {
590
+ name: "documentHash",
591
+ type: "bytes32"
592
+ },
593
+ {
594
+ name: "paymentType",
595
+ type: "uint8"
596
+ }
597
+ ],
598
+ outputs: [{
599
+ name: "commitmentId",
600
+ type: "uint256"
601
+ }]
473
602
  },
474
603
  {
475
- type: "uint128",
476
- name: "maxFeePerGas"
604
+ type: "function",
605
+ name: "claim",
606
+ stateMutability: "nonpayable",
607
+ inputs: [{
608
+ name: "commitmentId",
609
+ type: "uint256"
610
+ }],
611
+ outputs: []
477
612
  },
478
613
  {
479
- type: "bytes",
480
- name: "paymasterAndData"
614
+ type: "function",
615
+ name: "cancel",
616
+ stateMutability: "nonpayable",
617
+ inputs: [{
618
+ name: "commitmentId",
619
+ type: "uint256"
620
+ }, {
621
+ name: "documentHash",
622
+ type: "bytes32"
623
+ }],
624
+ outputs: []
481
625
  },
482
626
  {
483
- type: "uint48",
484
- name: "validAfter"
627
+ type: "function",
628
+ name: "redirect",
629
+ stateMutability: "nonpayable",
630
+ inputs: [
631
+ {
632
+ name: "commitmentId",
633
+ type: "uint256"
634
+ },
635
+ {
636
+ name: "newRecipient",
637
+ type: "address"
638
+ },
639
+ {
640
+ name: "newDocumentHash",
641
+ type: "bytes32"
642
+ }
643
+ ],
644
+ outputs: []
485
645
  },
486
646
  {
487
- type: "uint48",
488
- name: "validUntil"
647
+ type: "function",
648
+ name: "claimableAmount",
649
+ stateMutability: "view",
650
+ inputs: [{
651
+ name: "commitmentId",
652
+ type: "uint256"
653
+ }],
654
+ outputs: [{
655
+ name: "",
656
+ type: "uint256"
657
+ }]
489
658
  },
490
659
  {
491
- type: "address",
492
- name: "entryPoint"
660
+ type: "function",
661
+ name: "commitments",
662
+ stateMutability: "view",
663
+ inputs: [{
664
+ name: "",
665
+ type: "uint256"
666
+ }],
667
+ outputs: [
668
+ {
669
+ name: "creator",
670
+ type: "address"
671
+ },
672
+ {
673
+ name: "token",
674
+ type: "address"
675
+ },
676
+ {
677
+ name: "recipient",
678
+ type: "address"
679
+ },
680
+ {
681
+ name: "totalAmount",
682
+ type: "uint256"
683
+ },
684
+ {
685
+ name: "claimed",
686
+ type: "uint256"
687
+ },
688
+ {
689
+ name: "startTime",
690
+ type: "uint48"
691
+ },
692
+ {
693
+ name: "cliffTime",
694
+ type: "uint48"
695
+ },
696
+ {
697
+ name: "endTime",
698
+ type: "uint48"
699
+ },
700
+ {
701
+ name: "documentHash",
702
+ type: "bytes32"
703
+ },
704
+ {
705
+ name: "paymentType",
706
+ type: "uint8"
707
+ },
708
+ {
709
+ name: "cancelled",
710
+ type: "bool"
711
+ }
712
+ ]
493
713
  }
494
- ] };
495
- /** Pack EntryPoint v0.7 `factory` + `factoryData` into the SafeOp `initCode`. */
496
- function safe4337InitCode(userOp) {
497
- if (userOp.factory === void 0 || userOp.factory === "0x") return "0x";
498
- return concat([userOp.factory, userOp.factoryData ?? "0x"]);
499
- }
500
- /** Pack EntryPoint v0.7 unpacked paymaster fields into SafeOp `paymasterAndData`. */
501
- function safe4337PaymasterAndData(userOp) {
502
- if (userOp.paymaster === void 0 || userOp.paymaster === "0x") return "0x";
503
- return concat([
504
- userOp.paymaster,
505
- pad(toHex(userOp.paymasterVerificationGasLimit ?? 0n), { size: 16 }),
506
- pad(toHex(userOp.paymasterPostOpGasLimit ?? 0n), { size: 16 }),
507
- userOp.paymasterData ?? "0x"
508
- ]);
714
+ ];
715
+ function normalizeUint48(value, field) {
716
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffffffff) throw new RangeError(`${field} must be a uint48 (epoch seconds)`);
717
+ return value;
509
718
  }
510
719
  /**
511
- * Compute the EIP-712 `SafeOp` digest the Safe4337Module owner must sign for a
512
- * prepared deployment UserOperation. The `CapxulSigner` signs THIS digest.
720
+ * Encode a personal Safe's `createCommitment` UserOp: approve + createCommitment
721
+ * batched through a delegatecall into MultiSendCallOnly (one sponsored UserOp).
722
+ * The creator (payer Safe) escrows `totalAmount` into CapxulPayments.
513
723
  */
514
- function safe4337SafeOpDigest(input) {
515
- return hashTypedData({
516
- domain: {
517
- chainId: input.chainId,
518
- verifyingContract: input.safe4337ModuleAddress ?? "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226"
519
- },
520
- types: EIP712_SAFE_OPERATION_TYPE_V07,
521
- primaryType: "SafeOp",
522
- message: {
523
- safe: input.userOp.sender,
524
- nonce: input.userOp.nonce,
525
- initCode: safe4337InitCode(input.userOp),
526
- callData: input.userOp.callData,
527
- verificationGasLimit: input.userOp.verificationGasLimit,
528
- callGasLimit: input.userOp.callGasLimit,
529
- preVerificationGas: input.userOp.preVerificationGas,
530
- maxPriorityFeePerGas: input.userOp.maxPriorityFeePerGas,
531
- maxFeePerGas: input.userOp.maxFeePerGas,
532
- paymasterAndData: safe4337PaymasterAndData(input.userOp),
533
- validAfter: input.validAfter ?? 0,
534
- validUntil: input.validUntil ?? 0,
535
- entryPoint: input.entryPointAddress ?? "0x0000000071727De22E5E9d8BAf0edAc6f37da032"
536
- }
724
+ function buildCapxulCreateCommitmentPersonalCallData(input) {
725
+ const tokenAddress = normalizeAddress(input.tokenAddress, "tokenAddress");
726
+ const recipientAddress = normalizeAddress(input.recipientAddress, "recipientAddress");
727
+ const totalAmount = normalizePositiveAmount(input.totalAmount, "totalAmount");
728
+ const startTime = normalizeUint48(input.startTime, "startTime");
729
+ const cliffTime = normalizeUint48(input.cliffTime, "cliffTime");
730
+ const endTime = normalizeUint48(input.endTime, "endTime");
731
+ if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) throw new RangeError("commitment times must satisfy start <= cliff <= end");
732
+ const documentHash = normalizeBytes32(input.documentHash ?? `0x${"0".repeat(64)}`, "documentHash");
733
+ const paymentType = normalizeUint8(input.paymentType ?? 0, "paymentType");
734
+ return encodeFunctionData({
735
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
736
+ functionName: "executeUserOpWithErrorString",
737
+ args: [
738
+ MULTI_SEND_CALL_ONLY,
739
+ 0n,
740
+ encodeFunctionData({
741
+ abi: MULTI_SEND_CALL_ONLY_ABI,
742
+ functionName: "multiSend",
743
+ args: [concat([{
744
+ to: tokenAddress,
745
+ data: encodeFunctionData({
746
+ abi: ERC20_APPROVE_ABI,
747
+ functionName: "approve",
748
+ args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount]
749
+ }),
750
+ value: 0n
751
+ }, {
752
+ to: CAPXUL_PAYMENTS_ADDRESS,
753
+ data: encodeFunctionData({
754
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
755
+ functionName: "createCommitment",
756
+ args: [
757
+ tokenAddress,
758
+ recipientAddress,
759
+ totalAmount,
760
+ startTime,
761
+ cliffTime,
762
+ endTime,
763
+ documentHash,
764
+ paymentType
765
+ ]
766
+ }),
767
+ value: 0n
768
+ }].map(encodeMultiSendCallTransaction))]
769
+ }),
770
+ OPERATION_DELEGATECALL
771
+ ]
537
772
  });
538
773
  }
539
- /** Pack a single-owner ECDSA signature into the Safe4337 UserOp signature. */
540
- function packSafe4337OwnerSignature(input) {
541
- assertUint48(input.validAfter ?? 0, "validAfter");
542
- assertUint48(input.validUntil ?? 0, "validUntil");
543
- return encodePacked([
544
- "uint48",
545
- "uint48",
546
- "bytes"
547
- ], [
548
- input.validAfter ?? 0,
549
- input.validUntil ?? 0,
550
- input.signature
551
- ]);
774
+ function buildSingleCapxulPaymentsCallData(data) {
775
+ return encodeFunctionData({
776
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
777
+ functionName: "executeUserOpWithErrorString",
778
+ args: [
779
+ CAPXUL_PAYMENTS_ADDRESS,
780
+ 0n,
781
+ data,
782
+ OPERATION_CALL
783
+ ]
784
+ });
552
785
  }
553
- function assertUint48(value, field) {
554
- if (!Number.isSafeInteger(value) || value < 0 || value > UINT48_MAX) throw Errors.invalidInput(field, `must fit uint48 (0..${UINT48_MAX})`);
786
+ /** Encode a recipient Safe's `claim(commitmentId)` UserOp callData. */
787
+ function buildCapxulCommitmentClaimCallData(commitmentId) {
788
+ return buildSingleCapxulPaymentsCallData(encodeFunctionData({
789
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
790
+ functionName: "claim",
791
+ args: [commitmentId]
792
+ }));
555
793
  }
556
- const SAFE4337_STUB_OWNER_ECDSA = "0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c";
557
- /**
558
- * Packed Safe4337 stub signature (single static owner) for gas estimation —
559
- * byte-for-byte equal to permissionless's `getStubSignature()`.
560
- */
561
- function safe4337StubSignature() {
562
- return packSafe4337OwnerSignature({ signature: SAFE4337_STUB_OWNER_ECDSA });
794
+ /** Encode a creator Safe's `cancel(commitmentId, documentHash)` UserOp callData. */
795
+ function buildCapxulCommitmentCancelCallData(commitmentId, documentHash) {
796
+ return buildSingleCapxulPaymentsCallData(encodeFunctionData({
797
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
798
+ functionName: "cancel",
799
+ args: [commitmentId, normalizeBytes32(documentHash ?? `0x${"0".repeat(64)}`, "documentHash")]
800
+ }));
801
+ }
802
+ /** Encode a creator Safe's `redirect(commitmentId, newRecipient, newDocumentHash)` UserOp callData. */
803
+ function buildCapxulCommitmentRedirectCallData(commitmentId, newRecipient, newDocumentHash) {
804
+ return buildSingleCapxulPaymentsCallData(encodeFunctionData({
805
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
806
+ functionName: "redirect",
807
+ args: [
808
+ commitmentId,
809
+ normalizeAddress(newRecipient, "newRecipient"),
810
+ normalizeBytes32(newDocumentHash ?? `0x${"0".repeat(64)}`, "newDocumentHash")
811
+ ]
812
+ }));
563
813
  }
564
814
  //#endregion
565
- //#region ../../packages/config/src/binding.ts
566
- /** Openfort `thirdPartyUserId` namespace for email bindings (epic #331 / #332). */
567
- const CAPXUL_BINDING_EMAIL_NAMESPACE = "capxul:binding:email:v1";
815
+ //#region ../../packages/config/src/safe.ts
816
+ const BASE_SEPOLIA_CHAIN_ID = 84532;
817
+ const SAFE_PROXY_FACTORY = "0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67";
818
+ const SAFE_L2_SINGLETON = "0x29fcB43b46531BcA003ddC8FCB67FFE91900C762";
819
+ const SAFE_MODULE_SETUP = "0x2dd68b007B46fBe91B9A7c3EDa5A7a1063cB5b47";
820
+ const SAFE_4337_MODULE = "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226";
821
+ const MULTI_SEND = "0x38869bf66a61cF6bDB996A6aE40D5853Fd43B526";
822
+ /**
823
+ * Canonical personal-Safe salt namespace — **v2** (PRD #462). v2 derives the
824
+ * address from the email ONLY: the initializer's sole owner is the fixed
825
+ * `CAPXUL_BOOTSTRAP_OWNER`, so the address exists before any user signer does
826
+ * and can never rotate with one. The user's signer is installed at claim time
827
+ * via `swapOwner` (see `capxulClaimOwnerCallData`).
828
+ */
829
+ const CAPXUL_SAFE_SALT_NAMESPACE = "capxul:safe:email:v2";
830
+ /**
831
+ * The Capxul bootstrap owner — the sole `setup()` owner of every unclaimed
832
+ * personal Safe under derivation v2. This address is part of the CREATE2
833
+ * preimage of EVERY personal Safe address: treat it exactly like
834
+ * `SAFE_PROXY_FACTORY` (changing it is a derivation-version event → v3).
835
+ * The private key lives backend-only (`CAPXUL_BOOTSTRAP_OWNER_PRIVATE_KEY`)
836
+ * and signs exactly one kind of operation: the claim userOp that deploys the
837
+ * Safe and swaps this owner out for the user's signer (PRD #462). The earlier
838
+ * ClaimGuard derivation-v3 placeholder (#461) is closed; future mainnet-scale
839
+ * hardening should be filed against the current payments/claim architecture.
840
+ */
841
+ const CAPXUL_BOOTSTRAP_OWNER = "0x425fca96f4a3e18fb80974e38096b5da460f2704";
842
+ const UINT48_MAX = 0xffffffffffff;
843
+ const SAFE_PROXY_CREATION_CODE = "0x608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea264697066735822122003d1488ee65e08fa41e58e888a9865554c535f2c77126a82cb4c0f917f31441364736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564";
844
+ /**
845
+ * Normalize an email for use as a Capxul Safe salt input.
846
+ *
847
+ * Trims surrounding whitespace and lowercases the address so that
848
+ * `" User+Demo@Example.COM "` and `"user+demo@example.com"` derive
849
+ * the same `safeAddress`. This is the canonical normalization rule —
850
+ * any future change here would shift every existing user's Safe
851
+ * address, so the rule is pinned by the fixture matrix in
852
+ * `packages/config/tests/safe-address-conformance.test.ts`.
853
+ *
854
+ * @param email - The raw email address to normalize
855
+ * @returns The trimmed, lowercased email
856
+ */
857
+ function normalizeSafeSaltEmail(email) {
858
+ return email.trim().toLowerCase();
859
+ }
568
860
  /**
569
- * Normalize a raw email for binding id + Safe salt derivation.
570
- * Delegates to {@link normalizeSafeSaltEmail} so binding resolution and
571
- * `deriveCapxulSafeAddress` never drift apart.
861
+ * Compute the deterministic Safe salt nonce for a `(namespace, email)`
862
+ * pair. The salt nonce is the `bigint` reading of
863
+ * `keccak256(namespace + ":" + normalizeSafeSaltEmail(email))`.
864
+ *
865
+ * Namespace defaults to `CAPXUL_SAFE_SALT_NAMESPACE`
866
+ * (`"capxul:safe:email:v2"`) — the per-version Capxul scheme. Pass a
867
+ * different namespace only for pinned pre-v2 artifacts
868
+ * (`CAPXUL_SAFE_SALT_NAMESPACE_V1`, faucet Safe) or when bumping the scheme.
869
+ *
870
+ * @param input.email - The email to derive the salt nonce from
871
+ * @param input.namespace - Optional namespace override (defaults to `CAPXUL_SAFE_SALT_NAMESPACE`)
872
+ * @returns The Capxul-namespaced salt nonce as a `bigint`
572
873
  */
573
- function normalizeBindingEmail(email) {
574
- return normalizeSafeSaltEmail(email);
874
+ function computeCapxulSafeSaltNonce(input) {
875
+ const namespace = input.namespace ?? "capxul:safe:email:v2";
876
+ const normalizedEmail = normalizeSafeSaltEmail(input.email);
877
+ return BigInt(keccak256(toBytes(`${namespace}:${normalizedEmail}`)));
575
878
  }
576
- //#endregion
577
- //#region ../../packages/config/src/org-payments.ts
578
- /** Zodiac MultiSendCallOnly module on Base Sepolia. */
579
- const MULTI_SEND_CALL_ONLY = "0x9641d764fc13c8b624c04430c7356c1c7c8102e2";
580
- /** Zodiac Roles v2 mastercopy on Base Sepolia. */
581
- const ROLES_MASTERCOPY = "0x9646fdad06d3e24444381f44362a3b0eb343d337";
582
- /** Zodiac ModuleProxyFactory on Base Sepolia. */
583
- const ZODIAC_MODULE_PROXY_FACTORY = "0x000000000000addb49795b0f9ba5bc298cdda236";
584
- /** Zodiac MultiSend unwrapper on Base Sepolia. */
585
- const ZODIAC_MULTI_SEND_UNWRAPPER = "0x93b7fcbc63ed8a3a24b59e1c3e6649d50b7427c0";
586
- /** CapxulPayments proxy on Base Sepolia. */
587
- const CAPXUL_PAYMENTS_ADDRESS = "0xe740ea65521edc9bef0ea75d30b5334711db99f4";
588
- const CAPXUL_PAYMENTS_SEND_ABI = [{
879
+ const ZERO_ADDRESS$1 = "0x0000000000000000000000000000000000000000";
880
+ const safeSetupAbi$1 = [{
589
881
  type: "function",
590
- name: "send",
882
+ name: "setup",
591
883
  stateMutability: "nonpayable",
592
884
  inputs: [
593
885
  {
594
- name: "token",
886
+ name: "_owners",
887
+ type: "address[]"
888
+ },
889
+ {
890
+ name: "_threshold",
891
+ type: "uint256"
892
+ },
893
+ {
894
+ name: "to",
595
895
  type: "address"
596
896
  },
597
897
  {
598
- name: "recipient",
898
+ name: "data",
899
+ type: "bytes"
900
+ },
901
+ {
902
+ name: "fallbackHandler",
599
903
  type: "address"
600
904
  },
601
905
  {
602
- name: "amount",
603
- type: "uint256"
906
+ name: "paymentToken",
907
+ type: "address"
604
908
  },
605
909
  {
606
- name: "documentHash",
607
- type: "bytes32"
910
+ name: "payment",
911
+ type: "uint256"
608
912
  },
609
913
  {
610
- name: "paymentType",
611
- type: "uint8"
914
+ name: "paymentReceiver",
915
+ type: "address"
612
916
  }
613
917
  ],
614
918
  outputs: []
615
919
  }];
616
- const ERC20_APPROVE_ABI = [{
920
+ const enableModulesAbi$1 = [{
617
921
  type: "function",
618
- name: "approve",
922
+ name: "enableModules",
619
923
  stateMutability: "nonpayable",
620
924
  inputs: [{
621
- name: "spender",
622
- type: "address"
623
- }, {
624
- name: "amount",
625
- type: "uint256"
925
+ name: "modules",
926
+ type: "address[]"
626
927
  }],
627
- outputs: [{
628
- name: "",
629
- type: "bool"
630
- }]
928
+ outputs: []
631
929
  }];
632
- const MULTI_SEND_CALL_ONLY_ABI = [{
930
+ const multiSendAbi$1 = [{
633
931
  type: "function",
634
932
  name: "multiSend",
635
933
  stateMutability: "payable",
@@ -639,10 +937,10 @@ const MULTI_SEND_CALL_ONLY_ABI = [{
639
937
  }],
640
938
  outputs: []
641
939
  }];
642
- const ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI$1 = [{
940
+ const safeExecTransactionAbi = [{
643
941
  type: "function",
644
- name: "execTransactionWithRole",
645
- stateMutability: "nonpayable",
942
+ name: "execTransaction",
943
+ stateMutability: "payable",
646
944
  inputs: [
647
945
  {
648
946
  name: "to",
@@ -661,227 +959,70 @@ const ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI$1 = [{
661
959
  type: "uint8"
662
960
  },
663
961
  {
664
- name: "roleKey",
665
- type: "bytes32"
962
+ name: "safeTxGas",
963
+ type: "uint256"
666
964
  },
667
965
  {
668
- name: "shouldRevert",
669
- type: "bool"
670
- }
671
- ],
672
- outputs: [{
673
- name: "success",
674
- type: "bool"
675
- }]
676
- }];
677
- const SAFE4337_EXECUTE_USEROP_ABI = [{
678
- type: "function",
679
- name: "executeUserOpWithErrorString",
680
- stateMutability: "nonpayable",
681
- inputs: [
682
- {
683
- name: "to",
684
- type: "address"
966
+ name: "baseGas",
967
+ type: "uint256"
685
968
  },
686
969
  {
687
- name: "value",
970
+ name: "gasPrice",
688
971
  type: "uint256"
689
972
  },
690
973
  {
691
- name: "data",
692
- type: "bytes"
974
+ name: "gasToken",
975
+ type: "address"
693
976
  },
694
977
  {
695
- name: "operation",
696
- type: "uint8"
978
+ name: "refundReceiver",
979
+ type: "address"
980
+ },
981
+ {
982
+ name: "signatures",
983
+ type: "bytes"
697
984
  }
698
985
  ],
699
- outputs: []
700
- }];
701
- const OPERATION_CALL = 0;
702
- const OPERATION_DELEGATECALL = 1;
703
- const BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;
704
- function normalizeAddress(address, field) {
705
- if (!isAddress(address)) throw new RangeError(`${field} must be a valid EVM address`);
706
- return address.toLowerCase();
707
- }
708
- function normalizeBytes32(value, field) {
709
- if (!BYTES32_RE.test(value)) throw new RangeError(`${field} must be a 32-byte 0x-prefixed hex string`);
710
- return value.toLowerCase();
711
- }
712
- function normalizeUint8(value, field) {
713
- if (!Number.isInteger(value) || value < 0 || value > 255) throw new RangeError(`${field} must be an integer between 0 and 255`);
714
- return value;
715
- }
716
- function normalizePositiveAmount(value, field) {
717
- if (value <= 0n) throw new RangeError(`${field} must be positive`);
718
- return value;
719
- }
720
- function buildCapxulPaymentsSendCalls(input) {
721
- const tokenAddress = normalizeAddress(input.tokenAddress, "tokenAddress");
722
- const recipientAddress = normalizeAddress(input.recipientAddress, "recipientAddress");
723
- const amount = normalizePositiveAmount(input.amount, "amount");
724
- const documentHash = normalizeBytes32(input.documentHash ?? `0x${"0".repeat(64)}`, "documentHash");
725
- const paymentType = normalizeUint8(input.paymentType ?? 0, "paymentType");
726
- return [{
727
- to: tokenAddress,
728
- data: encodeFunctionData({
729
- abi: ERC20_APPROVE_ABI,
730
- functionName: "approve",
731
- args: [CAPXUL_PAYMENTS_ADDRESS, amount]
732
- }),
733
- value: 0n
734
- }, {
735
- to: CAPXUL_PAYMENTS_ADDRESS,
736
- data: encodeFunctionData({
737
- abi: CAPXUL_PAYMENTS_SEND_ABI,
738
- functionName: "send",
739
- args: [
740
- tokenAddress,
741
- recipientAddress,
742
- amount,
743
- documentHash,
744
- paymentType
745
- ]
746
- }),
747
- value: 0n
748
- }];
749
- }
750
- function buildCapxulCreateCommitmentCalls(input) {
751
- const tokenAddress = normalizeAddress(input.tokenAddress, "tokenAddress");
752
- const recipientAddress = normalizeAddress(input.recipientAddress, "recipientAddress");
753
- const totalAmount = normalizePositiveAmount(input.totalAmount, "totalAmount");
754
- const startTime = normalizeUint48(input.startTime, "startTime");
755
- const cliffTime = normalizeUint48(input.cliffTime, "cliffTime");
756
- const endTime = normalizeUint48(input.endTime, "endTime");
757
- if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) throw new RangeError("commitment times must satisfy start <= cliff <= end");
758
- const documentHash = normalizeBytes32(input.documentHash ?? `0x${"0".repeat(64)}`, "documentHash");
759
- const paymentType = normalizeUint8(input.paymentType ?? 0, "paymentType");
760
- return [{
761
- to: tokenAddress,
762
- data: encodeFunctionData({
763
- abi: ERC20_APPROVE_ABI,
764
- functionName: "approve",
765
- args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount]
766
- }),
767
- value: 0n
768
- }, {
769
- to: CAPXUL_PAYMENTS_ADDRESS,
770
- data: encodeFunctionData({
771
- abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
772
- functionName: "createCommitment",
773
- args: [
774
- tokenAddress,
775
- recipientAddress,
776
- totalAmount,
777
- startTime,
778
- cliffTime,
779
- endTime,
780
- documentHash,
781
- paymentType
782
- ]
783
- }),
784
- value: 0n
785
- }];
786
- }
787
- /**
788
- * Wrap an org Roles `execTransactionWithRole` call (from `*RoleSpendCall` /
789
- * `*RoleBatchSpendCall`) into the member Safe's `executeUserOpWithErrorString`
790
- * (operation = CALL into the Roles module) — the full Safe callData a sponsored
791
- * UserOp from the member's personal Safe carries (G4 · #547).
792
- */
793
- function buildOrgRoleSpendPersonalCallData(roleSpendCall) {
794
- return encodeFunctionData({
795
- abi: SAFE4337_EXECUTE_USEROP_ABI,
796
- functionName: "executeUserOpWithErrorString",
797
- args: [
798
- normalizeAddress(roleSpendCall.to, "rolesModuleAddress"),
799
- 0n,
800
- roleSpendCall.data,
801
- OPERATION_CALL
802
- ]
803
- });
804
- }
805
- /**
806
- * Wrap an ARBITRARY batch of calls into a member Safe's
807
- * `executeUserOpWithErrorString` via a delegatecall into MultiSendCallOnly
808
- * (G4 · #547 dev seam). Used by the dev MCP proof to drive the org's Zodiac
809
- * Roles DEPLOY (deployModule + enableModule + setUpRoles) and role GRANT
810
- * (assignRoles) as ONE sponsored UserOp from the founder's personal Safe —
811
- * the same `buildSponsoredSafeUserOp` mechanism the spend path uses. A single
812
- * call is still wrapped (MultiSend of length 1) so the caller need not branch.
813
- */
814
- function buildOrgPersonalMultiCallData(calls) {
815
- if (calls.length === 0) throw new RangeError("multi-call batch must include at least one call");
816
- return encodeFunctionData({
817
- abi: SAFE4337_EXECUTE_USEROP_ABI,
818
- functionName: "executeUserOpWithErrorString",
819
- args: [
820
- MULTI_SEND_CALL_ONLY,
821
- 0n,
822
- encodeFunctionData({
823
- abi: MULTI_SEND_CALL_ONLY_ABI,
824
- functionName: "multiSend",
825
- args: [concat(calls.map(encodeMultiSendCallTransaction))]
826
- }),
827
- OPERATION_DELEGATECALL
828
- ]
829
- });
830
- }
986
+ outputs: [{
987
+ name: "success",
988
+ type: "bool"
989
+ }]
990
+ }];
831
991
  /**
832
- * Encode an org PAYROLL BATCH (G4 · #547): one `execTransactionWithRole`
833
- * (the member's role key) → MultiSendCallOnly → N × (approve + CapxulPayments
834
- * settlement call), one call per employee. Instant lines use `send`; scheduled
835
- * and stream salary lines use `createCommitment`. Each line keeps its own
836
- * recipient + amount, so each is bounded independently by the role's on-chain
837
- * Zodiac conditions (per-tx cap, per-day allowance, allowed recipient). One
838
- * sponsored UserOp settles the batch.
992
+ * Encode ordered calls as one Safe `execTransaction` through MultiSend.
993
+ *
994
+ * The owner must approve the surrounding transaction, so this builder uses
995
+ * Safe's prevalidated-signature format and delegates the ordered calls through
996
+ * the canonical MultiSend contract.
839
997
  */
840
- function buildCapxulPaymentsRoleBatchSpendCall(input) {
841
- if (input.runs.length === 0) throw new RangeError("payroll batch must include at least one run");
842
- const roleKey = normalizeBytes32(input.roleKey, "roleKey");
843
- const paymentType = input.paymentType ?? 0;
998
+ function buildSafeMultiSendExecTransactionCall(input) {
844
999
  const multiSendData = encodeFunctionData({
845
- abi: MULTI_SEND_CALL_ONLY_ABI,
1000
+ abi: multiSendAbi$1,
846
1001
  functionName: "multiSend",
847
- args: [concat(input.runs.flatMap((run) => {
848
- if (run.timing !== void 0) return [...buildCapxulCreateCommitmentCalls({
849
- tokenAddress: input.tokenAddress,
850
- recipientAddress: run.recipientAddress,
851
- totalAmount: run.amount,
852
- startTime: run.timing.startTime,
853
- cliffTime: run.timing.cliffTime,
854
- endTime: run.timing.endTime,
855
- paymentType,
856
- ...run.documentHash === void 0 ? {} : { documentHash: run.documentHash }
857
- })];
858
- return [...buildCapxulPaymentsSendCalls({
859
- tokenAddress: input.tokenAddress,
860
- recipientAddress: run.recipientAddress,
861
- amount: run.amount,
862
- paymentType,
863
- ...run.documentHash === void 0 ? {} : { documentHash: run.documentHash }
864
- })];
865
- }).map(encodeMultiSendCallTransaction))]
1002
+ args: [concat(input.calls.map(encodeSafeMultiSendCallTransaction))]
866
1003
  });
867
1004
  return {
868
- to: normalizeAddress(input.rolesModuleAddress, "rolesModuleAddress"),
1005
+ to: input.safeAddress,
1006
+ value: 0n,
869
1007
  data: encodeFunctionData({
870
- abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI$1,
871
- functionName: "execTransactionWithRole",
1008
+ abi: safeExecTransactionAbi,
1009
+ functionName: "execTransaction",
872
1010
  args: [
873
- MULTI_SEND_CALL_ONLY,
1011
+ MULTI_SEND,
874
1012
  0n,
875
1013
  multiSendData,
876
- OPERATION_DELEGATECALL,
877
- roleKey,
878
- true
1014
+ 1,
1015
+ 0n,
1016
+ 0n,
1017
+ 0n,
1018
+ ZERO_ADDRESS$1,
1019
+ ZERO_ADDRESS$1,
1020
+ `${pad(input.ownerAddress, { size: 32 })}${"0".repeat(64)}01`
879
1021
  ]
880
- }),
881
- value: 0n
1022
+ })
882
1023
  };
883
1024
  }
884
- function encodeMultiSendCallTransaction(call) {
1025
+ function encodeSafeMultiSendCallTransaction(call) {
885
1026
  return encodePacked([
886
1027
  "uint8",
887
1028
  "address",
@@ -889,289 +1030,248 @@ function encodeMultiSendCallTransaction(call) {
889
1030
  "uint256",
890
1031
  "bytes"
891
1032
  ], [
892
- OPERATION_CALL,
1033
+ 0,
893
1034
  call.to,
894
1035
  call.value,
895
1036
  BigInt((call.data.length - 2) / 2),
896
1037
  call.data
897
1038
  ]);
898
1039
  }
899
- /**
900
- * Encode a personal Safe's `executeUserOpWithErrorString` callData that pays via
901
- * CapxulPayments in one UserOp: approve + send batched through a delegatecall
902
- * into MultiSendCallOnly. The Safe4337Module invokes this on the Safe; the
903
- * MultiSend then CALLs each sub-transaction from the Safe's own context.
904
- */
905
- function buildCapxulPaymentsPersonalSendCallData(input) {
1040
+ function buildCapxulSafeInitializer(owner) {
1041
+ const enableModulesCall = encodeFunctionData({
1042
+ abi: enableModulesAbi$1,
1043
+ functionName: "enableModules",
1044
+ args: [[SAFE_4337_MODULE]]
1045
+ });
1046
+ const setupData = encodeFunctionData({
1047
+ abi: multiSendAbi$1,
1048
+ functionName: "multiSend",
1049
+ args: [encodePacked([
1050
+ "uint8",
1051
+ "address",
1052
+ "uint256",
1053
+ "uint256",
1054
+ "bytes"
1055
+ ], [
1056
+ 1,
1057
+ SAFE_MODULE_SETUP,
1058
+ 0n,
1059
+ BigInt((enableModulesCall.length - 2) / 2),
1060
+ enableModulesCall
1061
+ ])]
1062
+ });
906
1063
  return encodeFunctionData({
907
- abi: SAFE4337_EXECUTE_USEROP_ABI,
908
- functionName: "executeUserOpWithErrorString",
1064
+ abi: safeSetupAbi$1,
1065
+ functionName: "setup",
909
1066
  args: [
910
- MULTI_SEND_CALL_ONLY,
1067
+ [owner],
1068
+ 1n,
1069
+ MULTI_SEND,
1070
+ setupData,
1071
+ SAFE_4337_MODULE,
1072
+ ZERO_ADDRESS$1,
911
1073
  0n,
912
- encodeFunctionData({
913
- abi: MULTI_SEND_CALL_ONLY_ABI,
914
- functionName: "multiSend",
915
- args: [concat(buildCapxulPaymentsSendCalls(input).map(encodeMultiSendCallTransaction))]
916
- }),
917
- OPERATION_DELEGATECALL
1074
+ ZERO_ADDRESS$1
918
1075
  ]
919
1076
  });
920
1077
  }
921
- const CAPXUL_PAYMENTS_COMMITMENT_ABI = [
1078
+ const ADDRESS_REGEX$1 = /^0x[0-9a-fA-F]{40}$/;
1079
+ function validateAndNormalizeAddress(field, value) {
1080
+ const address = value.toLowerCase();
1081
+ if (!ADDRESS_REGEX$1.test(address)) throw Errors.invalidInput(field, `must be 0x + 40 hex chars, got ${value}`);
1082
+ return address;
1083
+ }
1084
+ /**
1085
+ * Pure derivation of the Capxul personal Safe address — **v2: email only**
1086
+ * (PRD #462). The Safe v1.4.1 (SafeL2) + 4337-module initializer's sole owner
1087
+ * is the fixed `CAPXUL_BOOTSTRAP_OWNER`, so the address is a pure function of
1088
+ * the (normalized) email and exists before any user signer does. The user's
1089
+ * signer is installed at claim time via `swapOwner` — signer rotation can
1090
+ * never move the address (org-domain rule D7, now system-wide).
1091
+ *
1092
+ * Returns the lowercased `0x` + 40 hex string (raw — no brand applied so this
1093
+ * function is callable from both `@capxul/config` consumers that don't have
1094
+ * `@capxul/types` available, and from packages that re-brand at their own
1095
+ * boundary).
1096
+ *
1097
+ * Algorithm: exactly mirrors `permissionless.toSafeSmartAccount({ version:
1098
+ * "1.4.1", safeSingletonAddress: SAFE_L2_SINGLETON, owners: [BOOTSTRAP] })`
1099
+ * + the Capxul-canonical module setup (delegatecall into
1100
+ * `SafeModuleSetup.enableModules([SAFE_4337_MODULE])` via the MultiSend lane
1101
+ * during proxy setup). The proxy creation code is pinned at
1102
+ * `SAFE_PROXY_CREATION_CODE`; the salt is Capxul-namespaced (v2) via
1103
+ * `computeCapxulSafeSaltNonce({ email })`.
1104
+ *
1105
+ * Canonical: SDK deployment adapters and
1106
+ * `packages/backend/convex/smartAccount/mutations.ts:provision` import this
1107
+ * function; the conformance test at
1108
+ * `packages/config/tests/safe-address-conformance.test.ts` pins the matrix.
1109
+ */
1110
+ function deriveCapxulSafeAddress(input) {
1111
+ return deriveCapxulSafeAddressForOwner({
1112
+ ownerAddress: CAPXUL_BOOTSTRAP_OWNER,
1113
+ email: input.email
1114
+ });
1115
+ }
1116
+ /**
1117
+ * Owner-parametrized derivation core. Two callers only:
1118
+ * 1. `deriveCapxulSafeAddress` (canonical v2: owner = bootstrap, namespace v2);
1119
+ * 2. the backend faucet Safe (`testUsdcMint.ts`: owner = deployer EOA,
1120
+ * namespace pinned to `CAPXUL_SAFE_SALT_NAMESPACE_V1` so its deployed
1121
+ * address never moves).
1122
+ * Do NOT introduce new owner-parametrized lanes — per-user owners in the
1123
+ * derivation is exactly the v1 mistake v2 removes.
1124
+ */
1125
+ function deriveCapxulSafeAddressForOwner(input) {
1126
+ const initializer = buildCapxulSafeInitializer(validateAndNormalizeAddress("ownerAddress", input.ownerAddress));
1127
+ const saltNonce = computeCapxulSafeSaltNonce(input.namespace === void 0 ? { email: input.email } : {
1128
+ email: input.email,
1129
+ namespace: input.namespace
1130
+ });
1131
+ return getContractAddress({
1132
+ opcode: "CREATE2",
1133
+ from: SAFE_PROXY_FACTORY,
1134
+ salt: keccak256(encodePacked(["bytes32", "uint256"], [keccak256(initializer), saltNonce])),
1135
+ bytecodeHash: keccak256(concat([SAFE_PROXY_CREATION_CODE, encodeAbiParameters([{ type: "uint256" }], [BigInt(SAFE_L2_SINGLETON)])]))
1136
+ }).toLowerCase();
1137
+ }
1138
+ /** Canonical ERC-4337 EntryPoint v0.7 address (same on every chain). */
1139
+ const ENTRY_POINT_07_ADDRESS = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
1140
+ /** EIP-712 `SafeOp` typed-data fields for EntryPoint v0.7 (Safe4337Module). */
1141
+ const EIP712_SAFE_OPERATION_TYPE_V07 = { SafeOp: [
922
1142
  {
923
- type: "function",
924
- name: "createCommitment",
925
- stateMutability: "nonpayable",
926
- inputs: [
927
- {
928
- name: "token",
929
- type: "address"
930
- },
931
- {
932
- name: "recipient",
933
- type: "address"
934
- },
935
- {
936
- name: "totalAmount",
937
- type: "uint256"
938
- },
939
- {
940
- name: "startTime",
941
- type: "uint48"
942
- },
943
- {
944
- name: "cliffTime",
945
- type: "uint48"
946
- },
947
- {
948
- name: "endTime",
949
- type: "uint48"
950
- },
951
- {
952
- name: "documentHash",
953
- type: "bytes32"
954
- },
955
- {
956
- name: "paymentType",
957
- type: "uint8"
958
- }
959
- ],
960
- outputs: [{
961
- name: "commitmentId",
962
- type: "uint256"
963
- }]
1143
+ type: "address",
1144
+ name: "safe"
964
1145
  },
965
1146
  {
966
- type: "function",
967
- name: "claim",
968
- stateMutability: "nonpayable",
969
- inputs: [{
970
- name: "commitmentId",
971
- type: "uint256"
972
- }],
973
- outputs: []
1147
+ type: "uint256",
1148
+ name: "nonce"
974
1149
  },
975
1150
  {
976
- type: "function",
977
- name: "cancel",
978
- stateMutability: "nonpayable",
979
- inputs: [{
980
- name: "commitmentId",
981
- type: "uint256"
982
- }, {
983
- name: "documentHash",
984
- type: "bytes32"
985
- }],
986
- outputs: []
1151
+ type: "bytes",
1152
+ name: "initCode"
1153
+ },
1154
+ {
1155
+ type: "bytes",
1156
+ name: "callData"
1157
+ },
1158
+ {
1159
+ type: "uint128",
1160
+ name: "verificationGasLimit"
1161
+ },
1162
+ {
1163
+ type: "uint128",
1164
+ name: "callGasLimit"
1165
+ },
1166
+ {
1167
+ type: "uint256",
1168
+ name: "preVerificationGas"
1169
+ },
1170
+ {
1171
+ type: "uint128",
1172
+ name: "maxPriorityFeePerGas"
1173
+ },
1174
+ {
1175
+ type: "uint128",
1176
+ name: "maxFeePerGas"
1177
+ },
1178
+ {
1179
+ type: "bytes",
1180
+ name: "paymasterAndData"
987
1181
  },
988
1182
  {
989
- type: "function",
990
- name: "redirect",
991
- stateMutability: "nonpayable",
992
- inputs: [
993
- {
994
- name: "commitmentId",
995
- type: "uint256"
996
- },
997
- {
998
- name: "newRecipient",
999
- type: "address"
1000
- },
1001
- {
1002
- name: "newDocumentHash",
1003
- type: "bytes32"
1004
- }
1005
- ],
1006
- outputs: []
1183
+ type: "uint48",
1184
+ name: "validAfter"
1007
1185
  },
1008
1186
  {
1009
- type: "function",
1010
- name: "claimableAmount",
1011
- stateMutability: "view",
1012
- inputs: [{
1013
- name: "commitmentId",
1014
- type: "uint256"
1015
- }],
1016
- outputs: [{
1017
- name: "",
1018
- type: "uint256"
1019
- }]
1187
+ type: "uint48",
1188
+ name: "validUntil"
1020
1189
  },
1021
1190
  {
1022
- type: "function",
1023
- name: "commitments",
1024
- stateMutability: "view",
1025
- inputs: [{
1026
- name: "",
1027
- type: "uint256"
1028
- }],
1029
- outputs: [
1030
- {
1031
- name: "creator",
1032
- type: "address"
1033
- },
1034
- {
1035
- name: "token",
1036
- type: "address"
1037
- },
1038
- {
1039
- name: "recipient",
1040
- type: "address"
1041
- },
1042
- {
1043
- name: "totalAmount",
1044
- type: "uint256"
1045
- },
1046
- {
1047
- name: "claimed",
1048
- type: "uint256"
1049
- },
1050
- {
1051
- name: "startTime",
1052
- type: "uint48"
1053
- },
1054
- {
1055
- name: "cliffTime",
1056
- type: "uint48"
1057
- },
1058
- {
1059
- name: "endTime",
1060
- type: "uint48"
1061
- },
1062
- {
1063
- name: "documentHash",
1064
- type: "bytes32"
1065
- },
1066
- {
1067
- name: "paymentType",
1068
- type: "uint8"
1069
- },
1070
- {
1071
- name: "cancelled",
1072
- type: "bool"
1073
- }
1074
- ]
1191
+ type: "address",
1192
+ name: "entryPoint"
1075
1193
  }
1076
- ];
1077
- function normalizeUint48(value, field) {
1078
- if (!Number.isInteger(value) || value < 0 || value > 0xffffffffffff) throw new RangeError(`${field} must be a uint48 (epoch seconds)`);
1079
- return value;
1194
+ ] };
1195
+ /** Pack EntryPoint v0.7 `factory` + `factoryData` into the SafeOp `initCode`. */
1196
+ function safe4337InitCode(userOp) {
1197
+ if (userOp.factory === void 0 || userOp.factory === "0x") return "0x";
1198
+ return concat([userOp.factory, userOp.factoryData ?? "0x"]);
1199
+ }
1200
+ /** Pack EntryPoint v0.7 unpacked paymaster fields into SafeOp `paymasterAndData`. */
1201
+ function safe4337PaymasterAndData(userOp) {
1202
+ if (userOp.paymaster === void 0 || userOp.paymaster === "0x") return "0x";
1203
+ return concat([
1204
+ userOp.paymaster,
1205
+ pad(toHex(userOp.paymasterVerificationGasLimit ?? 0n), { size: 16 }),
1206
+ pad(toHex(userOp.paymasterPostOpGasLimit ?? 0n), { size: 16 }),
1207
+ userOp.paymasterData ?? "0x"
1208
+ ]);
1080
1209
  }
1081
1210
  /**
1082
- * Encode a personal Safe's `createCommitment` UserOp: approve + createCommitment
1083
- * batched through a delegatecall into MultiSendCallOnly (one sponsored UserOp).
1084
- * The creator (payer Safe) escrows `totalAmount` into CapxulPayments.
1211
+ * Compute the EIP-712 `SafeOp` digest the Safe4337Module owner must sign for a
1212
+ * prepared deployment UserOperation. The `CapxulSigner` signs THIS digest.
1085
1213
  */
1086
- function buildCapxulCreateCommitmentPersonalCallData(input) {
1087
- const tokenAddress = normalizeAddress(input.tokenAddress, "tokenAddress");
1088
- const recipientAddress = normalizeAddress(input.recipientAddress, "recipientAddress");
1089
- const totalAmount = normalizePositiveAmount(input.totalAmount, "totalAmount");
1090
- const startTime = normalizeUint48(input.startTime, "startTime");
1091
- const cliffTime = normalizeUint48(input.cliffTime, "cliffTime");
1092
- const endTime = normalizeUint48(input.endTime, "endTime");
1093
- if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) throw new RangeError("commitment times must satisfy start <= cliff <= end");
1094
- const documentHash = normalizeBytes32(input.documentHash ?? `0x${"0".repeat(64)}`, "documentHash");
1095
- const paymentType = normalizeUint8(input.paymentType ?? 0, "paymentType");
1096
- return encodeFunctionData({
1097
- abi: SAFE4337_EXECUTE_USEROP_ABI,
1098
- functionName: "executeUserOpWithErrorString",
1099
- args: [
1100
- MULTI_SEND_CALL_ONLY,
1101
- 0n,
1102
- encodeFunctionData({
1103
- abi: MULTI_SEND_CALL_ONLY_ABI,
1104
- functionName: "multiSend",
1105
- args: [concat([{
1106
- to: tokenAddress,
1107
- data: encodeFunctionData({
1108
- abi: ERC20_APPROVE_ABI,
1109
- functionName: "approve",
1110
- args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount]
1111
- }),
1112
- value: 0n
1113
- }, {
1114
- to: CAPXUL_PAYMENTS_ADDRESS,
1115
- data: encodeFunctionData({
1116
- abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1117
- functionName: "createCommitment",
1118
- args: [
1119
- tokenAddress,
1120
- recipientAddress,
1121
- totalAmount,
1122
- startTime,
1123
- cliffTime,
1124
- endTime,
1125
- documentHash,
1126
- paymentType
1127
- ]
1128
- }),
1129
- value: 0n
1130
- }].map(encodeMultiSendCallTransaction))]
1131
- }),
1132
- OPERATION_DELEGATECALL
1133
- ]
1214
+ function safe4337SafeOpDigest(input) {
1215
+ return hashTypedData({
1216
+ domain: {
1217
+ chainId: input.chainId,
1218
+ verifyingContract: input.safe4337ModuleAddress ?? "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226"
1219
+ },
1220
+ types: EIP712_SAFE_OPERATION_TYPE_V07,
1221
+ primaryType: "SafeOp",
1222
+ message: {
1223
+ safe: input.userOp.sender,
1224
+ nonce: input.userOp.nonce,
1225
+ initCode: safe4337InitCode(input.userOp),
1226
+ callData: input.userOp.callData,
1227
+ verificationGasLimit: input.userOp.verificationGasLimit,
1228
+ callGasLimit: input.userOp.callGasLimit,
1229
+ preVerificationGas: input.userOp.preVerificationGas,
1230
+ maxPriorityFeePerGas: input.userOp.maxPriorityFeePerGas,
1231
+ maxFeePerGas: input.userOp.maxFeePerGas,
1232
+ paymasterAndData: safe4337PaymasterAndData(input.userOp),
1233
+ validAfter: input.validAfter ?? 0,
1234
+ validUntil: input.validUntil ?? 0,
1235
+ entryPoint: input.entryPointAddress ?? "0x0000000071727De22E5E9d8BAf0edAc6f37da032"
1236
+ }
1134
1237
  });
1135
1238
  }
1136
- function buildSingleCapxulPaymentsCallData(data) {
1137
- return encodeFunctionData({
1138
- abi: SAFE4337_EXECUTE_USEROP_ABI,
1139
- functionName: "executeUserOpWithErrorString",
1140
- args: [
1141
- CAPXUL_PAYMENTS_ADDRESS,
1142
- 0n,
1143
- data,
1144
- OPERATION_CALL
1145
- ]
1146
- });
1239
+ /** Pack a single-owner ECDSA signature into the Safe4337 UserOp signature. */
1240
+ function packSafe4337OwnerSignature(input) {
1241
+ assertUint48(input.validAfter ?? 0, "validAfter");
1242
+ assertUint48(input.validUntil ?? 0, "validUntil");
1243
+ return encodePacked([
1244
+ "uint48",
1245
+ "uint48",
1246
+ "bytes"
1247
+ ], [
1248
+ input.validAfter ?? 0,
1249
+ input.validUntil ?? 0,
1250
+ input.signature
1251
+ ]);
1147
1252
  }
1148
- /** Encode a recipient Safe's `claim(commitmentId)` UserOp callData. */
1149
- function buildCapxulCommitmentClaimCallData(commitmentId) {
1150
- return buildSingleCapxulPaymentsCallData(encodeFunctionData({
1151
- abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1152
- functionName: "claim",
1153
- args: [commitmentId]
1154
- }));
1253
+ function assertUint48(value, field) {
1254
+ if (!Number.isSafeInteger(value) || value < 0 || value > UINT48_MAX) throw Errors.invalidInput(field, `must fit uint48 (0..${UINT48_MAX})`);
1155
1255
  }
1156
- /** Encode a creator Safe's `cancel(commitmentId, documentHash)` UserOp callData. */
1157
- function buildCapxulCommitmentCancelCallData(commitmentId, documentHash) {
1158
- return buildSingleCapxulPaymentsCallData(encodeFunctionData({
1159
- abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1160
- functionName: "cancel",
1161
- args: [commitmentId, normalizeBytes32(documentHash ?? `0x${"0".repeat(64)}`, "documentHash")]
1162
- }));
1256
+ const SAFE4337_STUB_OWNER_ECDSA = "0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c";
1257
+ /**
1258
+ * Packed Safe4337 stub signature (single static owner) for gas estimation —
1259
+ * byte-for-byte equal to permissionless's `getStubSignature()`.
1260
+ */
1261
+ function safe4337StubSignature() {
1262
+ return packSafe4337OwnerSignature({ signature: SAFE4337_STUB_OWNER_ECDSA });
1163
1263
  }
1164
- /** Encode a creator Safe's `redirect(commitmentId, newRecipient, newDocumentHash)` UserOp callData. */
1165
- function buildCapxulCommitmentRedirectCallData(commitmentId, newRecipient, newDocumentHash) {
1166
- return buildSingleCapxulPaymentsCallData(encodeFunctionData({
1167
- abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1168
- functionName: "redirect",
1169
- args: [
1170
- commitmentId,
1171
- normalizeAddress(newRecipient, "newRecipient"),
1172
- normalizeBytes32(newDocumentHash ?? `0x${"0".repeat(64)}`, "newDocumentHash")
1173
- ]
1174
- }));
1264
+ //#endregion
1265
+ //#region ../../packages/config/src/binding.ts
1266
+ /** Openfort `thirdPartyUserId` namespace for email bindings (epic #331 / #332). */
1267
+ const CAPXUL_BINDING_EMAIL_NAMESPACE = "capxul:binding:email:v1";
1268
+ /**
1269
+ * Normalize a raw email for binding id + Safe salt derivation.
1270
+ * Delegates to {@link normalizeSafeSaltEmail} so binding resolution and
1271
+ * `deriveCapxulSafeAddress` never drift apart.
1272
+ */
1273
+ function normalizeBindingEmail(email) {
1274
+ return normalizeSafeSaltEmail(email);
1175
1275
  }
1176
1276
  //#endregion
1177
1277
  //#region ../../packages/config/src/route.ts
@@ -1679,9 +1779,22 @@ const ORG_ROLE_ALLOWANCE_KEYS = {
1679
1779
  })
1680
1780
  };
1681
1781
  const MULTI_SEND_SELECTOR = "0x8d80ff0a";
1782
+ padHex(concat([MULTI_SEND_CALL_ONLY, MULTI_SEND_SELECTOR]), {
1783
+ dir: "right",
1784
+ size: 32
1785
+ });
1682
1786
  const ONE_DAY_SECONDS = 86400n;
1683
1787
  const ZODIAC_OPERATION_CALL = 0;
1684
1788
  const EXEC_TRANSACTION_WITH_ROLE = "zodiac.roles.execTransactionWithRole";
1789
+ const ROLE_MANAGEMENT_SIGNATURES = [
1790
+ "allowTarget(bytes32,address,uint8)",
1791
+ "scopeTarget(bytes32,address)",
1792
+ "revokeTarget(bytes32,address)",
1793
+ "allowFunction(bytes32,address,bytes4,uint8)",
1794
+ "scopeFunction(bytes32,address,bytes4,(uint8,uint8,uint8,bytes)[],uint8)",
1795
+ "revokeFunction(bytes32,address,bytes4)",
1796
+ "setAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)"
1797
+ ];
1685
1798
  const PARAMETER_TYPE = {
1686
1799
  none: 0,
1687
1800
  static: 1,
@@ -1980,6 +2093,10 @@ function rolePermissions(input) {
1980
2093
  targetAddress: input.rolesModuleAddress,
1981
2094
  signature: "assignRoles(address,bytes32[],bool[])"
1982
2095
  });
2096
+ if (input.role.definition.canManageRoles === true) permissions.push(...ROLE_MANAGEMENT_SIGNATURES.map((signature) => ({
2097
+ targetAddress: input.rolesModuleAddress,
2098
+ signature
2099
+ })));
1983
2100
  if (input.role.allowance === null && input.role.permissions.includes(EXEC_TRANSACTION_WITH_ROLE)) permissions.push(...uncappedPaymentPermissions(), ...uncappedCommitmentPermissions());
1984
2101
  if (input.role.allowance?.perTx !== void 0 && input.role.allowance.perDay !== void 0) {
1985
2102
  const allowanceKey = orgRoleAllowanceKeyForLabel(input.role.label);
@@ -2085,5 +2202,15 @@ function buildOrgRoleAssignmentCall(input) {
2085
2202
  value: 0n
2086
2203
  };
2087
2204
  }
2205
+ new Map([
2206
+ ["assignRoles(address,bytes32[],bool[])", "AssignRoles(address,bytes32[],bool[])"],
2207
+ ["allowTarget(bytes32,address,uint8)", "AllowTarget(bytes32,address,uint8)"],
2208
+ ["scopeTarget(bytes32,address)", "ScopeTarget(bytes32,address)"],
2209
+ ["revokeTarget(bytes32,address)", "RevokeTarget(bytes32,address)"],
2210
+ ["allowFunction(bytes32,address,bytes4,uint8)", "AllowFunction(bytes32,address,bytes4,uint8)"],
2211
+ ["scopeFunction(bytes32,address,bytes4,(uint8,uint8,uint8,bytes)[],uint8)", "ScopeFunction(bytes32,address,bytes4,(uint8,uint8,uint8,bytes)[],uint8)"],
2212
+ ["revokeFunction(bytes32,address,bytes4)", "RevokeFunction(bytes32,address,bytes4)"],
2213
+ ["setAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)", "SetAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)"]
2214
+ ].map(([functionSignature, eventSignature]) => [toFunctionSelector(functionSignature), toEventSelector(eventSignature)]));
2088
2215
  //#endregion
2089
- export { packSafe4337OwnerSignature as $, buildCapxulCommitmentRedirectCallData as A, CAPXUL_BOOTSTRAP_OWNER as B, ERC20_APPROVE_ABI as C, ZODIAC_MULTI_SEND_UNWRAPPER as D, ZODIAC_MODULE_PROXY_FACTORY as E, buildOrgPersonalMultiCallData as F, SAFE_L2_SINGLETON as G, ENTRY_POINT_07_ADDRESS as H, buildOrgRoleSpendPersonalCallData as I, SAFE_PROXY_FACTORY as J, SAFE_MODULE_SETUP as K, CAPXUL_BINDING_EMAIL_NAMESPACE as L, buildCapxulPaymentsPersonalSendCallData as M, buildCapxulPaymentsRoleBatchSpendCall as N, buildCapxulCommitmentCancelCallData as O, buildCapxulPaymentsSendCalls as P, normalizeSafeSaltEmail as Q, normalizeBindingEmail as R, CAPXUL_PAYMENTS_SEND_ABI as S, ROLES_MASTERCOPY as T, MULTI_SEND as U, CAPXUL_SAFE_SALT_NAMESPACE as V, SAFE_4337_MODULE as W, deriveCapxulSafeAddress as X, computeCapxulSafeSaltNonce as Y, deriveCapxulSafeAddressForOwner as Z, validateOrgHandle as _, orgRoleAllowanceKeyForLabel as a, USDX_ADDRESS_BASE_SEPOLIA as at, CAPXUL_PAYMENTS_ADDRESS as b, orgRoleKeyForLabel as c, CapxulError as ct, startupOrgRoleTemplate as d, isCapxulError as dt, safe4337InitCode as et, CAPXUL_ORG_SALT_NAMESPACE as f, normalizeOrgHandle as g, deriveCapxulOrgAddress as h, computeOrgRolesModuleAddress as i, EXACT_TRANSFER_TOKEN_ALLOWLIST as it, buildCapxulCreateCommitmentPersonalCallData as j, buildCapxulCommitmentClaimCallData as k, orgRoleTemplateDefinitions as l, Errors as lt, computeCapxulOrgSaltNonce as m, buildOrgRoleAssignmentCall as n, safe4337SafeOpDigest as nt, compileOrgRoleDefinitions as o, isExactTransferTokenAllowed as ot, buildCapxulOrgInitializer as p, SAFE_PROXY_CREATION_CODE as q, buildOrgRolesDeployCalls as r, safe4337StubSignature as rt, normalizeOrgRoleLabel as s, decodeConvexError as st, ORG_ROLE_ALLOWANCE_KEYS as t, safe4337PaymasterAndData as tt, soloOrgRoleTemplate as u, deserializeCapxulError as ut, DIRECT_BASE_ROUTE as v, MULTI_SEND_CALL_ONLY as w, CAPXUL_PAYMENTS_COMMITMENT_ABI as x, USDX_BASE_SEPOLIA_TOKEN as y, BASE_SEPOLIA_CHAIN_ID as z };
2216
+ export { buildCapxulCommitmentRedirectCallData as $, SAFE_MODULE_SETUP as A, safe4337PaymasterAndData as B, BASE_SEPOLIA_CHAIN_ID as C, MULTI_SEND as D, ENTRY_POINT_07_ADDRESS as E, deriveCapxulSafeAddress as F, CAPXUL_PAYMENTS_SEND_ABI as G, safe4337StubSignature as H, deriveCapxulSafeAddressForOwner as I, ROLES_MASTERCOPY as J, ERC20_APPROVE_ABI as K, normalizeSafeSaltEmail as L, SAFE_PROXY_FACTORY as M, buildSafeMultiSendExecTransactionCall as N, SAFE_4337_MODULE as O, computeCapxulSafeSaltNonce as P, buildCapxulCommitmentClaimCallData as Q, packSafe4337OwnerSignature as R, normalizeBindingEmail as S, CAPXUL_SAFE_SALT_NAMESPACE as T, CAPXUL_PAYMENTS_ADDRESS as U, safe4337SafeOpDigest as V, CAPXUL_PAYMENTS_COMMITMENT_ABI as W, ZODIAC_MULTI_SEND_UNWRAPPER as X, ZODIAC_MODULE_PROXY_FACTORY as Y, buildCapxulCommitmentCancelCallData as Z, normalizeOrgHandle as _, computeOrgRolesModuleAddress as a, buildOrgRoleSpendPersonalCallData as at, USDX_BASE_SEPOLIA_TOKEN as b, normalizeOrgRoleLabel as c, isExactTransferTokenAllowed as ct, soloOrgRoleTemplate as d, Errors as dt, buildCapxulCreateCommitmentPersonalCallData as et, startupOrgRoleTemplate as f, deserializeCapxulError as ft, deriveCapxulOrgAddress as g, computeCapxulOrgSaltNonce as h, buildOrgRolesDeployCalls as i, buildOrgPersonalMultiCallData as it, SAFE_PROXY_CREATION_CODE as j, SAFE_L2_SINGLETON as k, orgRoleKeyForLabel as l, decodeConvexError as lt, buildCapxulOrgInitializer as m, ORG_ROLE_ALLOWANCE_KEYS as n, buildCapxulPaymentsRoleBatchSpendCall as nt, orgRoleAllowanceKeyForLabel as o, EXACT_TRANSFER_TOKEN_ALLOWLIST as ot, CAPXUL_ORG_SALT_NAMESPACE as p, isCapxulError as pt, MULTI_SEND_CALL_ONLY as q, buildOrgRoleAssignmentCall as r, buildCapxulPaymentsSendCalls as rt, compileOrgRoleDefinitions as s, USDX_ADDRESS_BASE_SEPOLIA as st, MULTI_SEND_SELECTOR as t, buildCapxulPaymentsPersonalSendCallData as tt, orgRoleTemplateDefinitions as u, CapxulError as ut, validateOrgHandle as v, CAPXUL_BOOTSTRAP_OWNER as w, CAPXUL_BINDING_EMAIL_NAMESPACE as x, DIRECT_BASE_ROUTE as y, safe4337InitCode as z };