@capxul/mcp 1.0.0-alpha.4 → 1.2.0

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