@capxul/mcp 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2038 @@
1
+ import { concat, encodeAbiParameters, encodeFunctionData, encodePacked, getContractAddress, hashTypedData, isAddress, keccak256, pad, padHex, parseAbiParameters, stringToHex, toBytes, toHex } from "viem";
2
+ //#region ../../packages/errors/src/errors.ts
3
+ const CAPXUL_ERROR_CODES = [
4
+ "NOT_AUTHENTICATED",
5
+ "EMAIL_DELIVERY_FAILED",
6
+ "PROFILE_NOT_FOUND",
7
+ "SMART_ACCOUNT_MISSING",
8
+ "PLAYER_NOT_FOUND",
9
+ "ACCOUNT_NOT_FOUND",
10
+ "PROVIDER_ERROR",
11
+ "INVALID_INPUT",
12
+ "ENV_MISSING",
13
+ "NOT_IMPLEMENTED",
14
+ "VERIFICATION_REQUIRED",
15
+ "INSUFFICIENT_BALANCE",
16
+ "INVALID_RECIPIENT",
17
+ "ROLE_PERMISSION_DENIED",
18
+ "TRANSACTION_FAILED",
19
+ "RATE_LIMITED",
20
+ "NETWORK_ERROR",
21
+ "UNKNOWN",
22
+ "OTP_EXPIRED",
23
+ "SIGNER_REJECTED",
24
+ "CANCELLED",
25
+ "WRONG_STATE"
26
+ ];
27
+ var CapxulError = class extends Error {
28
+ code;
29
+ details;
30
+ correlationId;
31
+ layer;
32
+ constructor(code, message, options = {}) {
33
+ super(message, "cause" in options ? { cause: options.cause } : void 0);
34
+ this.name = "CapxulError";
35
+ this.code = code;
36
+ if (options.details !== void 0) this.details = options.details;
37
+ if (options.correlationId !== void 0) this.correlationId = options.correlationId;
38
+ if (options.layer !== void 0) this.layer = options.layer;
39
+ }
40
+ };
41
+ function isCapxulError(value) {
42
+ return value instanceof CapxulError;
43
+ }
44
+ function deserializeCapxulError(serialized) {
45
+ return new CapxulError(serialized.code, serialized.message, compactErrorOptions({
46
+ details: serialized.details,
47
+ correlationId: serialized.correlationId,
48
+ layer: serialized.layer
49
+ }));
50
+ }
51
+ function compactErrorOptions(options) {
52
+ const result = {};
53
+ if ("cause" in options) result.cause = options.cause;
54
+ if (options.details !== void 0) result.details = options.details;
55
+ if (options.correlationId !== void 0) result.correlationId = options.correlationId;
56
+ if (options.layer !== void 0) result.layer = options.layer;
57
+ return result;
58
+ }
59
+ const Errors = {
60
+ notAuthenticated: (message, opts) => new CapxulError("NOT_AUTHENTICATED", message ?? "Not authenticated", opts?.failure_mode ? { details: { failure_mode: opts.failure_mode } } : void 0),
61
+ emailDeliveryFailed: (detail) => new CapxulError("EMAIL_DELIVERY_FAILED", "Failed to send email", { details: { detail } }),
62
+ profileNotFound: (authUserId) => new CapxulError("PROFILE_NOT_FOUND", `Profile not found for user ${authUserId}`, { details: { authUserId } }),
63
+ smartAccountMissing: (authUserId) => new CapxulError("SMART_ACCOUNT_MISSING", "Smart account not provisioned", { details: { authUserId } }),
64
+ playerNotFound: (playerId) => new CapxulError("PLAYER_NOT_FOUND", playerId ? `Openfort player ${playerId} not found` : "Openfort player not found", playerId === void 0 ? void 0 : { details: { playerId } }),
65
+ accountNotFound: (accountId) => new CapxulError("ACCOUNT_NOT_FOUND", accountId ? `Openfort account ${accountId} not found` : "Openfort account not found", accountId === void 0 ? void 0 : { details: { accountId } }),
66
+ providerError: (provider, operation, cause, opts) => {
67
+ const details = {
68
+ provider,
69
+ operation
70
+ };
71
+ if (opts?.failure_mode) details.failure_mode = opts.failure_mode;
72
+ return new CapxulError("PROVIDER_ERROR", `Provider error: ${provider} ${operation}`, {
73
+ cause,
74
+ details
75
+ });
76
+ },
77
+ invalidInput: (field, reason) => new CapxulError("INVALID_INPUT", `Invalid ${field}: ${reason}`, { details: {
78
+ field,
79
+ reason
80
+ } }),
81
+ envMissing: (name) => new CapxulError("ENV_MISSING", `Environment variable ${name} not configured`, { details: { name } }),
82
+ notImplemented: (domain, method) => new CapxulError("NOT_IMPLEMENTED", `${domain}.${method} is not yet implemented. This feature is planned for a future release.`, { details: {
83
+ domain,
84
+ method
85
+ } }),
86
+ /**
87
+ * 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
90
+ * `providerError`, plus a `details.reason: "timeout"` discriminator so
91
+ * downstream observers can distinguish failure modes without parsing the
92
+ * message string. The redacted message names the timeout budget; the
93
+ * native `cause` carries the same information for `reportError` fidelity.
94
+ */
95
+ providerTimeout: (provider, operation, timeoutMs) => new CapxulError("PROVIDER_ERROR", `Provider error: ${provider} ${operation} (timeout exceeded ${timeoutMs}ms)`, {
96
+ details: {
97
+ provider,
98
+ operation,
99
+ reason: "timeout"
100
+ },
101
+ cause: /* @__PURE__ */ new Error(`timeout: ${operation} exceeded ${timeoutMs}ms`)
102
+ }),
103
+ verificationRequired: (details) => {
104
+ return new CapxulError("VERIFICATION_REQUIRED", "rail" in details ? `Verification is required before ${details.rail} can use ${details.currentKind}.` : `Verification tier ${details.requiredTier} is required.`, { details });
105
+ },
106
+ insufficientBalance: (asset, available, required) => new CapxulError("INSUFFICIENT_BALANCE", `Insufficient ${asset} balance`, { details: {
107
+ asset,
108
+ available,
109
+ required
110
+ } }),
111
+ invalidRecipient: (reason) => new CapxulError("INVALID_RECIPIENT", `Invalid recipient: ${reason}`, { details: { reason } }),
112
+ /**
113
+ * The org Zodiac Roles modifier REFUSED the spend on-chain (G4 · #547): the
114
+ * member's role condition (per-tx cap, per-day allowance, allowed recipient,
115
+ * or membership) was violated, so `execTransactionWithRole` reverted. This is
116
+ * a PERMISSION denial — explicitly NOT an `INSUFFICIENT_BALANCE` (the treasury
117
+ * held the funds; the role's authority is what bound). `reason` discriminates
118
+ * the violated condition (`over_cap` / `daily_cap` / `not_member` /
119
+ * `disallowed_recipient` / `condition_violation`); leak-safe — no on-chain
120
+ * identifiers ever enter the details.
121
+ */
122
+ rolePermissionDenied: (details) => new CapxulError("ROLE_PERMISSION_DENIED", `Org role denied this spend on-chain (${details.reason}).`, { details: details.operation === void 0 ? { reason: details.reason } : {
123
+ reason: details.reason,
124
+ operation: details.operation
125
+ } }),
126
+ /**
127
+ * A transaction (or sponsored UserOp) failed. `details.reason` discriminates
128
+ * the failure mode for callers that must distinguish a CONFIRMED on-chain
129
+ * revert (`"onchain_revert"` — the op executed and reverted, e.g. a Zodiac
130
+ * Roles condition violation) from an inconclusive infra failure. A confirmed
131
+ * revert is the ONLY mode the org spend port may map to a roles denial.
132
+ */
133
+ transactionFailed: (operation, cause, extra) => new CapxulError("TRANSACTION_FAILED", `Transaction failed: ${operation}`, {
134
+ cause,
135
+ details: extra?.reason === void 0 ? { operation } : {
136
+ operation,
137
+ reason: extra.reason
138
+ }
139
+ }),
140
+ rateLimited: (details) => new CapxulError("RATE_LIMITED", "Rate limit exceeded", details === void 0 ? void 0 : { details: { ...details } }),
141
+ networkError: (operation, cause) => new CapxulError("NETWORK_ERROR", `Network error during ${operation}`, {
142
+ cause,
143
+ details: { operation }
144
+ }),
145
+ unknown: (cause) => new CapxulError("UNKNOWN", "Unknown error", { cause }),
146
+ otpExpired: (details) => new CapxulError("OTP_EXPIRED", "Verification code has expired. Request a new one.", details === void 0 ? void 0 : { details: { ...details } }),
147
+ signerRejected: (details) => new CapxulError("SIGNER_REJECTED", "Signer rejected the request.", {
148
+ cause: details.cause,
149
+ details: details.reason === void 0 ? { source: details.source } : {
150
+ source: details.source,
151
+ reason: details.reason
152
+ }
153
+ }),
154
+ cancelled: (details) => new CapxulError("CANCELLED", "Operation was cancelled.", details === void 0 ? void 0 : { details: { ...details } }),
155
+ /**
156
+ * Method called from a flow state where its precondition fails (TA16). The
157
+ * SDK's method API short-circuits with this error before driving the
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`
161
+ * enumerates the states the method accepts.
162
+ */
163
+ wrongState: (details) => new CapxulError("WRONG_STATE", `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(", ")}`, { details: {
164
+ ...details,
165
+ validStates: [...details.validStates]
166
+ } })
167
+ };
168
+ //#endregion
169
+ //#region ../../packages/errors/src/convex-error-decoding.ts
170
+ const KNOWN_CODES = new Set(CAPXUL_ERROR_CODES);
171
+ function isCapxulCode(value) {
172
+ return typeof value === "string" && KNOWN_CODES.has(value);
173
+ }
174
+ function reconstruct(serialized) {
175
+ if (!isCapxulCode(serialized.code)) return null;
176
+ return deserializeCapxulError({
177
+ code: serialized.code,
178
+ message: typeof serialized.message === "string" ? serialized.message : String(serialized.code),
179
+ ...typeof serialized.details === "object" && serialized.details !== null && !Array.isArray(serialized.details) ? { details: serialized.details } : {},
180
+ ...typeof serialized.correlationId === "string" ? { correlationId: serialized.correlationId } : {},
181
+ ...typeof serialized.layer === "string" ? { layer: serialized.layer } : {}
182
+ });
183
+ }
184
+ function decodeConvexError(err) {
185
+ if (err === null || err === void 0) return null;
186
+ if (err instanceof CapxulError) return err;
187
+ if (typeof err !== "object") return null;
188
+ const record = err;
189
+ if (!("data" in record)) return null;
190
+ const data = record.data;
191
+ if (typeof data === "object" && data !== null) return reconstruct(data);
192
+ if (typeof data === "string") try {
193
+ const parsed = JSON.parse(data);
194
+ if (typeof parsed === "object" && parsed !== null) return reconstruct(parsed);
195
+ } catch {}
196
+ return null;
197
+ }
198
+ //#endregion
199
+ //#region ../../packages/config/src/tokens.ts
200
+ /** `TestUSDC` ("USDX") — Base Sepolia, 6 decimals, open `mint`. (Canon §1.) */
201
+ const USDX_ADDRESS_BASE_SEPOLIA = "0xf09fcbb6df9f8f918e58f9c8ab15a76ade862b77";
202
+ /**
203
+ * Exact-transfer token allowlist (#536 / G2 HITL gate): the only ERC-20s the
204
+ * `CapxulPayments` adapter may move via `send(token, …)`. v1 permits USDX on
205
+ * Base Sepolia only. Enforced BEFORE any execute so a tainted or fuzzy token
206
+ * address can never be transferred — the allowlist is the policy boundary, not
207
+ * the caller's input. Lowercased for case-insensitive comparison.
208
+ */
209
+ const EXACT_TRANSFER_TOKEN_ALLOWLIST = [USDX_ADDRESS_BASE_SEPOLIA.toLowerCase()];
210
+ /** True iff `tokenAddress` is on the exact-transfer allowlist (case-insensitive). */
211
+ function isExactTransferTokenAllowed(tokenAddress) {
212
+ return EXACT_TRANSFER_TOKEN_ALLOWLIST.includes(tokenAddress.toLowerCase());
213
+ }
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 = [{
281
+ type: "function",
282
+ name: "setup",
283
+ stateMutability: "nonpayable",
284
+ inputs: [
285
+ {
286
+ name: "_owners",
287
+ type: "address[]"
288
+ },
289
+ {
290
+ name: "_threshold",
291
+ type: "uint256"
292
+ },
293
+ {
294
+ name: "to",
295
+ type: "address"
296
+ },
297
+ {
298
+ name: "data",
299
+ type: "bytes"
300
+ },
301
+ {
302
+ name: "fallbackHandler",
303
+ type: "address"
304
+ },
305
+ {
306
+ name: "paymentToken",
307
+ type: "address"
308
+ },
309
+ {
310
+ name: "payment",
311
+ type: "uint256"
312
+ },
313
+ {
314
+ name: "paymentReceiver",
315
+ type: "address"
316
+ }
317
+ ],
318
+ outputs: []
319
+ }];
320
+ const enableModulesAbi$1 = [{
321
+ type: "function",
322
+ name: "enableModules",
323
+ stateMutability: "nonpayable",
324
+ inputs: [{
325
+ name: "modules",
326
+ type: "address[]"
327
+ }],
328
+ outputs: []
329
+ }];
330
+ const multiSendAbi$1 = [{
331
+ type: "function",
332
+ name: "multiSend",
333
+ stateMutability: "payable",
334
+ inputs: [{
335
+ name: "transactions",
336
+ type: "bytes"
337
+ }],
338
+ outputs: []
339
+ }];
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
+ });
377
+ }
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;
383
+ }
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.
409
+ */
410
+ function deriveCapxulSafeAddress(input) {
411
+ return deriveCapxulSafeAddressForOwner({
412
+ ownerAddress: CAPXUL_BOOTSTRAP_OWNER,
413
+ email: input.email
414
+ });
415
+ }
416
+ /**
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.
424
+ */
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
430
+ });
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
+ }
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
+ },
470
+ {
471
+ type: "uint128",
472
+ name: "maxPriorityFeePerGas"
473
+ },
474
+ {
475
+ type: "uint128",
476
+ name: "maxFeePerGas"
477
+ },
478
+ {
479
+ type: "bytes",
480
+ name: "paymasterAndData"
481
+ },
482
+ {
483
+ type: "uint48",
484
+ name: "validAfter"
485
+ },
486
+ {
487
+ type: "uint48",
488
+ name: "validUntil"
489
+ },
490
+ {
491
+ type: "address",
492
+ name: "entryPoint"
493
+ }
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
+ ]);
509
+ }
510
+ /**
511
+ * Compute the EIP-712 `SafeOp` digest the Safe4337Module owner must sign for a
512
+ * prepared deployment UserOperation. The `CapxulSigner` signs THIS digest.
513
+ */
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
+ }
537
+ });
538
+ }
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
+ ]);
552
+ }
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})`);
555
+ }
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 });
563
+ }
564
+ //#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";
568
+ /**
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.
572
+ */
573
+ function normalizeBindingEmail(email) {
574
+ return normalizeSafeSaltEmail(email);
575
+ }
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 = [{
589
+ type: "function",
590
+ name: "send",
591
+ stateMutability: "nonpayable",
592
+ inputs: [
593
+ {
594
+ name: "token",
595
+ type: "address"
596
+ },
597
+ {
598
+ name: "recipient",
599
+ type: "address"
600
+ },
601
+ {
602
+ name: "amount",
603
+ type: "uint256"
604
+ },
605
+ {
606
+ name: "documentHash",
607
+ type: "bytes32"
608
+ },
609
+ {
610
+ name: "paymentType",
611
+ type: "uint8"
612
+ }
613
+ ],
614
+ outputs: []
615
+ }];
616
+ const ERC20_APPROVE_ABI = [{
617
+ type: "function",
618
+ name: "approve",
619
+ stateMutability: "nonpayable",
620
+ inputs: [{
621
+ name: "spender",
622
+ type: "address"
623
+ }, {
624
+ name: "amount",
625
+ type: "uint256"
626
+ }],
627
+ outputs: [{
628
+ name: "",
629
+ type: "bool"
630
+ }]
631
+ }];
632
+ const MULTI_SEND_CALL_ONLY_ABI = [{
633
+ type: "function",
634
+ name: "multiSend",
635
+ stateMutability: "payable",
636
+ inputs: [{
637
+ name: "transactions",
638
+ type: "bytes"
639
+ }],
640
+ outputs: []
641
+ }];
642
+ const ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI$1 = [{
643
+ type: "function",
644
+ name: "execTransactionWithRole",
645
+ stateMutability: "nonpayable",
646
+ inputs: [
647
+ {
648
+ name: "to",
649
+ type: "address"
650
+ },
651
+ {
652
+ name: "value",
653
+ type: "uint256"
654
+ },
655
+ {
656
+ name: "data",
657
+ type: "bytes"
658
+ },
659
+ {
660
+ name: "operation",
661
+ type: "uint8"
662
+ },
663
+ {
664
+ name: "roleKey",
665
+ type: "bytes32"
666
+ },
667
+ {
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"
685
+ },
686
+ {
687
+ name: "value",
688
+ type: "uint256"
689
+ },
690
+ {
691
+ name: "data",
692
+ type: "bytes"
693
+ },
694
+ {
695
+ name: "operation",
696
+ type: "uint8"
697
+ }
698
+ ],
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
+ /**
751
+ * Wrap an org Roles `execTransactionWithRole` call (from `*RoleSpendCall` /
752
+ * `*RoleBatchSpendCall`) into the member Safe's `executeUserOpWithErrorString`
753
+ * (operation = CALL into the Roles module) — the full Safe callData a sponsored
754
+ * UserOp from the member's personal Safe carries (G4 · #547).
755
+ */
756
+ function buildOrgRoleSpendPersonalCallData(roleSpendCall) {
757
+ return encodeFunctionData({
758
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
759
+ functionName: "executeUserOpWithErrorString",
760
+ args: [
761
+ normalizeAddress(roleSpendCall.to, "rolesModuleAddress"),
762
+ 0n,
763
+ roleSpendCall.data,
764
+ OPERATION_CALL
765
+ ]
766
+ });
767
+ }
768
+ /**
769
+ * Wrap an ARBITRARY batch of calls into a member Safe's
770
+ * `executeUserOpWithErrorString` via a delegatecall into MultiSendCallOnly
771
+ * (G4 · #547 dev seam). Used by the dev MCP proof to drive the org's Zodiac
772
+ * Roles DEPLOY (deployModule + enableModule + setUpRoles) and role GRANT
773
+ * (assignRoles) as ONE sponsored UserOp from the founder's personal Safe —
774
+ * the same `buildSponsoredSafeUserOp` mechanism the spend path uses. A single
775
+ * call is still wrapped (MultiSend of length 1) so the caller need not branch.
776
+ */
777
+ function buildOrgPersonalMultiCallData(calls) {
778
+ if (calls.length === 0) throw new RangeError("multi-call batch must include at least one call");
779
+ return encodeFunctionData({
780
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
781
+ functionName: "executeUserOpWithErrorString",
782
+ args: [
783
+ MULTI_SEND_CALL_ONLY,
784
+ 0n,
785
+ encodeFunctionData({
786
+ abi: MULTI_SEND_CALL_ONLY_ABI,
787
+ functionName: "multiSend",
788
+ args: [concat(calls.map(encodeMultiSendCallTransaction))]
789
+ }),
790
+ OPERATION_DELEGATECALL
791
+ ]
792
+ });
793
+ }
794
+ /**
795
+ * Encode an org PAYROLL BATCH (G4 · #547): one `execTransactionWithRole`
796
+ * (the member's role key) → MultiSendCallOnly → N × (approve + CapxulPayments.send),
797
+ * one send per employee. Each send keeps its own recipient + amount, so each is
798
+ * bounded independently by the role's on-chain Zodiac conditions (per-tx cap,
799
+ * per-day allowance, allowed recipient). One sponsored UserOp settles the batch.
800
+ */
801
+ function buildCapxulPaymentsRoleBatchSpendCall(input) {
802
+ if (input.runs.length === 0) throw new RangeError("payroll batch must include at least one run");
803
+ const roleKey = normalizeBytes32(input.roleKey, "roleKey");
804
+ const paymentType = input.paymentType ?? 0;
805
+ const multiSendData = encodeFunctionData({
806
+ abi: MULTI_SEND_CALL_ONLY_ABI,
807
+ functionName: "multiSend",
808
+ args: [concat(input.runs.flatMap((run) => [...buildCapxulPaymentsSendCalls({
809
+ tokenAddress: input.tokenAddress,
810
+ recipientAddress: run.recipientAddress,
811
+ amount: run.amount,
812
+ paymentType,
813
+ ...run.documentHash === void 0 ? {} : { documentHash: run.documentHash }
814
+ })]).map(encodeMultiSendCallTransaction))]
815
+ });
816
+ return {
817
+ to: normalizeAddress(input.rolesModuleAddress, "rolesModuleAddress"),
818
+ data: encodeFunctionData({
819
+ abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI$1,
820
+ functionName: "execTransactionWithRole",
821
+ args: [
822
+ MULTI_SEND_CALL_ONLY,
823
+ 0n,
824
+ multiSendData,
825
+ OPERATION_DELEGATECALL,
826
+ roleKey,
827
+ true
828
+ ]
829
+ }),
830
+ value: 0n
831
+ };
832
+ }
833
+ function encodeMultiSendCallTransaction(call) {
834
+ return encodePacked([
835
+ "uint8",
836
+ "address",
837
+ "uint256",
838
+ "uint256",
839
+ "bytes"
840
+ ], [
841
+ OPERATION_CALL,
842
+ call.to,
843
+ call.value,
844
+ BigInt((call.data.length - 2) / 2),
845
+ call.data
846
+ ]);
847
+ }
848
+ /**
849
+ * Encode a personal Safe's `executeUserOpWithErrorString` callData that pays via
850
+ * CapxulPayments in one UserOp: approve + send batched through a delegatecall
851
+ * into MultiSendCallOnly. The Safe4337Module invokes this on the Safe; the
852
+ * MultiSend then CALLs each sub-transaction from the Safe's own context.
853
+ */
854
+ function buildCapxulPaymentsPersonalSendCallData(input) {
855
+ return encodeFunctionData({
856
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
857
+ functionName: "executeUserOpWithErrorString",
858
+ args: [
859
+ MULTI_SEND_CALL_ONLY,
860
+ 0n,
861
+ encodeFunctionData({
862
+ abi: MULTI_SEND_CALL_ONLY_ABI,
863
+ functionName: "multiSend",
864
+ args: [concat(buildCapxulPaymentsSendCalls(input).map(encodeMultiSendCallTransaction))]
865
+ }),
866
+ OPERATION_DELEGATECALL
867
+ ]
868
+ });
869
+ }
870
+ const CAPXUL_PAYMENTS_COMMITMENT_ABI = [
871
+ {
872
+ type: "function",
873
+ name: "createCommitment",
874
+ stateMutability: "nonpayable",
875
+ inputs: [
876
+ {
877
+ name: "token",
878
+ type: "address"
879
+ },
880
+ {
881
+ name: "recipient",
882
+ type: "address"
883
+ },
884
+ {
885
+ name: "totalAmount",
886
+ type: "uint256"
887
+ },
888
+ {
889
+ name: "startTime",
890
+ type: "uint48"
891
+ },
892
+ {
893
+ name: "cliffTime",
894
+ type: "uint48"
895
+ },
896
+ {
897
+ name: "endTime",
898
+ type: "uint48"
899
+ },
900
+ {
901
+ name: "documentHash",
902
+ type: "bytes32"
903
+ },
904
+ {
905
+ name: "paymentType",
906
+ type: "uint8"
907
+ }
908
+ ],
909
+ outputs: [{
910
+ name: "commitmentId",
911
+ type: "uint256"
912
+ }]
913
+ },
914
+ {
915
+ type: "function",
916
+ name: "claim",
917
+ stateMutability: "nonpayable",
918
+ inputs: [{
919
+ name: "commitmentId",
920
+ type: "uint256"
921
+ }],
922
+ outputs: []
923
+ },
924
+ {
925
+ type: "function",
926
+ name: "cancel",
927
+ stateMutability: "nonpayable",
928
+ inputs: [{
929
+ name: "commitmentId",
930
+ type: "uint256"
931
+ }, {
932
+ name: "documentHash",
933
+ type: "bytes32"
934
+ }],
935
+ outputs: []
936
+ },
937
+ {
938
+ type: "function",
939
+ name: "redirect",
940
+ stateMutability: "nonpayable",
941
+ inputs: [
942
+ {
943
+ name: "commitmentId",
944
+ type: "uint256"
945
+ },
946
+ {
947
+ name: "newRecipient",
948
+ type: "address"
949
+ },
950
+ {
951
+ name: "newDocumentHash",
952
+ type: "bytes32"
953
+ }
954
+ ],
955
+ outputs: []
956
+ },
957
+ {
958
+ type: "function",
959
+ name: "claimableAmount",
960
+ stateMutability: "view",
961
+ inputs: [{
962
+ name: "commitmentId",
963
+ type: "uint256"
964
+ }],
965
+ outputs: [{
966
+ name: "",
967
+ type: "uint256"
968
+ }]
969
+ },
970
+ {
971
+ type: "function",
972
+ name: "commitments",
973
+ stateMutability: "view",
974
+ inputs: [{
975
+ name: "",
976
+ type: "uint256"
977
+ }],
978
+ outputs: [
979
+ {
980
+ name: "creator",
981
+ type: "address"
982
+ },
983
+ {
984
+ name: "token",
985
+ type: "address"
986
+ },
987
+ {
988
+ name: "recipient",
989
+ type: "address"
990
+ },
991
+ {
992
+ name: "totalAmount",
993
+ type: "uint256"
994
+ },
995
+ {
996
+ name: "claimed",
997
+ type: "uint256"
998
+ },
999
+ {
1000
+ name: "startTime",
1001
+ type: "uint48"
1002
+ },
1003
+ {
1004
+ name: "cliffTime",
1005
+ type: "uint48"
1006
+ },
1007
+ {
1008
+ name: "endTime",
1009
+ type: "uint48"
1010
+ },
1011
+ {
1012
+ name: "documentHash",
1013
+ type: "bytes32"
1014
+ },
1015
+ {
1016
+ name: "paymentType",
1017
+ type: "uint8"
1018
+ },
1019
+ {
1020
+ name: "cancelled",
1021
+ type: "bool"
1022
+ }
1023
+ ]
1024
+ }
1025
+ ];
1026
+ function normalizeUint48(value, field) {
1027
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffffffff) throw new RangeError(`${field} must be a uint48 (epoch seconds)`);
1028
+ return value;
1029
+ }
1030
+ /**
1031
+ * Encode a personal Safe's `createCommitment` UserOp: approve + createCommitment
1032
+ * batched through a delegatecall into MultiSendCallOnly (one sponsored UserOp).
1033
+ * The creator (payer Safe) escrows `totalAmount` into CapxulPayments.
1034
+ */
1035
+ function buildCapxulCreateCommitmentPersonalCallData(input) {
1036
+ const tokenAddress = normalizeAddress(input.tokenAddress, "tokenAddress");
1037
+ const recipientAddress = normalizeAddress(input.recipientAddress, "recipientAddress");
1038
+ const totalAmount = normalizePositiveAmount(input.totalAmount, "totalAmount");
1039
+ const startTime = normalizeUint48(input.startTime, "startTime");
1040
+ const cliffTime = normalizeUint48(input.cliffTime, "cliffTime");
1041
+ const endTime = normalizeUint48(input.endTime, "endTime");
1042
+ if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) throw new RangeError("commitment times must satisfy start <= cliff <= end");
1043
+ const documentHash = normalizeBytes32(input.documentHash ?? `0x${"0".repeat(64)}`, "documentHash");
1044
+ const paymentType = normalizeUint8(input.paymentType ?? 0, "paymentType");
1045
+ return encodeFunctionData({
1046
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
1047
+ functionName: "executeUserOpWithErrorString",
1048
+ args: [
1049
+ MULTI_SEND_CALL_ONLY,
1050
+ 0n,
1051
+ encodeFunctionData({
1052
+ abi: MULTI_SEND_CALL_ONLY_ABI,
1053
+ functionName: "multiSend",
1054
+ args: [concat([{
1055
+ to: tokenAddress,
1056
+ data: encodeFunctionData({
1057
+ abi: ERC20_APPROVE_ABI,
1058
+ functionName: "approve",
1059
+ args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount]
1060
+ }),
1061
+ value: 0n
1062
+ }, {
1063
+ to: CAPXUL_PAYMENTS_ADDRESS,
1064
+ data: encodeFunctionData({
1065
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1066
+ functionName: "createCommitment",
1067
+ args: [
1068
+ tokenAddress,
1069
+ recipientAddress,
1070
+ totalAmount,
1071
+ startTime,
1072
+ cliffTime,
1073
+ endTime,
1074
+ documentHash,
1075
+ paymentType
1076
+ ]
1077
+ }),
1078
+ value: 0n
1079
+ }].map(encodeMultiSendCallTransaction))]
1080
+ }),
1081
+ OPERATION_DELEGATECALL
1082
+ ]
1083
+ });
1084
+ }
1085
+ function buildSingleCapxulPaymentsCallData(data) {
1086
+ return encodeFunctionData({
1087
+ abi: SAFE4337_EXECUTE_USEROP_ABI,
1088
+ functionName: "executeUserOpWithErrorString",
1089
+ args: [
1090
+ CAPXUL_PAYMENTS_ADDRESS,
1091
+ 0n,
1092
+ data,
1093
+ OPERATION_CALL
1094
+ ]
1095
+ });
1096
+ }
1097
+ /** Encode a recipient Safe's `claim(commitmentId)` UserOp callData. */
1098
+ function buildCapxulCommitmentClaimCallData(commitmentId) {
1099
+ return buildSingleCapxulPaymentsCallData(encodeFunctionData({
1100
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1101
+ functionName: "claim",
1102
+ args: [commitmentId]
1103
+ }));
1104
+ }
1105
+ /** Encode a creator Safe's `cancel(commitmentId, documentHash)` UserOp callData. */
1106
+ function buildCapxulCommitmentCancelCallData(commitmentId, documentHash) {
1107
+ return buildSingleCapxulPaymentsCallData(encodeFunctionData({
1108
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1109
+ functionName: "cancel",
1110
+ args: [commitmentId, normalizeBytes32(documentHash ?? `0x${"0".repeat(64)}`, "documentHash")]
1111
+ }));
1112
+ }
1113
+ /** Encode a creator Safe's `redirect(commitmentId, newRecipient, newDocumentHash)` UserOp callData. */
1114
+ function buildCapxulCommitmentRedirectCallData(commitmentId, newRecipient, newDocumentHash) {
1115
+ return buildSingleCapxulPaymentsCallData(encodeFunctionData({
1116
+ abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,
1117
+ functionName: "redirect",
1118
+ args: [
1119
+ commitmentId,
1120
+ normalizeAddress(newRecipient, "newRecipient"),
1121
+ normalizeBytes32(newDocumentHash ?? `0x${"0".repeat(64)}`, "newDocumentHash")
1122
+ ]
1123
+ }));
1124
+ }
1125
+ //#endregion
1126
+ //#region ../../packages/config/src/route.ts
1127
+ /** USDX on Base Sepolia — the only settlement token in v1. */
1128
+ const USDX_BASE_SEPOLIA_TOKEN = {
1129
+ chainId: BASE_SEPOLIA_CHAIN_ID,
1130
+ address: USDX_ADDRESS_BASE_SEPOLIA,
1131
+ decimals: 6
1132
+ };
1133
+ /**
1134
+ * The `direct-base` settlement route: USDX on Base Sepolia, settled directly
1135
+ * through the `CapxulPayments` contract. This is the ONLY route implemented in
1136
+ * D1; the `Route` shape is the seam future provider routes slot into.
1137
+ */
1138
+ const DIRECT_BASE_ROUTE = {
1139
+ kind: "direct-base",
1140
+ token: USDX_BASE_SEPOLIA_TOKEN,
1141
+ chainId: USDX_BASE_SEPOLIA_TOKEN.chainId,
1142
+ verifyingContract: CAPXUL_PAYMENTS_ADDRESS
1143
+ };
1144
+ USDX_BASE_SEPOLIA_TOKEN.chainId;
1145
+ //#endregion
1146
+ //#region ../../packages/config/src/org-safe.ts
1147
+ /**
1148
+ * Per-version Capxul Org Safe salt namespace (D10a). Distinct from the
1149
+ * personal-Safe namespace (`capxul:safe:email:v1`) so an Org Safe and a
1150
+ * personal Safe with the same `(signer, email)` never collide. Bump only when
1151
+ * the Org Safe scheme itself changes (e.g. a Safe factory bytecode migration).
1152
+ */
1153
+ const CAPXUL_ORG_SALT_NAMESPACE = "capxul:org:v1";
1154
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
1155
+ const ORG_HANDLE_REGEX = /^[a-z0-9-]{3,32}$/;
1156
+ const ADDRESS_REGEX = /^0x[0-9a-f]{40}$/;
1157
+ const safeSetupAbi = [{
1158
+ type: "function",
1159
+ name: "setup",
1160
+ stateMutability: "nonpayable",
1161
+ inputs: [
1162
+ {
1163
+ name: "_owners",
1164
+ type: "address[]"
1165
+ },
1166
+ {
1167
+ name: "_threshold",
1168
+ type: "uint256"
1169
+ },
1170
+ {
1171
+ name: "to",
1172
+ type: "address"
1173
+ },
1174
+ {
1175
+ name: "data",
1176
+ type: "bytes"
1177
+ },
1178
+ {
1179
+ name: "fallbackHandler",
1180
+ type: "address"
1181
+ },
1182
+ {
1183
+ name: "paymentToken",
1184
+ type: "address"
1185
+ },
1186
+ {
1187
+ name: "payment",
1188
+ type: "uint256"
1189
+ },
1190
+ {
1191
+ name: "paymentReceiver",
1192
+ type: "address"
1193
+ }
1194
+ ],
1195
+ outputs: []
1196
+ }];
1197
+ const enableModulesAbi = [{
1198
+ type: "function",
1199
+ name: "enableModules",
1200
+ stateMutability: "nonpayable",
1201
+ inputs: [{
1202
+ name: "modules",
1203
+ type: "address[]"
1204
+ }],
1205
+ outputs: []
1206
+ }];
1207
+ const multiSendAbi = [{
1208
+ type: "function",
1209
+ name: "multiSend",
1210
+ stateMutability: "payable",
1211
+ inputs: [{
1212
+ name: "transactions",
1213
+ type: "bytes"
1214
+ }],
1215
+ outputs: []
1216
+ }];
1217
+ /**
1218
+ * Normalize an org handle for both salting and storage (D10a — trim +
1219
+ * lowercase). Idempotent: `normalizeOrgHandle(normalizeOrgHandle(x)) ===
1220
+ * normalizeOrgHandle(x)`.
1221
+ *
1222
+ * @param handle - The raw org handle
1223
+ * @returns The trimmed, lowercased handle
1224
+ */
1225
+ function normalizeOrgHandle(handle) {
1226
+ return handle.trim().toLowerCase();
1227
+ }
1228
+ /**
1229
+ * Validate an org handle against the D10a rule `^[a-z0-9-]{3,32}$` over its
1230
+ * NORMALIZED form. Returns the normalized handle on success; throws a typed
1231
+ * `INVALID_INPUT` `CapxulError` (field `orgHandle`) on failure — never a raw
1232
+ * `Error`, so SDK / backend boundary handlers can route on the code.
1233
+ *
1234
+ * @param handle - The raw org handle
1235
+ * @returns The normalized, validated handle
1236
+ */
1237
+ function validateOrgHandle(handle) {
1238
+ const normalized = normalizeOrgHandle(handle);
1239
+ if (!ORG_HANDLE_REGEX.test(normalized)) throw Errors.invalidInput("orgHandle", `must match ^[a-z0-9-]{3,32}$ after trim+lowercase, got ${handle}`);
1240
+ return normalized;
1241
+ }
1242
+ /**
1243
+ * Compute the deterministic Org Safe salt nonce for a `(namespace, email,
1244
+ * orgHandle)` triple (D10a). The salt nonce is the `bigint` reading of
1245
+ * `keccak256(namespace + ":" + normalizeSafeSaltEmail(email) + ":" +
1246
+ * normalizeOrgHandle(orgHandle))`.
1247
+ *
1248
+ * Keyed on email + handle, NOT the signer — so the Org address survives signer
1249
+ * rotation (D7). Namespace defaults to `CAPXUL_ORG_SALT_NAMESPACE`.
1250
+ *
1251
+ * @param input.email - The founder email to derive the salt nonce from
1252
+ * @param input.orgHandle - The org handle (normalized internally)
1253
+ * @param input.namespace - Optional namespace override
1254
+ * @returns The Capxul-namespaced Org salt nonce as a `bigint`
1255
+ */
1256
+ function computeCapxulOrgSaltNonce(input) {
1257
+ const namespace = input.namespace ?? "capxul:org:v1";
1258
+ const normalizedEmail = normalizeSafeSaltEmail(input.email);
1259
+ const normalizedHandle = normalizeOrgHandle(input.orgHandle);
1260
+ return BigInt(keccak256(toBytes(`${namespace}:${normalizedEmail}:${normalizedHandle}`)));
1261
+ }
1262
+ /**
1263
+ * Pure derivation of the Org Safe v1.4.1 (SafeL2) + 4337-module-enabled
1264
+ * counterfactual address for a Capxul `(founderPersonalSafe, email, orgHandle)`
1265
+ * triple (D10a). Mirrors `deriveCapxulSafeAddress` byte-for-byte except the salt
1266
+ * nonce (Org-namespaced, keyed on email+handle) and the initializer owner
1267
+ * (the founder's PERSONAL Safe address, passed in directly — D7).
1268
+ *
1269
+ * Returns the lowercased `0x` + 40 hex string (raw — no brand applied; callers
1270
+ * brand at their own boundary). Throws a typed `INVALID_INPUT` `CapxulError`
1271
+ * (field `orgHandle`) if the handle is malformed.
1272
+ *
1273
+ * Canonical conformance: `packages/config/tests/org-safe-address-conformance.test.ts`
1274
+ * pins the matrix against Safes actually deployed on Base Sepolia.
1275
+ */
1276
+ /**
1277
+ * Build the EXACT Org Safe `setup()` initializer calldata (D10a). This is the
1278
+ * single source of truth for the initializer bytes: `deriveCapxulOrgAddress`
1279
+ * hashes it into the CREATE2 salt, and the live Org deploy adapter passes the
1280
+ * IDENTICAL bytes to `SafeProxyFactory.createProxyWithNonce` — so the deployed
1281
+ * address provably equals the counterfactual byte-for-byte.
1282
+ *
1283
+ * `setup([founderPersonalSafe], 1, MULTI_SEND, <enableModules([SAFE_4337_MODULE])
1284
+ * MultiSend>, SAFE_4337_MODULE, 0, 0, 0)` — owner is the founder's PERSONAL Safe
1285
+ * (D7), the 4337 module is enabled via the same MultiSend lane as the personal
1286
+ * Safe. NO Zodiac Roles / Allowance at setup() (S1 decision A — those land in S2).
1287
+ *
1288
+ * Validates (and lowercases) `founderPersonalSafe`; throws a typed INVALID_INPUT
1289
+ * (`founderPersonalSafe`) on a malformed address.
1290
+ *
1291
+ * @param input.founderPersonalSafe - The founder's personal Safe address (owner)
1292
+ * @returns The `0x`-prefixed `setup()` calldata
1293
+ */
1294
+ function buildCapxulOrgInitializer(input) {
1295
+ const founderPersonalSafe = input.founderPersonalSafe.toLowerCase();
1296
+ if (!ADDRESS_REGEX.test(founderPersonalSafe)) throw Errors.invalidInput("founderPersonalSafe", `must be 0x + 40 hex chars, got ${input.founderPersonalSafe}`);
1297
+ const enableModulesCall = encodeFunctionData({
1298
+ abi: enableModulesAbi,
1299
+ functionName: "enableModules",
1300
+ args: [[SAFE_4337_MODULE]]
1301
+ });
1302
+ const setupData = encodeFunctionData({
1303
+ abi: multiSendAbi,
1304
+ functionName: "multiSend",
1305
+ args: [encodePacked([
1306
+ "uint8",
1307
+ "address",
1308
+ "uint256",
1309
+ "uint256",
1310
+ "bytes"
1311
+ ], [
1312
+ 1,
1313
+ SAFE_MODULE_SETUP,
1314
+ 0n,
1315
+ BigInt((enableModulesCall.length - 2) / 2),
1316
+ enableModulesCall
1317
+ ])]
1318
+ });
1319
+ return encodeFunctionData({
1320
+ abi: safeSetupAbi,
1321
+ functionName: "setup",
1322
+ args: [
1323
+ [founderPersonalSafe],
1324
+ 1n,
1325
+ MULTI_SEND,
1326
+ setupData,
1327
+ SAFE_4337_MODULE,
1328
+ ZERO_ADDRESS,
1329
+ 0n,
1330
+ ZERO_ADDRESS
1331
+ ]
1332
+ });
1333
+ }
1334
+ function deriveCapxulOrgAddress(input) {
1335
+ const orgHandle = validateOrgHandle(input.orgHandle);
1336
+ const initializer = buildCapxulOrgInitializer({ founderPersonalSafe: input.founderPersonalSafe });
1337
+ const saltNonce = computeCapxulOrgSaltNonce({
1338
+ email: input.email,
1339
+ orgHandle
1340
+ });
1341
+ return getContractAddress({
1342
+ opcode: "CREATE2",
1343
+ from: SAFE_PROXY_FACTORY,
1344
+ salt: keccak256(encodePacked(["bytes32", "uint256"], [keccak256(initializer), saltNonce])),
1345
+ bytecodeHash: keccak256(concat([SAFE_PROXY_CREATION_CODE, encodeAbiParameters([{ type: "uint256" }], [BigInt(SAFE_L2_SINGLETON)])]))
1346
+ }).toLowerCase();
1347
+ }
1348
+ //#endregion
1349
+ //#region ../../packages/config/src/role-dsl.ts
1350
+ const USD_DECIMALS = 6;
1351
+ const USD_SCALE = 10n ** BigInt(USD_DECIMALS);
1352
+ const USD_DISPLAY_RE = /^\d+(?:\.\d{1,6})?$/;
1353
+ const USD_BASE_UNIT_RE = /^\d+$/;
1354
+ const EXEC_TRANSACTION_WITH_ROLE$1 = "zodiac.roles.execTransactionWithRole";
1355
+ const ASSIGN_ROLES = "zodiac.roles.assignRoles";
1356
+ const SCOPE_TARGET = "zodiac.roles.scopeTarget";
1357
+ const OWNER_ROLE_LABEL = "Owner";
1358
+ const MARKETING_SUB_ACCOUNT_ID = "subaccount_marketing";
1359
+ const PAYROLL_SUB_ACCOUNT_ID = "subaccount_payroll";
1360
+ function usd(value) {
1361
+ return {
1362
+ currency: "USD",
1363
+ value: usdDisplayToBaseUnits(value),
1364
+ decimals: USD_DECIMALS
1365
+ };
1366
+ }
1367
+ function usdDisplayToBaseUnits(value) {
1368
+ if (value.trim() !== value || !USD_DISPLAY_RE.test(value)) throw Errors.invalidInput("role.spend", "USD caps must be unsigned decimal strings with at most 6 fractional digits");
1369
+ const parts = value.split(".");
1370
+ const whole = parts[0] ?? "0";
1371
+ const fraction = parts[1] ?? "";
1372
+ return (BigInt(whole) * USD_SCALE + BigInt(fraction.padEnd(USD_DECIMALS, "0"))).toString();
1373
+ }
1374
+ function normalizeOrgRoleMoney(money, field) {
1375
+ if (money.currency !== "USD" || money.decimals !== USD_DECIMALS || !USD_BASE_UNIT_RE.test(money.value)) throw Errors.invalidInput(field, `must be USD base units with ${USD_DECIMALS} decimals`);
1376
+ return money;
1377
+ }
1378
+ function normalizeOrgRoleSpendCap(spend) {
1379
+ if (spend === void 0) return void 0;
1380
+ return {
1381
+ ...spend.perTx === void 0 ? {} : { perTx: normalizeOrgRoleMoney(spend.perTx, "roles.spend.perTx") },
1382
+ ...spend.perDay === void 0 ? {} : { perDay: normalizeOrgRoleMoney(spend.perDay, "roles.spend.perDay") },
1383
+ ...spend.toRecipients === void 0 ? {} : { toRecipients: spend.toRecipients }
1384
+ };
1385
+ }
1386
+ function normalizeOrgRoleLabel(label) {
1387
+ const normalized = label.trim().replace(/\s+/g, " ");
1388
+ if (normalized.length === 0) throw Errors.invalidInput("role.label", "must be a non-empty role label");
1389
+ return normalized;
1390
+ }
1391
+ function orgRoleKeyForLabel(label) {
1392
+ return keccak256(toBytes(normalizeOrgRoleLabel(label).toLowerCase()));
1393
+ }
1394
+ function soloOrgRoleTemplate() {
1395
+ return [{
1396
+ label: "Owner",
1397
+ subAccounts: { scope: "all" },
1398
+ canManageMembers: true,
1399
+ canManageRoles: true
1400
+ }];
1401
+ }
1402
+ function startupOrgRoleTemplate() {
1403
+ return [
1404
+ ...soloOrgRoleTemplate(),
1405
+ {
1406
+ label: "Finance Manager",
1407
+ spend: {
1408
+ perTx: usd("25000"),
1409
+ perDay: usd("100000"),
1410
+ toRecipients: "anyone"
1411
+ },
1412
+ subAccounts: { scope: [MARKETING_SUB_ACCOUNT_ID] }
1413
+ },
1414
+ {
1415
+ label: "Team Lead",
1416
+ spend: {
1417
+ perTx: usd("5000"),
1418
+ perDay: usd("15000"),
1419
+ toRecipients: "anyone"
1420
+ },
1421
+ subAccounts: { scope: [PAYROLL_SUB_ACCOUNT_ID] }
1422
+ }
1423
+ ];
1424
+ }
1425
+ function orgRoleTemplateDefinitions(template, customRoles = []) {
1426
+ switch (template) {
1427
+ case "Solo": return soloOrgRoleTemplate();
1428
+ case "Startup": return startupOrgRoleTemplate();
1429
+ case "Custom": return customRoles.length === 0 ? soloOrgRoleTemplate() : customRoles;
1430
+ default: return template;
1431
+ }
1432
+ }
1433
+ function compileOrgRoleDefinitions(definitions) {
1434
+ if (definitions.length === 0) throw Errors.invalidInput("roles", "must include at least one role");
1435
+ const seen = /* @__PURE__ */ new Set();
1436
+ const roles = definitions.map((definition) => {
1437
+ const label = normalizeOrgRoleLabel(definition.label);
1438
+ const roleKey = orgRoleKeyForLabel(label);
1439
+ if (seen.has(roleKey)) throw Errors.invalidInput("roles", `duplicate role label: ${label}`);
1440
+ seen.add(roleKey);
1441
+ const spend = normalizeOrgRoleSpendCap(definition.spend);
1442
+ const permissions = [];
1443
+ if (spend !== void 0 || label === OWNER_ROLE_LABEL) permissions.push(EXEC_TRANSACTION_WITH_ROLE$1);
1444
+ if (definition.canManageMembers === true) permissions.push(ASSIGN_ROLES);
1445
+ if (definition.canManageRoles === true) permissions.push(SCOPE_TARGET);
1446
+ return {
1447
+ label,
1448
+ roleKey,
1449
+ definition: {
1450
+ ...definition,
1451
+ label,
1452
+ ...spend === void 0 ? {} : { spend }
1453
+ },
1454
+ permissions,
1455
+ allowance: spend ?? null
1456
+ };
1457
+ });
1458
+ const manager = roles.find((role) => role.definition.canManageMembers === true);
1459
+ if (manager === void 0) throw Errors.invalidInput("roles.canManageMembers", "at least one role must compile to the on-chain member-management permission");
1460
+ return {
1461
+ roles,
1462
+ memberManagementRole: {
1463
+ roleKey: manager.roleKey,
1464
+ permission: ASSIGN_ROLES
1465
+ }
1466
+ };
1467
+ }
1468
+ //#endregion
1469
+ //#region ../../packages/config/src/org-zodiac.ts
1470
+ const MODULE_PROXY_FACTORY_ABI = [{
1471
+ type: "function",
1472
+ name: "deployModule",
1473
+ stateMutability: "nonpayable",
1474
+ inputs: [
1475
+ {
1476
+ name: "masterCopy",
1477
+ type: "address"
1478
+ },
1479
+ {
1480
+ name: "initializer",
1481
+ type: "bytes"
1482
+ },
1483
+ {
1484
+ name: "saltNonce",
1485
+ type: "uint256"
1486
+ }
1487
+ ],
1488
+ outputs: [{
1489
+ name: "proxy",
1490
+ type: "address"
1491
+ }]
1492
+ }];
1493
+ const SAFE_ENABLE_MODULE_ABI = [{
1494
+ type: "function",
1495
+ name: "enableModule",
1496
+ stateMutability: "nonpayable",
1497
+ inputs: [{
1498
+ name: "module",
1499
+ type: "address"
1500
+ }],
1501
+ outputs: []
1502
+ }];
1503
+ const ROLES_SET_UP_ABI = [{
1504
+ type: "function",
1505
+ name: "setUp",
1506
+ stateMutability: "nonpayable",
1507
+ inputs: [{
1508
+ name: "initParams",
1509
+ type: "bytes"
1510
+ }],
1511
+ outputs: []
1512
+ }];
1513
+ const ROLES_SET_ALLOWANCE_ABI = [{
1514
+ type: "function",
1515
+ name: "setAllowance",
1516
+ stateMutability: "nonpayable",
1517
+ inputs: [
1518
+ {
1519
+ name: "key",
1520
+ type: "bytes32"
1521
+ },
1522
+ {
1523
+ name: "balance",
1524
+ type: "uint128"
1525
+ },
1526
+ {
1527
+ name: "maxRefill",
1528
+ type: "uint128"
1529
+ },
1530
+ {
1531
+ name: "refill",
1532
+ type: "uint128"
1533
+ },
1534
+ {
1535
+ name: "period",
1536
+ type: "uint64"
1537
+ },
1538
+ {
1539
+ name: "timestamp",
1540
+ type: "uint64"
1541
+ }
1542
+ ],
1543
+ outputs: []
1544
+ }];
1545
+ const ROLES_SET_TRANSACTION_UNWRAPPER_ABI = [{
1546
+ type: "function",
1547
+ name: "setTransactionUnwrapper",
1548
+ stateMutability: "nonpayable",
1549
+ inputs: [
1550
+ {
1551
+ name: "target",
1552
+ type: "address"
1553
+ },
1554
+ {
1555
+ name: "selector",
1556
+ type: "bytes4"
1557
+ },
1558
+ {
1559
+ name: "adapter",
1560
+ type: "address"
1561
+ }
1562
+ ],
1563
+ outputs: []
1564
+ }];
1565
+ const ROLES_ASSIGN_ROLES_ABI = [{
1566
+ type: "function",
1567
+ name: "assignRoles",
1568
+ stateMutability: "nonpayable",
1569
+ inputs: [
1570
+ {
1571
+ name: "module",
1572
+ type: "address"
1573
+ },
1574
+ {
1575
+ name: "roleKeys",
1576
+ type: "bytes32[]"
1577
+ },
1578
+ {
1579
+ name: "memberOf",
1580
+ type: "bool[]"
1581
+ }
1582
+ ],
1583
+ outputs: []
1584
+ }];
1585
+ const ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI = [{
1586
+ type: "function",
1587
+ name: "execTransactionWithRole",
1588
+ stateMutability: "nonpayable",
1589
+ inputs: [
1590
+ {
1591
+ name: "to",
1592
+ type: "address"
1593
+ },
1594
+ {
1595
+ name: "value",
1596
+ type: "uint256"
1597
+ },
1598
+ {
1599
+ name: "data",
1600
+ type: "bytes"
1601
+ },
1602
+ {
1603
+ name: "operation",
1604
+ type: "uint8"
1605
+ },
1606
+ {
1607
+ name: "roleKey",
1608
+ type: "bytes32"
1609
+ },
1610
+ {
1611
+ name: "shouldRevert",
1612
+ type: "bool"
1613
+ }
1614
+ ],
1615
+ outputs: [{
1616
+ name: "success",
1617
+ type: "bool"
1618
+ }]
1619
+ }];
1620
+ const ORG_ROLE_ALLOWANCE_KEYS = {
1621
+ financeManagerDaily: padHex(stringToHex("FM_DAILY"), {
1622
+ size: 32,
1623
+ dir: "right"
1624
+ }),
1625
+ teamLeadDaily: padHex(stringToHex("TL_DAILY"), {
1626
+ size: 32,
1627
+ dir: "right"
1628
+ })
1629
+ };
1630
+ const MULTI_SEND_SELECTOR = "0x8d80ff0a";
1631
+ const ONE_DAY_SECONDS = 86400n;
1632
+ const ZODIAC_OPERATION_CALL = 0;
1633
+ const EXEC_TRANSACTION_WITH_ROLE = "zodiac.roles.execTransactionWithRole";
1634
+ const PARAMETER_TYPE = {
1635
+ none: 0,
1636
+ static: 1,
1637
+ calldata: 5
1638
+ };
1639
+ const OPERATOR = {
1640
+ pass: 0,
1641
+ and: 1,
1642
+ or: 2,
1643
+ matches: 5,
1644
+ equalTo: 16,
1645
+ lessThan: 18,
1646
+ withinAllowance: 28
1647
+ };
1648
+ function normalizeHexAddress(address) {
1649
+ return address.toLowerCase();
1650
+ }
1651
+ function orgRoleAllowanceKeyForLabel(label) {
1652
+ const normalized = normalizeOrgRoleLabel(label);
1653
+ switch (normalized) {
1654
+ case "Finance Manager": return ORG_ROLE_ALLOWANCE_KEYS.financeManagerDaily;
1655
+ case "Team Lead": return ORG_ROLE_ALLOWANCE_KEYS.teamLeadDaily;
1656
+ default: return keccak256(stringToHex(`CAPXUL_ORG_DAILY_ALLOWANCE:${normalized.toLowerCase()}`));
1657
+ }
1658
+ }
1659
+ function passStatic() {
1660
+ return {
1661
+ paramType: PARAMETER_TYPE.static,
1662
+ operator: OPERATOR.pass
1663
+ };
1664
+ }
1665
+ function equalAddress(address) {
1666
+ return {
1667
+ paramType: PARAMETER_TYPE.static,
1668
+ operator: OPERATOR.equalTo,
1669
+ compValue: encodeAbiParameters([{ type: "address" }], [address])
1670
+ };
1671
+ }
1672
+ function lteUint256(value) {
1673
+ return {
1674
+ paramType: PARAMETER_TYPE.static,
1675
+ operator: OPERATOR.lessThan,
1676
+ compValue: encodeAbiParameters([{ type: "uint256" }], [BigInt(value) + 1n])
1677
+ };
1678
+ }
1679
+ function withinAllowance(allowanceKey) {
1680
+ return {
1681
+ paramType: PARAMETER_TYPE.static,
1682
+ operator: OPERATOR.withinAllowance,
1683
+ compValue: encodeAbiParameters([{ type: "bytes32" }], [allowanceKey])
1684
+ };
1685
+ }
1686
+ function and(...children) {
1687
+ return {
1688
+ paramType: PARAMETER_TYPE.none,
1689
+ operator: OPERATOR.and,
1690
+ children
1691
+ };
1692
+ }
1693
+ function calldataMatches(children) {
1694
+ return {
1695
+ paramType: PARAMETER_TYPE.calldata,
1696
+ operator: OPERATOR.matches,
1697
+ children
1698
+ };
1699
+ }
1700
+ /**
1701
+ * The on-chain recipient condition for a role's `toRecipients` scope. `"anyone"`
1702
+ * (or an empty/undefined set) leaves the recipient param unconstrained on-chain
1703
+ * (`passStatic` — recipient validation is the Level-2 off-chain guard). A FIXED
1704
+ * recipient set compiles to an `Or` over per-address equality so the on-chain
1705
+ * Roles modifier itself refuses any recipient outside the set — this is the
1706
+ * treasury-drain boundary for createCommitment / redirect, not just `send`.
1707
+ */
1708
+ function recipientCondition(toRecipients) {
1709
+ if (toRecipients === void 0 || toRecipients === "anyone" || toRecipients.length === 0) return passStatic();
1710
+ const equals = toRecipients.map((address) => equalAddress(normalizeHexAddress(address)));
1711
+ return equals.length === 1 ? equals[0] : orMatch(equals);
1712
+ }
1713
+ function orMatch(children) {
1714
+ return {
1715
+ paramType: PARAMETER_TYPE.none,
1716
+ operator: OPERATOR.or,
1717
+ children
1718
+ };
1719
+ }
1720
+ function encodeRolesSetUpCall(input) {
1721
+ return encodeFunctionData({
1722
+ abi: ROLES_SET_UP_ABI,
1723
+ functionName: "setUp",
1724
+ args: [encodeAbiParameters(parseAbiParameters("address, address, address"), [
1725
+ input.owner,
1726
+ input.avatar,
1727
+ input.target
1728
+ ])]
1729
+ });
1730
+ }
1731
+ function computeOrgRolesModuleAddress(input) {
1732
+ const saltNonce = input.saltNonce ?? 0n;
1733
+ const proxyInitCode = "0x602d8060093d393df3363d3d373d3d3d363d73" + ROLES_MASTERCOPY.slice(2).toLowerCase() + "5af43d82803e903d91602b57fd5bf3";
1734
+ return normalizeHexAddress(getContractAddress({
1735
+ opcode: "CREATE2",
1736
+ from: ZODIAC_MODULE_PROXY_FACTORY,
1737
+ salt: keccak256(keccak256(encodeRolesSetUpCall(input)) + encodeAbiParameters(parseAbiParameters("uint256"), [saltNonce]).slice(2)),
1738
+ bytecodeHash: keccak256(proxyInitCode)
1739
+ }));
1740
+ }
1741
+ function buildDeployModuleCall(input) {
1742
+ return {
1743
+ to: ZODIAC_MODULE_PROXY_FACTORY,
1744
+ data: encodeFunctionData({
1745
+ abi: MODULE_PROXY_FACTORY_ABI,
1746
+ functionName: "deployModule",
1747
+ args: [
1748
+ ROLES_MASTERCOPY,
1749
+ encodeRolesSetUpCall({
1750
+ owner: input.safeAddress,
1751
+ avatar: input.safeAddress,
1752
+ target: input.safeAddress
1753
+ }),
1754
+ input.saltNonce
1755
+ ]
1756
+ }),
1757
+ value: 0n
1758
+ };
1759
+ }
1760
+ function buildEnableModuleCall(input) {
1761
+ return {
1762
+ to: input.safeAddress,
1763
+ data: encodeFunctionData({
1764
+ abi: SAFE_ENABLE_MODULE_ABI,
1765
+ functionName: "enableModule",
1766
+ args: [input.rolesModuleAddress]
1767
+ }),
1768
+ value: 0n
1769
+ };
1770
+ }
1771
+ function buildSetUnwrapperCall(rolesModuleAddress) {
1772
+ return {
1773
+ to: rolesModuleAddress,
1774
+ data: encodeFunctionData({
1775
+ abi: ROLES_SET_TRANSACTION_UNWRAPPER_ABI,
1776
+ functionName: "setTransactionUnwrapper",
1777
+ args: [
1778
+ MULTI_SEND_CALL_ONLY,
1779
+ MULTI_SEND_SELECTOR,
1780
+ ZODIAC_MULTI_SEND_UNWRAPPER
1781
+ ]
1782
+ }),
1783
+ value: 0n
1784
+ };
1785
+ }
1786
+ function buildSetAllowanceCall(input) {
1787
+ const dailyCap = BigInt(input.dailyCap);
1788
+ return {
1789
+ to: input.rolesModuleAddress,
1790
+ data: encodeFunctionData({
1791
+ abi: ROLES_SET_ALLOWANCE_ABI,
1792
+ functionName: "setAllowance",
1793
+ args: [
1794
+ input.allowanceKey,
1795
+ dailyCap,
1796
+ dailyCap,
1797
+ dailyCap,
1798
+ ONE_DAY_SECONDS,
1799
+ 0n
1800
+ ]
1801
+ }),
1802
+ value: 0n
1803
+ };
1804
+ }
1805
+ function buildTemplateAllowanceCalls(input) {
1806
+ return input.roles.flatMap((role) => {
1807
+ const dailyCap = role?.allowance?.perDay?.value;
1808
+ return dailyCap === void 0 ? [] : [buildSetAllowanceCall({
1809
+ rolesModuleAddress: input.rolesModuleAddress,
1810
+ allowanceKey: orgRoleAllowanceKeyForLabel(role.label),
1811
+ dailyCap
1812
+ })];
1813
+ });
1814
+ }
1815
+ const CREATE_COMMITMENT_SIGNATURE = "createCommitment(address,address,uint256,uint48,uint48,uint48,bytes32,uint8)";
1816
+ const CANCEL_SIGNATURE = "cancel(uint256,bytes32)";
1817
+ const REDIRECT_SIGNATURE = "redirect(uint256,address,bytes32)";
1818
+ function approvePermission() {
1819
+ return {
1820
+ targetAddress: USDX_ADDRESS_BASE_SEPOLIA,
1821
+ signature: "approve(address,uint256)",
1822
+ condition: calldataMatches([equalAddress(CAPXUL_PAYMENTS_ADDRESS), passStatic()])
1823
+ };
1824
+ }
1825
+ function paymentPermissions(input) {
1826
+ return [approvePermission(), {
1827
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1828
+ signature: "send(address,address,uint256,bytes32,uint8)",
1829
+ condition: calldataMatches([
1830
+ equalAddress(USDX_ADDRESS_BASE_SEPOLIA),
1831
+ input.recipient,
1832
+ and(lteUint256(input.perTxCap), withinAllowance(input.allowanceKey)),
1833
+ passStatic(),
1834
+ passStatic()
1835
+ ])
1836
+ }];
1837
+ }
1838
+ function uncappedPaymentPermissions() {
1839
+ return [approvePermission(), {
1840
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1841
+ signature: "send(address,address,uint256,bytes32,uint8)",
1842
+ condition: calldataMatches([
1843
+ equalAddress(USDX_ADDRESS_BASE_SEPOLIA),
1844
+ passStatic(),
1845
+ passStatic(),
1846
+ passStatic(),
1847
+ passStatic()
1848
+ ])
1849
+ }];
1850
+ }
1851
+ /**
1852
+ * Commitment-verb permissions for a CAPPED role (#488 / G4 #547). `createCommitment`
1853
+ * carries the SAME on-chain conditions as `send`: token == USDX, the recipient
1854
+ * is in the role's allowed set, and the escrowed `totalAmount` is `<= perTx cap`
1855
+ * AND `withinAllowance(perDay key)`. `redirect` re-pins `newRecipient` to the
1856
+ * same allowed set (it changes who receives, so it is a recipient-boundary op).
1857
+ * `cancel` only reclaims unvested funds from a commitment the role created and
1858
+ * carries no recipient/amount, so it is allow-listed by selector with no comp
1859
+ * value. `claim` is NEVER emitted — it is recipient-side, not treasury authority.
1860
+ */
1861
+ function commitmentPermissions(input) {
1862
+ return [
1863
+ {
1864
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1865
+ signature: CREATE_COMMITMENT_SIGNATURE,
1866
+ condition: calldataMatches([
1867
+ equalAddress(USDX_ADDRESS_BASE_SEPOLIA),
1868
+ input.recipient,
1869
+ and(lteUint256(input.perTxCap), withinAllowance(input.allowanceKey)),
1870
+ passStatic(),
1871
+ passStatic(),
1872
+ passStatic(),
1873
+ passStatic(),
1874
+ passStatic()
1875
+ ])
1876
+ },
1877
+ {
1878
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1879
+ signature: REDIRECT_SIGNATURE,
1880
+ condition: calldataMatches([
1881
+ passStatic(),
1882
+ input.recipient,
1883
+ passStatic()
1884
+ ])
1885
+ },
1886
+ {
1887
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1888
+ signature: CANCEL_SIGNATURE,
1889
+ condition: calldataMatches([passStatic(), passStatic()])
1890
+ }
1891
+ ];
1892
+ }
1893
+ /** Uncapped commitment permissions for the Owner role (no per-tx/recipient cap). */
1894
+ function uncappedCommitmentPermissions() {
1895
+ return [
1896
+ {
1897
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1898
+ signature: CREATE_COMMITMENT_SIGNATURE,
1899
+ condition: calldataMatches([
1900
+ equalAddress(USDX_ADDRESS_BASE_SEPOLIA),
1901
+ passStatic(),
1902
+ passStatic(),
1903
+ passStatic(),
1904
+ passStatic(),
1905
+ passStatic(),
1906
+ passStatic(),
1907
+ passStatic()
1908
+ ])
1909
+ },
1910
+ {
1911
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1912
+ signature: REDIRECT_SIGNATURE,
1913
+ condition: calldataMatches([
1914
+ passStatic(),
1915
+ passStatic(),
1916
+ passStatic()
1917
+ ])
1918
+ },
1919
+ {
1920
+ targetAddress: CAPXUL_PAYMENTS_ADDRESS,
1921
+ signature: CANCEL_SIGNATURE,
1922
+ condition: calldataMatches([passStatic(), passStatic()])
1923
+ }
1924
+ ];
1925
+ }
1926
+ function rolePermissions(input) {
1927
+ const permissions = [];
1928
+ if (input.role.definition.canManageMembers === true) permissions.push({
1929
+ targetAddress: input.rolesModuleAddress,
1930
+ signature: "assignRoles(address,bytes32[],bool[])"
1931
+ });
1932
+ if (input.role.allowance === null && input.role.permissions.includes(EXEC_TRANSACTION_WITH_ROLE)) permissions.push(...uncappedPaymentPermissions(), ...uncappedCommitmentPermissions());
1933
+ if (input.role.allowance?.perTx !== void 0 && input.role.allowance.perDay !== void 0) {
1934
+ const allowanceKey = orgRoleAllowanceKeyForLabel(input.role.label);
1935
+ const perTxCap = input.role.allowance.perTx.value;
1936
+ const recipient = recipientCondition(input.role.allowance.toRecipients);
1937
+ permissions.push(...paymentPermissions({
1938
+ allowanceKey,
1939
+ perTxCap,
1940
+ recipient
1941
+ }), ...commitmentPermissions({
1942
+ allowanceKey,
1943
+ perTxCap,
1944
+ recipient
1945
+ }));
1946
+ }
1947
+ return permissions;
1948
+ }
1949
+ async function getZodiacSdk() {
1950
+ return await import("./src-Cg8p_ZgR.mjs");
1951
+ }
1952
+ async function buildRoleSetupCalls(input) {
1953
+ const managerRoleKey = input.managerRoleKey.toLowerCase();
1954
+ const roles = input.roles.map((role) => ({
1955
+ key: role.roleKey,
1956
+ members: role.roleKey.toLowerCase() === managerRoleKey ? [input.ownerAddress] : [],
1957
+ permissions: rolePermissions({
1958
+ role,
1959
+ rolesModuleAddress: input.rolesModuleAddress
1960
+ })
1961
+ }));
1962
+ return (await getZodiacSdk()).setUpRoles({
1963
+ address: input.rolesModuleAddress,
1964
+ roles
1965
+ }).map((call) => ({
1966
+ to: normalizeHexAddress(call.to),
1967
+ data: call.data,
1968
+ value: BigInt(call.value)
1969
+ }));
1970
+ }
1971
+ async function buildOrgRolesDeployCalls(input) {
1972
+ const safeAddress = normalizeHexAddress(input.safeAddress);
1973
+ const ownerAddress = normalizeHexAddress(input.ownerAddress);
1974
+ const saltNonce = input.saltNonce ?? 0n;
1975
+ const compiled = compileOrgRoleDefinitions(input.roleDefinitions ?? startupOrgRoleTemplate());
1976
+ const rolesModuleAddress = computeOrgRolesModuleAddress({
1977
+ owner: safeAddress,
1978
+ avatar: safeAddress,
1979
+ target: safeAddress,
1980
+ saltNonce
1981
+ });
1982
+ return {
1983
+ rolesModuleAddress,
1984
+ calls: [
1985
+ buildDeployModuleCall({
1986
+ safeAddress,
1987
+ saltNonce
1988
+ }),
1989
+ buildEnableModuleCall({
1990
+ safeAddress,
1991
+ rolesModuleAddress
1992
+ }),
1993
+ buildSetUnwrapperCall(rolesModuleAddress),
1994
+ ...buildTemplateAllowanceCalls({
1995
+ rolesModuleAddress,
1996
+ roles: compiled.roles
1997
+ }),
1998
+ ...await buildRoleSetupCalls({
1999
+ rolesModuleAddress,
2000
+ ownerAddress,
2001
+ roles: compiled.roles,
2002
+ managerRoleKey: compiled.memberManagementRole.roleKey
2003
+ })
2004
+ ]
2005
+ };
2006
+ }
2007
+ function buildOrgRoleAssignmentCall(input) {
2008
+ const rolesModuleAddress = normalizeHexAddress(input.rolesModuleAddress);
2009
+ const memberAddress = normalizeHexAddress(input.memberAddress);
2010
+ const roleKey = input.roleKey.toLowerCase();
2011
+ const managerRoleKey = input.managerRoleKey.toLowerCase();
2012
+ return {
2013
+ to: rolesModuleAddress,
2014
+ data: encodeFunctionData({
2015
+ abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI,
2016
+ functionName: "execTransactionWithRole",
2017
+ args: [
2018
+ rolesModuleAddress,
2019
+ 0n,
2020
+ encodeFunctionData({
2021
+ abi: ROLES_ASSIGN_ROLES_ABI,
2022
+ functionName: "assignRoles",
2023
+ args: [
2024
+ memberAddress,
2025
+ [roleKey],
2026
+ [input.memberOf]
2027
+ ]
2028
+ }),
2029
+ ZODIAC_OPERATION_CALL,
2030
+ managerRoleKey,
2031
+ true
2032
+ ]
2033
+ }),
2034
+ value: 0n
2035
+ };
2036
+ }
2037
+ //#endregion
2038
+ 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 };