@capxul/mcp 2.3.2 → 2.5.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.
Files changed (2) hide show
  1. package/dist/main.mjs +558 -141
  2. package/package.json +4 -4
package/dist/main.mjs CHANGED
@@ -240,7 +240,7 @@ function normalizeEmail(email) {
240
240
  }
241
241
  //#endregion
242
242
  //#region package.json
243
- var version$2 = "2.3.2";
243
+ var version$2 = "2.5.0";
244
244
  //#endregion
245
245
  //#region ../../packages/errors/src/errors.ts
246
246
  const CAPXUL_ERROR_CODES = [
@@ -2398,6 +2398,12 @@ function toPartyId(raw) {
2398
2398
  function toBudgetId(raw) {
2399
2399
  return toNonEmptyStringBrand(raw, "budgetId");
2400
2400
  }
2401
+ function toPayrollRunId(raw) {
2402
+ return toNonEmptyStringBrand(raw, "payrollRunId");
2403
+ }
2404
+ function toPayrollGroupId(raw) {
2405
+ return toNonEmptyStringBrand(raw, "payrollGroupId");
2406
+ }
2401
2407
  function toOrgId(raw) {
2402
2408
  return toNonEmptyStringBrand(raw, "orgId");
2403
2409
  }
@@ -2554,7 +2560,8 @@ const EngineeringTelemetryBootstrapPolicy = Schema.Struct({
2554
2560
  capxulEnv: Schema.Union([
2555
2561
  Schema.Literal("development"),
2556
2562
  Schema.Literal("staging"),
2557
- Schema.Literal("production")
2563
+ Schema.Literal("production"),
2564
+ Schema.Literal("local")
2558
2565
  ])
2559
2566
  });
2560
2567
  /**
@@ -2645,7 +2652,8 @@ const CAPXUL_FUNCTIONS = {
2645
2652
  "movement/activity": {
2646
2653
  annotate: "movement/activity:annotate",
2647
2654
  get: "movement/activity:get",
2648
- list: "movement/activity:list"
2655
+ list: "movement/activity:list",
2656
+ summary: "movement/activity:summary"
2649
2657
  },
2650
2658
  "moneyExecution/actions": {
2651
2659
  preparePermissionExecution: "moneyExecution/actions:preparePermissionExecution",
@@ -2673,6 +2681,15 @@ const CAPXUL_FUNCTIONS = {
2673
2681
  resumeBootstrapSubmission: "org/actions:resumeBootstrapSubmission",
2674
2682
  submitBootstrap: "org/actions:submitBootstrap"
2675
2683
  },
2684
+ "payroll/actions": { authorizeRun: "payroll/actions:authorizeRun" },
2685
+ "payroll/mutations": {
2686
+ removeGroup: "payroll/mutations:removeGroup",
2687
+ saveGroup: "payroll/mutations:saveGroup"
2688
+ },
2689
+ "payroll/queries": {
2690
+ groups: "payroll/queries:groups",
2691
+ runs: "payroll/queries:runs"
2692
+ },
2676
2693
  "permission/actions": { verify: "permission/actions:verify" },
2677
2694
  "permission/mutations": { command: "permission/mutations:command" },
2678
2695
  "permission/queries": {
@@ -3866,7 +3883,7 @@ Schema.Struct({
3866
3883
  items: Schema.Array(OrganizationPaymentExecutionItemSchema),
3867
3884
  lineage: Schema.optional(PaymentCommandLineageSchema)
3868
3885
  });
3869
- Schema.Struct({
3886
+ const PreparedPaymentCommandExecutionSchema = Schema.Struct({
3870
3887
  executionId: MoneyExecutionIdSchema,
3871
3888
  commandId: PaymentCommandIdSchema,
3872
3889
  paymentIds: Schema.Array(PaymentIdSchema),
@@ -3959,6 +3976,69 @@ Schema.Struct({
3959
3976
  userOpHash: Bytes32Schema,
3960
3977
  value: PermissionResourceSchema
3961
3978
  });
3979
+ const PayrollRunStatusSchema = Schema.Literals([
3980
+ "draft",
3981
+ "authorized",
3982
+ "settled"
3983
+ ]);
3984
+ const PayrollRunIdSchema = Schema.String.pipe(Schema.refine((value) => /^payroll_run_[0-9a-f]{64}$/u.test(value), { message: "payrollRunId must be a payroll_run_ digest identifier" }));
3985
+ const SignedMinorUnitSchema = Schema.String.pipe(Schema.refine((value) => /^-?(0|[1-9][0-9]*)$/u.test(value), { message: "must be an integer minor-unit string" }));
3986
+ const MinorUnitSchema = Schema.String.pipe(Schema.refine((value) => /^(0|[1-9][0-9]*)$/u.test(value), { message: "must be a non-negative integer minor-unit string" }));
3987
+ const PayrollRunItemInputSchema = Schema.Struct({
3988
+ to: PaymentRef,
3989
+ partyId: nonEmpty("partyId"),
3990
+ gross: MinorUnitSchema,
3991
+ net: MinorUnitSchema,
3992
+ adjustments: Schema.Array(Schema.Struct({
3993
+ label: Schema.String,
3994
+ amount: SignedMinorUnitSchema
3995
+ }))
3996
+ });
3997
+ Schema.Struct({
3998
+ orgId: nonEmpty("orgId"),
3999
+ permissionId: PermissionIdSchema,
4000
+ requestKey: nonEmpty("requestKey"),
4001
+ signerAddress: AddressSchema$1,
4002
+ period: Schema.Struct({
4003
+ start: nonNegativeInteger("period.start"),
4004
+ end: nonNegativeInteger("period.end")
4005
+ }),
4006
+ items: Schema.Array(PayrollRunItemInputSchema)
4007
+ });
4008
+ const PayrollRunSchema = Schema.Struct({
4009
+ id: PayrollRunIdSchema,
4010
+ status: PayrollRunStatusSchema,
4011
+ periodStart: nonNegativeInteger("periodStart"),
4012
+ periodEnd: nonNegativeInteger("periodEnd"),
4013
+ total: FinancialOpsMoney,
4014
+ recipientCount: nonNegativeInteger("recipientCount")
4015
+ });
4016
+ Schema.Struct({
4017
+ runs: Schema.Array(PayrollRunSchema),
4018
+ settledThisMonth: FinancialOpsMoney
4019
+ });
4020
+ Schema.Struct({
4021
+ run: PayrollRunSchema,
4022
+ execution: PreparedPaymentCommandExecutionSchema
4023
+ });
4024
+ const PayrollGroupIdSchema = Schema.String.pipe(Schema.refine((value) => /^payroll_group_[0-9A-Z]{26}$/u.test(value), { message: "payrollGroupId must be a payroll_group_ ULID identifier" }));
4025
+ const PayrollGroupMemberSchema = Schema.Struct({
4026
+ partyId: PartyIdSchema,
4027
+ amount: Schema.String,
4028
+ currency: CurrencyCodeSchema$1
4029
+ });
4030
+ Schema.Struct({
4031
+ id: PayrollGroupIdSchema,
4032
+ name: nonEmpty("name"),
4033
+ tone: Schema.String,
4034
+ members: Schema.Array(PayrollGroupMemberSchema)
4035
+ });
4036
+ Schema.Struct({
4037
+ id: Schema.optional(PayrollGroupIdSchema),
4038
+ name: Schema.String,
4039
+ tone: Schema.String,
4040
+ members: Schema.Array(PayrollGroupMemberSchema)
4041
+ });
3962
4042
  `
3963
4043
  .capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;
3964
4044
  font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;
@@ -5812,6 +5892,31 @@ const transition = (state, event, config = DEFAULT_CONFIG) => {
5812
5892
  };
5813
5893
  const PRIVATE_TAGS = new Set(PRIVATE_EVENT_TAGS);
5814
5894
  const isPrivate = (event) => PRIVATE_TAGS.has(event._tag);
5895
+ Object.freeze({
5896
+ terminal: false,
5897
+ outcome: null,
5898
+ needsAction: false
5899
+ });
5900
+ Object.freeze({
5901
+ terminal: false,
5902
+ outcome: null,
5903
+ needsAction: true
5904
+ });
5905
+ Object.freeze({
5906
+ terminal: true,
5907
+ outcome: "good",
5908
+ needsAction: false
5909
+ });
5910
+ Object.freeze({
5911
+ terminal: true,
5912
+ outcome: "bad",
5913
+ needsAction: false
5914
+ });
5915
+ Object.freeze({
5916
+ terminal: true,
5917
+ outcome: "neutral",
5918
+ needsAction: false
5919
+ });
5815
5920
  //#endregion
5816
5921
  //#region ../../packages/sdk/src/surface/_shared/provisioning-telemetry.ts
5817
5922
  async function emitProvisioningTelemetry(telemetry, smartAccount) {
@@ -7154,7 +7259,7 @@ function mapActorRequest(request, payer) {
7154
7259
  ...resolvedPayer === void 0 ? {} : { payer: resolvedPayer },
7155
7260
  amount: request.amount,
7156
7261
  reference: request.reference,
7157
- status: mapActorRequestStatus(request.status),
7262
+ status: request.status,
7158
7263
  expiresAt: request.expiresAt ?? null
7159
7264
  };
7160
7265
  }
@@ -7212,28 +7317,17 @@ function mapApprovedInboxPayment(command, input) {
7212
7317
  };
7213
7318
  }
7214
7319
  }
7215
- function mapActorRequestStatus(status) {
7320
+ function mapInboxStatus(status) {
7216
7321
  switch (status) {
7217
7322
  case "draft":
7218
7323
  case "sent":
7219
- case "viewed":
7324
+ case "viewed": return "open";
7325
+ case "pending_settlement": return "approved";
7220
7326
  case "paid":
7221
- case "pending_settlement":
7222
7327
  case "declined":
7223
7328
  case "cancelled":
7224
7329
  case "expired": return status;
7225
- default: return "sent";
7226
- }
7227
- }
7228
- function mapInboxStatus(status) {
7229
- switch (status) {
7230
- case "approved":
7231
- case "declined":
7232
- case "paid":
7233
- case "cancelled":
7234
- case "expired": return status;
7235
- case "pending_settlement": return "approved";
7236
- default: return "open";
7330
+ default: throw Errors.invalidInput("status", "unknown request status");
7237
7331
  }
7238
7332
  }
7239
7333
  function normalizeRefForBackend$1(ref, field) {
@@ -7552,6 +7646,7 @@ const financialOpsContract = {
7552
7646
  listPayments: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].listPayments),
7553
7647
  getPayment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].getPayment),
7554
7648
  activityList: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].list),
7649
+ activitySummary: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].summary),
7555
7650
  activityGet: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].get),
7556
7651
  activityAnnotate: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].annotate),
7557
7652
  verifyPaymentDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].verifyPaymentDocument),
@@ -7725,7 +7820,10 @@ function canonicalJson(value) {
7725
7820
  async function fingerprintPaymentIntent(intent) {
7726
7821
  return keccak256(toBytes(canonicalJson(intent)));
7727
7822
  }
7728
- async function executePrepared(deps, prepare, expectedRequest, signal) {
7823
+ function matchesIntent(expected) {
7824
+ return async (request) => await fingerprintPaymentIntent(request) === await fingerprintPaymentIntent(expected);
7825
+ }
7826
+ async function executePrepared(deps, prepare, isExpectedRequest, signal) {
7729
7827
  if (isAborted$1(signal)) return {
7730
7828
  ok: false,
7731
7829
  error: Errors.cancelled({ operation: "payments" })
@@ -7746,7 +7844,7 @@ async function executePrepared(deps, prepare, expectedRequest, signal) {
7746
7844
  }
7747
7845
  const prepared = await prepare(signerAddress);
7748
7846
  if (!prepared.ok) return prepared;
7749
- if (await fingerprintPaymentIntent(prepared.value.request) !== await fingerprintPaymentIntent(expectedRequest)) return {
7847
+ if (!await isExpectedRequest(prepared.value.request)) return {
7750
7848
  ok: false,
7751
7849
  error: Errors.invalidInput("payment", "prepared command mismatch")
7752
7850
  };
@@ -7781,13 +7879,13 @@ function executePaymentLifecycle(deps, intent, signal) {
7781
7879
  return executePrepared(deps, (signerAddress) => runIfActive(signal, "payments.prepareLifecycleExecution", () => deps.convexCall.action(deps.functions.preparePaymentLifecycleExecution, { input: {
7782
7880
  signerAddress,
7783
7881
  intent
7784
- } })), intent, signal);
7882
+ } })), matchesIntent(intent), signal);
7785
7883
  }
7786
7884
  function executeOrganizationPayment(deps, input, signal) {
7787
7885
  return executePrepared(deps, (signerAddress) => runIfActive(signal, "organizationPayments.prepareExecution", () => deps.convexCall.action(deps.functions.prepareOrganizationPaymentExecution, { input: {
7788
7886
  ...input,
7789
7887
  signerAddress
7790
- } })), input, signal);
7888
+ } })), matchesIntent(input), signal);
7791
7889
  }
7792
7890
  //#endregion
7793
7891
  //#region ../../packages/sdk/src/surface/money.ts
@@ -7803,6 +7901,40 @@ function actorReferenceToBackend(actor) {
7803
7901
  case "org": return actor;
7804
7902
  }
7805
7903
  }
7904
+ /**
7905
+ * The activity backend gives its actor a different name than the other
7906
+ * financialOps functions: `{kind: "organization", orgId}`, and not
7907
+ * `{kind: "org", orgId}`. Thus it does not use `actorReferenceToBackend`.
7908
+ *
7909
+ * The `personal` case sends NO actor. This is correct, and it does not lose
7910
+ * data. `requireActivityActor` uses the signed-in Account when the actor is
7911
+ * absent, and `canReadActor` refuses all other account identifiers
7912
+ * (`packages/backend/convex/movement/activityAuth.ts`). Thus "personal" and
7913
+ * "absent" both name the one Account that an SDK caller can read. The SDK does
7914
+ * not hold an account identifier to send.
7915
+ *
7916
+ * The `switch` is exhaustive. A new `ActorReference` variant is a compile error
7917
+ * here. The conditional expression that this function replaced removed each
7918
+ * value that was not an organization.
7919
+ */
7920
+ function activityActorField(actor) {
7921
+ if (actor === void 0) return {};
7922
+ switch (actor.kind) {
7923
+ case "personal": return {};
7924
+ case "organization": return { actor: {
7925
+ kind: "organization",
7926
+ orgId: actor.organizationId
7927
+ } };
7928
+ }
7929
+ }
7930
+ /** An absent actor and a `personal` actor both name the signed-in Account. */
7931
+ function actorScopeKey(actor) {
7932
+ return actor === void 0 || actor.kind === "personal" ? "personal" : `org:${actor.organizationId}`;
7933
+ }
7934
+ /** Two actor references name the same scope. */
7935
+ function sameActor(left, right) {
7936
+ return actorScopeKey(left) === actorScopeKey(right);
7937
+ }
7806
7938
  const memoryPaymentRequestKeys = /* @__PURE__ */ new Map();
7807
7939
  const paymentAttemptReleases = /* @__PURE__ */ new Set();
7808
7940
  let paymentAttemptPagehideInstalled = false;
@@ -8233,31 +8365,48 @@ function makeFinancialOpsMethods(deps) {
8233
8365
  },
8234
8366
  activity: {
8235
8367
  list: (params, options) => runIfActive(options?.signal, "activity.list", () => deps.convexCall.query(fns.activityList, { input: {
8236
- ...params?.actor?.kind === "organization" ? { actor: {
8237
- kind: "organization",
8238
- orgId: params.actor.organizationId
8239
- } } : {},
8368
+ ...activityActorField(params?.actor),
8240
8369
  ...params?.cursor === void 0 ? {} : { cursor: params.cursor },
8241
- ...params?.limit === void 0 ? {} : { limit: params.limit }
8370
+ ...params?.limit === void 0 ? {} : { limit: params.limit },
8371
+ ...params?.range === void 0 ? {} : { range: params.range },
8372
+ ...params?.filter === void 0 ? {} : { filter: params.filter }
8242
8373
  } })),
8243
- get: (reference, options) => runIfActive(options?.signal, "activity.get", () => deps.convexCall.query(fns.activityGet, { input: {
8244
- kind: reference.kind,
8245
- id: reference.id,
8246
- ...reference.kind === "payment" && reference.actor?.kind === "organization" ? { actor: {
8247
- kind: "organization",
8248
- orgId: reference.actor.organizationId
8249
- } } : {}
8374
+ summary: (params, options) => runIfActive(options?.signal, "activity.summary", () => deps.convexCall.query(fns.activitySummary, { input: {
8375
+ ...activityActorField(params?.actor),
8376
+ ...params?.window === void 0 ? {} : { window: params.window }
8250
8377
  } })),
8251
- annotate: (input, options) => runIfActive(options?.signal, "activity.annotate", () => deps.convexCall.mutation(fns.activityAnnotate, { input: {
8252
- ...input.actor?.kind === "organization" ? { actor: {
8253
- kind: "organization",
8254
- orgId: input.actor.organizationId
8255
- } } : {},
8256
- movementId: input.movementId,
8257
- ...input.counterpartyLabel === void 0 ? {} : { counterpartyLabel: input.counterpartyLabel },
8258
- ...input.accountingCategory === void 0 ? {} : { accountingCategory: input.accountingCategory },
8259
- ...input.memo === void 0 ? {} : { memo: input.memo }
8260
- } }))
8378
+ get: (reference, options) => {
8379
+ const actor = actorReferenceToBackend(options?.actor);
8380
+ return runIfActive(options?.signal, "activity.get", () => deps.convexCall.query(fns.activityGet, {
8381
+ input: {
8382
+ kind: reference.kind,
8383
+ id: reference.id,
8384
+ ...reference.kind === "payment" ? activityActorField(reference.actor) : {}
8385
+ },
8386
+ ...actor === void 0 ? {} : { actor }
8387
+ }));
8388
+ },
8389
+ annotate: (input, options) => {
8390
+ if (input.actor !== void 0 && input.reference.kind === "payment" && input.reference.actor !== void 0 && !sameActor(input.actor, input.reference.actor)) return Promise.resolve({
8391
+ ok: false,
8392
+ error: Errors.invalidInput("reference.actor", "must match the annotation actor")
8393
+ });
8394
+ const referenceActor = input.reference.kind === "payment" ? activityActorField(input.reference.actor).actor : void 0;
8395
+ return runIfActive(options?.signal, "activity.annotate", () => deps.convexCall.mutation(fns.activityAnnotate, { input: {
8396
+ ...activityActorField(input.actor),
8397
+ reference: input.reference.kind === "payment" && referenceActor !== void 0 ? {
8398
+ kind: "payment",
8399
+ id: input.reference.id,
8400
+ actor: referenceActor
8401
+ } : {
8402
+ kind: input.reference.kind,
8403
+ id: input.reference.id
8404
+ },
8405
+ ...input.counterpartyLabel === void 0 ? {} : { counterpartyLabel: input.counterpartyLabel },
8406
+ ...input.accountingCategory === void 0 ? {} : { accountingCategory: input.accountingCategory },
8407
+ ...input.memo === void 0 ? {} : { memo: input.memo }
8408
+ } }));
8409
+ }
8261
8410
  },
8262
8411
  offramp: {
8263
8412
  quote: (input, options) => {
@@ -8748,9 +8897,15 @@ async function recoverRawDigestSigner(input) {
8748
8897
  }
8749
8898
  //#endregion
8750
8899
  //#region ../../packages/sdk/package.json
8751
- var version = "2.3.2";
8900
+ var version = "2.5.0";
8752
8901
  //#endregion
8753
8902
  //#region ../../packages/observability/src/engineering.ts
8903
+ const ENGINEERING_CAPXUL_ENVS = [
8904
+ "development",
8905
+ "staging",
8906
+ "production",
8907
+ "local"
8908
+ ];
8754
8909
  const SAFE_TRACED_HEADER_NAMES = [
8755
8910
  "content-length",
8756
8911
  "content-type",
@@ -8773,11 +8928,7 @@ const postHogOtlpEndpoints = (host) => {
8773
8928
  traces: `${base}/i/v1/traces`
8774
8929
  };
8775
8930
  };
8776
- const ENGINEERING_CAPXUL_ENVS = new Set([
8777
- "development",
8778
- "staging",
8779
- "production"
8780
- ]);
8931
+ const ENGINEERING_CAPXUL_ENV_SET = new Set(ENGINEERING_CAPXUL_ENVS);
8781
8932
  const ENGINEERING_PRODUCERS = new Set(["browser", "server"]);
8782
8933
  const PUBLIC_POSTHOG_AUTHORIZATION = /^Bearer phc_[A-Za-z0-9_-]{1,191}$/u;
8783
8934
  const SAFE_RESOURCE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._+@/-]{0,127}$/u;
@@ -8789,7 +8940,7 @@ const validateEngineeringTelemetryConfig = (config) => {
8789
8940
  throw new TypeError("engineering telemetry host must be an absolute HTTPS URL");
8790
8941
  }
8791
8942
  if (url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.pathname !== "/" || url.search.length > 0 || url.hash.length > 0 || !(url.hostname === "posthog.com" || url.hostname.endsWith(".posthog.com"))) throw new TypeError("engineering telemetry host must be a credential-free HTTPS origin");
8792
- if (!ENGINEERING_CAPXUL_ENVS.has(config.capxulEnv)) throw new TypeError("engineering telemetry capxulEnv is not canonical");
8943
+ if (!ENGINEERING_CAPXUL_ENV_SET.has(config.capxulEnv)) throw new TypeError("engineering telemetry capxulEnv is not canonical");
8793
8944
  if (!ENGINEERING_PRODUCERS.has(config.producer)) throw new TypeError("engineering telemetry producer is not canonical");
8794
8945
  if (!SAFE_RESOURCE_VALUE.test(config.sdkVersion)) throw new TypeError("engineering telemetry sdkVersion must be a bounded safe value");
8795
8946
  if (config.serviceName !== void 0 && !SAFE_RESOURCE_VALUE.test(config.serviceName)) throw new TypeError("engineering telemetry serviceName must be a bounded safe value");
@@ -13631,7 +13782,8 @@ const TelemetryEnvelopeProps = {
13631
13782
  "development",
13632
13783
  "staging",
13633
13784
  "production",
13634
- "unknown"
13785
+ "unknown",
13786
+ "local"
13635
13787
  ]),
13636
13788
  producer: Schema.Literals([
13637
13789
  "server",
@@ -38401,7 +38553,7 @@ function makePermissionMethods(deps, orgId) {
38401
38553
  }
38402
38554
  //#endregion
38403
38555
  //#region ../../packages/sdk/src/surface/organization-payments.ts
38404
- function executionDependencies(input) {
38556
+ function executionDependencies$1(input) {
38405
38557
  return input.actor === void 0 || input.chainId === void 0 || input.signer === void 0 ? null : {
38406
38558
  actor: input.actor,
38407
38559
  chainId: input.chainId,
@@ -38418,7 +38570,7 @@ function makeOrganizationPaymentsMethods(deps, orgId) {
38418
38570
  ok: false,
38419
38571
  error: Errors.cancelled({ operation })
38420
38572
  };
38421
- const execution = executionDependencies(deps);
38573
+ const execution = executionDependencies$1(deps);
38422
38574
  if (execution === null) return {
38423
38575
  ok: false,
38424
38576
  error: Errors.notImplemented("organizationPayments", "executionComposition")
@@ -38513,6 +38665,197 @@ function makeOrganizationPaymentsMethods(deps, orgId) {
38513
38665
  };
38514
38666
  }
38515
38667
  //#endregion
38668
+ //#region ../../packages/sdk/src/contract/payroll.ts
38669
+ const payrollContract = {
38670
+ authorizeRun: makeFunctionReference(CAPXUL_FUNCTIONS["payroll/actions"].authorizeRun),
38671
+ runs: makeFunctionReference(CAPXUL_FUNCTIONS["payroll/queries"].runs),
38672
+ groups: makeFunctionReference(CAPXUL_FUNCTIONS["payroll/queries"].groups),
38673
+ saveGroup: makeFunctionReference(CAPXUL_FUNCTIONS["payroll/mutations"].saveGroup),
38674
+ removeGroup: makeFunctionReference(CAPXUL_FUNCTIONS["payroll/mutations"].removeGroup)
38675
+ };
38676
+ //#endregion
38677
+ //#region ../../packages/sdk/src/surface/payroll.ts
38678
+ const AUTHORIZE_RUN = "payroll.authorizeRun";
38679
+ function toPayrollRun(wire) {
38680
+ return {
38681
+ id: toPayrollRunId(wire.id),
38682
+ status: wire.status,
38683
+ periodStart: wire.periodStart,
38684
+ periodEnd: wire.periodEnd,
38685
+ total: wire.total,
38686
+ recipientCount: wire.recipientCount
38687
+ };
38688
+ }
38689
+ function toPayrollRuns(wire) {
38690
+ return {
38691
+ runs: wire.runs.map(toPayrollRun),
38692
+ settledThisMonth: wire.settledThisMonth
38693
+ };
38694
+ }
38695
+ function toPayrollGroup(wire) {
38696
+ return {
38697
+ id: toPayrollGroupId(wire.id),
38698
+ name: wire.name,
38699
+ tone: wire.tone,
38700
+ members: wire.members.map((member) => ({
38701
+ partyId: member.partyId,
38702
+ amount: member.amount,
38703
+ currency: member.currency
38704
+ }))
38705
+ };
38706
+ }
38707
+ const MINOR_UNIT_INTEGER = /^-?\d+$/u;
38708
+ /**
38709
+ * One prepared `Money` counted in the minor units `net` is written in, or
38710
+ * `null` when the value is not a decimal number. `amount.value` is a DECIMAL
38711
+ * string (`"200"` at 6 decimals is 200000000 minor units), so comparing it to
38712
+ * `net` directly would compare two different units and pass nothing.
38713
+ */
38714
+ function minorUnits(amount) {
38715
+ const [whole = "", fraction = ""] = amount.value.split(".");
38716
+ if (!/^\d+$/u.test(whole) || !/^\d*$/u.test(fraction) || fraction.length > amount.decimals) return null;
38717
+ return BigInt(whole + fraction.padEnd(amount.decimals, "0"));
38718
+ }
38719
+ /**
38720
+ * One prepared item must pay the person this caller named, the amount this
38721
+ * caller set, under a payslip that attests to the same figures.
38722
+ *
38723
+ * `issuedAt` and `employerRef` are server facts the caller cannot contradict,
38724
+ * so they are not compared. Everything the caller DID supply is: the recipient
38725
+ * `Ref`, the transfer amount against `net`, and the payslip's employee, gross
38726
+ * and net. Adjustments are not in the signed command at all — the backend
38727
+ * enforces `gross + Σ adjustments === net` (ADR-0022 R8), and gross and net
38728
+ * being right is what the signer can prove here.
38729
+ */
38730
+ function isRunItem(prepared, item) {
38731
+ if (prepared === void 0) return false;
38732
+ const payslip = prepared.document;
38733
+ return canonicalJson(prepared.to) === canonicalJson(item.to) && prepared.paymentType === "payroll" && MINOR_UNIT_INTEGER.test(item.net) && minorUnits(prepared.amount) === BigInt(item.net) && payslip?.primaryType === "Payslip" && payslip.message.employeeRef === item.partyId && payslip.message.gross === item.gross && payslip.message.net === item.net;
38734
+ }
38735
+ /**
38736
+ * The batch the backend derived from a payroll intent must be the batch this
38737
+ * caller asked for, checked before the digest is signed.
38738
+ *
38739
+ * The payslip envelope on each item is server-built and carries the run row's
38740
+ * own `issuedAt`, so the batch cannot be fingerprinted against a local copy
38741
+ * (`matchesIntent` is unavailable here). What CAN be verified is every field
38742
+ * the caller supplied — the org, the Budget, the request key, and per item the
38743
+ * recipient, the amount and the payslip figures — plus the lineage binding the
38744
+ * batch to the run just written. A prepared command that pays a different
38745
+ * person, a different amount, from a different Budget, or under a different
38746
+ * run never reaches the signer.
38747
+ */
38748
+ function isRunBatch(input) {
38749
+ return (request) => {
38750
+ const batch = request;
38751
+ return Promise.resolve(batch.orgId === input.orgId && batch.permissionId === input.permissionId && batch.requestKey === input.requestKey && batch.lineage?.kind === "payroll" && batch.lineage.runId === input.runId && batch.items?.length === input.items.length && input.items.every((item, index) => isRunItem(batch.items?.[index], item)));
38752
+ };
38753
+ }
38754
+ function executionDependencies(deps) {
38755
+ return deps.actor === void 0 || deps.chainId === void 0 || deps.signer === void 0 ? null : {
38756
+ actor: deps.actor,
38757
+ chainId: deps.chainId,
38758
+ convexCall: deps.convexCall,
38759
+ functions: moneyExecutionContract,
38760
+ signer: deps.signer
38761
+ };
38762
+ }
38763
+ function makePayrollMethods(deps, orgId) {
38764
+ const requestKeyScope = deps.requestKeyScope ?? `client-${crypto.randomUUID()}`;
38765
+ async function authorize(input, signal) {
38766
+ const execution = executionDependencies(deps);
38767
+ if (execution === null) return {
38768
+ ok: false,
38769
+ error: Errors.notImplemented("payroll", "executionComposition")
38770
+ };
38771
+ const requestKey = await paymentRequestKeyLifecycle(`${requestKeyScope}:${AUTHORIZE_RUN}`, {
38772
+ orgId,
38773
+ input
38774
+ }, input.requestKey);
38775
+ let authorized;
38776
+ const submitted = await executePrepared(execution, async (signerAddress) => {
38777
+ const prepared = await runIfActive(signal, AUTHORIZE_RUN, () => deps.convexCall.action(payrollContract.authorizeRun, { input: {
38778
+ orgId,
38779
+ permissionId: input.permissionId,
38780
+ requestKey: requestKey.key,
38781
+ signerAddress,
38782
+ period: input.period,
38783
+ items: input.items
38784
+ } }));
38785
+ if (!prepared.ok) return prepared;
38786
+ authorized = prepared.value.run;
38787
+ return {
38788
+ ok: true,
38789
+ value: prepared.value.execution
38790
+ };
38791
+ }, (request) => authorized === void 0 || authorized.periodStart !== input.period.start || authorized.periodEnd !== input.period.end ? Promise.resolve(false) : isRunBatch({
38792
+ orgId,
38793
+ permissionId: input.permissionId,
38794
+ requestKey: requestKey.key,
38795
+ runId: authorized.id,
38796
+ items: input.items
38797
+ })(request), signal);
38798
+ try {
38799
+ await requestKey.finish(submitted.ok);
38800
+ } catch {}
38801
+ if (!submitted.ok) return submitted;
38802
+ return authorized === void 0 ? {
38803
+ ok: false,
38804
+ error: Errors.unknown()
38805
+ } : {
38806
+ ok: true,
38807
+ value: toPayrollRun(authorized)
38808
+ };
38809
+ }
38810
+ return {
38811
+ runs: (options) => runIfActive(options?.signal, "payroll.runs", () => Effect.map(deps.convexCall.query(payrollContract.runs, { orgId }), toPayrollRuns)),
38812
+ authorizeRun: async (input, options) => {
38813
+ if (options?.signal?.aborted === true) return {
38814
+ ok: false,
38815
+ error: Errors.cancelled({ operation: AUTHORIZE_RUN })
38816
+ };
38817
+ try {
38818
+ return await authorize(input, options?.signal);
38819
+ } catch (cause) {
38820
+ return {
38821
+ ok: false,
38822
+ error: cause instanceof CapxulError ? cause : Errors.unknown(cause)
38823
+ };
38824
+ }
38825
+ },
38826
+ groups: {
38827
+ list: (options) => runIfActive(options?.signal, "payroll.groups.list", () => Effect.map(deps.convexCall.query(payrollContract.groups, { orgId }), (groups) => groups.map(toPayrollGroup))),
38828
+ save: (input, options) => runIfActive(options?.signal, "payroll.groups.save", () => Effect.map(deps.convexCall.mutation(payrollContract.saveGroup, {
38829
+ orgId,
38830
+ ...input.id === void 0 ? {} : { id: String(input.id) },
38831
+ name: input.name,
38832
+ tone: input.tone,
38833
+ members: input.members
38834
+ }), toPayrollGroup)),
38835
+ remove: (id, options) => runIfActive(options?.signal, "payroll.groups.remove", () => Effect.map(deps.convexCall.mutation(payrollContract.removeGroup, {
38836
+ orgId,
38837
+ id
38838
+ }), () => void 0))
38839
+ }
38840
+ };
38841
+ }
38842
+ const payrollUnavailable = () => Promise.resolve({
38843
+ ok: false,
38844
+ error: Errors.notImplemented("payroll", "executionComposition")
38845
+ });
38846
+ /** The bundle an unconfigured client exposes — every verb refuses, none throws. */
38847
+ function makeUnavailablePayrollMethods() {
38848
+ return {
38849
+ runs: payrollUnavailable,
38850
+ authorizeRun: payrollUnavailable,
38851
+ groups: {
38852
+ list: payrollUnavailable,
38853
+ save: payrollUnavailable,
38854
+ remove: payrollUnavailable
38855
+ }
38856
+ };
38857
+ }
38858
+ //#endregion
38516
38859
  //#region ../../packages/sdk/src/surface/_shared/org-telemetry.ts
38517
38860
  /** Extract the domain from an email for telemetry (never the local part / PII). */
38518
38861
  function emailDomain$1(email) {
@@ -39050,6 +39393,13 @@ function makeOrgMethods(deps) {
39050
39393
  ...deps.actor === void 0 ? {} : { actor: deps.actor },
39051
39394
  ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
39052
39395
  ...deps.signer === void 0 ? {} : { signer: deps.signer }
39396
+ }, String(orgId)),
39397
+ payroll: convexCall === void 0 ? makeUnavailablePayrollMethods() : makePayrollMethods({
39398
+ convexCall,
39399
+ ...deps.requestKeyScope === void 0 ? {} : { requestKeyScope: deps.requestKeyScope },
39400
+ ...deps.actor === void 0 ? {} : { actor: deps.actor },
39401
+ ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
39402
+ ...deps.signer === void 0 ? {} : { signer: deps.signer }
39053
39403
  }, String(orgId))
39054
39404
  };
39055
39405
  }
@@ -39088,13 +39438,74 @@ const organizationPaymentExecutionUnavailable = () => Promise.resolve({
39088
39438
  //#region ../../packages/sdk/src/contract/holdings.ts
39089
39439
  const holdingsContract = { current: makeFunctionReference(CAPXUL_FUNCTIONS["holdings/actions"].current) };
39090
39440
  //#endregion
39441
+ //#region ../../packages/sdk/src/domain/money/primary-holding.ts
39442
+ const CURRENCY_BY_TOKEN_SYMBOL = new Map([["USDX", toCurrencyCode("USD")]]);
39443
+ /**
39444
+ * The designated display asset: the payable row holding the most money, or
39445
+ * `null` when no row is payable.
39446
+ *
39447
+ * A `HoldingRow` (`packages/wire/src/money.ts`) is a RAW CHAIN ROW, and three
39448
+ * of its shapes cannot become a `Holding`. Each is SKIPPED rather than
39449
+ * reported, because a row nobody can render is not a failure of the read:
39450
+ *
39451
+ * - no `decimals` — the raw balance cannot be lifted into major units;
39452
+ * - no `symbol` — the asset cannot be named;
39453
+ * - a symbol that stands for no supported `CurrencyCode` — the balance
39454
+ * cannot be stated as `Money` without inventing a currency for it.
39455
+ *
39456
+ * This replaces the app's hand pick in `formatCurrentHoldingsBalance`
39457
+ * (`dashboard-formatters.ts`): a `.find()` over a hardcoded `["USDX","USDC"]`
39458
+ * list falling back to `rows[0]`. Ties keep the earlier row, so the same
39459
+ * snapshot always yields the same answer.
39460
+ */
39461
+ function primaryHolding(rows) {
39462
+ let primary = null;
39463
+ for (const row of rows) {
39464
+ const holding = toHolding(row);
39465
+ if (holding === null) continue;
39466
+ if (primary === null || compareDecimal(holding.available.value, primary.available.value) > 0) primary = holding;
39467
+ }
39468
+ return primary;
39469
+ }
39470
+ function toHolding(row) {
39471
+ if (row.symbol === void 0 || row.decimals === void 0) return null;
39472
+ const currency = currencyForTokenSymbol(row.symbol);
39473
+ if (currency === null) return null;
39474
+ return {
39475
+ id: row.assetKind === "native" ? "native" : row.tokenAddress.toLowerCase(),
39476
+ symbol: row.symbol,
39477
+ available: fromWei(row.rawBalance, row.decimals, currency)
39478
+ };
39479
+ }
39480
+ function currencyForTokenSymbol(symbol) {
39481
+ return CURRENCY_BY_TOKEN_SYMBOL.get(symbol.toUpperCase()) ?? null;
39482
+ }
39483
+ /**
39484
+ * Order two non-negative major-unit decimal strings without converting either
39485
+ * to a JavaScript number. Rows carry different `decimals`, so the raw integers
39486
+ * are not comparable: 1999999999 at 9 decimals is LESS than 2000000 at 6.
39487
+ */
39488
+ function compareDecimal(first, second) {
39489
+ const [firstWhole = "0", firstFraction = ""] = first.split(".");
39490
+ const [secondWhole = "0", secondFraction = ""] = second.split(".");
39491
+ const width = Math.max(firstFraction.length, secondFraction.length);
39492
+ const firstScaled = BigInt(firstWhole + firstFraction.padEnd(width, "0"));
39493
+ const secondScaled = BigInt(secondWhole + secondFraction.padEnd(width, "0"));
39494
+ if (firstScaled === secondScaled) return 0;
39495
+ return firstScaled < secondScaled ? -1 : 1;
39496
+ }
39497
+ //#endregion
39091
39498
  //#region ../../packages/sdk/src/surface/holdings.ts
39092
39499
  function makeHoldingsMethods(deps) {
39093
39500
  const functions = deps.functions ?? holdingsContract;
39094
- return { current: (input, options) => runIfActive(options?.signal, "holdings.current", () => deps.convexCall.action(functions.current, input?.actor?.kind === "organization" ? { actor: {
39501
+ const read = (operation, actor, signal, pick) => runIfActive(signal, operation, () => deps.convexCall.action(functions.current, actor?.kind === "organization" ? { actor: {
39095
39502
  kind: "organization",
39096
- orgId: input.actor.organizationId
39097
- } } : {})) };
39503
+ orgId: actor.organizationId
39504
+ } } : {}).pipe(Effect.map(pick)));
39505
+ return {
39506
+ current: (input, options) => read("holdings.current", input?.actor, options?.signal, (snapshot) => snapshot),
39507
+ primary: (input, options) => read("holdings.primary", input?.actor, options?.signal, (snapshot) => primaryHolding(snapshot.rows))
39508
+ };
39098
39509
  }
39099
39510
  //#endregion
39100
39511
  //#region ../../packages/sdk/src/ports/auth-cache.ts
@@ -42575,50 +42986,59 @@ const BUNDLER_RPC_METHODS = new Set([
42575
42986
  "pm_getPaymasterStubData",
42576
42987
  "pm_getPaymasterData"
42577
42988
  ]);
42578
- function providerFor(method) {
42579
- return BUNDLER_RPC_METHODS.has(method) ? "account-abstraction" : "alchemy";
42989
+ function rpcProviderRole(chainId, method) {
42990
+ if (BUNDLER_RPC_METHODS.has(method)) return "account-abstraction";
42991
+ if (chainId === 84532 && EVIDENCE_RPC_METHODS.has(method) && optionalEnv("BASE_SEPOLIA_EVIDENCE_RPC_URL") !== void 0) return "chain-evidence";
42992
+ return "chain-rpc";
42580
42993
  }
42581
42994
  function accountAbstractionUrl(chainId) {
42582
42995
  if (chainId !== 84532) throw Errors.invalidInput("chainId", `owned account-abstraction rail supports Base Sepolia; got ${String(chainId)}`);
42583
42996
  return requireEnvOrThrow("BASE_SEPOLIA_BUNDLER_RPC_URL");
42584
42997
  }
42585
- function rethrowProvider(method) {
42998
+ function rpcProviderError(operation, cause, chainId) {
42999
+ const method = operation.split(" ", 1)[0] ?? operation;
43000
+ return Errors.providerError(rpcProviderRole(chainId, method), operation, cause);
43001
+ }
43002
+ function rethrowProvider(chainId, method) {
42586
43003
  return (e) => {
42587
- throw Errors.providerError(providerFor(method), method, e);
43004
+ throw rpcProviderError(method, e, chainId);
42588
43005
  };
42589
43006
  }
42590
- function parseAlchemyQuantity(value, operation, field) {
43007
+ function parseRpcQuantity(value, operation, field, chainId) {
42591
43008
  try {
42592
43009
  return BigInt(value);
42593
43010
  } catch (cause) {
42594
- throw Errors.providerError("alchemy", `${operation} ${field}`, `invalid ${field} ${value} (${String(cause)})`);
43011
+ throw rpcProviderError(`${operation} ${field}`, `invalid ${field} ${value} (${String(cause)})`, chainId);
42595
43012
  }
42596
43013
  }
42597
- function providerValue(value, pattern, operation, field) {
42598
- if (typeof value !== "string" || !pattern.test(value)) throw Errors.providerError(providerFor(operation), operation, `invalid ${field}`);
43014
+ function providerValue(value, pattern, operation, field, chainId) {
43015
+ if (typeof value !== "string" || !pattern.test(value)) throw rpcProviderError(operation, `invalid ${field}`, chainId);
42599
43016
  return value.toLowerCase();
42600
43017
  }
42601
- function providerAddress(value, operation, field) {
42602
- return providerValue(value, ADDRESS_HEX, operation, field);
43018
+ function providerAddress(value, operation, field, chainId) {
43019
+ return providerValue(value, ADDRESS_HEX, operation, field, chainId);
42603
43020
  }
42604
- function providerBytes32(value, operation, field) {
42605
- return providerValue(value, BYTES32_HEX, operation, field);
43021
+ function providerBytes32(value, operation, field, chainId) {
43022
+ return providerValue(value, BYTES32_HEX, operation, field, chainId);
42606
43023
  }
42607
- function providerData(value, operation, field) {
42608
- return providerValue(value, EVEN_DATA_HEX, operation, field);
43024
+ function providerData(value, operation, field, chainId) {
43025
+ if (typeof value !== "string" || !EVEN_DATA_HEX.test(value)) throw rpcProviderError(operation, `invalid ${field}`, chainId);
43026
+ return value.toLowerCase();
42609
43027
  }
43028
+ /** The standard public Base node endpoints. Each one is overridable by env. */
43029
+ const BASE_SEPOLIA_NODE_RPC_URL = "https://sepolia.base.org";
43030
+ const BASE_MAINNET_NODE_RPC_URL = "https://mainnet.base.org";
42610
43031
  /**
42611
43032
  * Construct the node RPC URL for a given chain. Account-abstraction methods
42612
43033
  * use the separate owned gateway URL.
43034
+ *
43035
+ * The default is the standard public Base endpoint. An operator points a chain
43036
+ * at a different node with `BASE_SEPOLIA_RPC_URL` or `BASE_MAINNET_RPC_URL`.
42613
43037
  */
42614
- function alchemyUrl(chainId) {
43038
+ function nodeRpcUrl(chainId) {
42615
43039
  switch (chainId) {
42616
- case 84532: {
42617
- const baseSepoliaRpcUrl = optionalEnv("BASE_SEPOLIA_RPC_URL");
42618
- if (baseSepoliaRpcUrl !== void 0) return baseSepoliaRpcUrl.replace(/\/+$/, "");
42619
- return `https://base-sepolia.g.alchemy.com/v2/${requireEnvOrThrow("ALCHEMY_API_KEY")}`;
42620
- }
42621
- case 8453: return `https://base-mainnet.g.alchemy.com/v2/${requireEnvOrThrow("ALCHEMY_API_KEY")}`;
43040
+ case 84532: return (optionalEnv("BASE_SEPOLIA_RPC_URL") ?? BASE_SEPOLIA_NODE_RPC_URL).replace(/\/+$/, "");
43041
+ case 8453: return (optionalEnv("BASE_MAINNET_RPC_URL") ?? BASE_MAINNET_NODE_RPC_URL).replace(/\/+$/, "");
42622
43042
  default: throw Errors.invalidInput("chainId", `unsupported chainId ${String(chainId)}`);
42623
43043
  }
42624
43044
  }
@@ -42632,16 +43052,16 @@ function isValidJsonRpcEnvelope(value) {
42632
43052
  function isValidJsonRpcError(value) {
42633
43053
  return isRecord(value) && typeof value.code === "number" && Number.isInteger(value.code) && typeof value.message === "string";
42634
43054
  }
42635
- var DefinitiveUserOperationRpcRejection = class extends Error {
43055
+ var DefinitiveBundlerJsonRpcRejection = class extends Error {
42636
43056
  constructor() {
42637
- super("The bundler returned an explicit JSON-RPC rejection");
42638
- this.name = "DefinitiveUserOperationRpcRejection";
43057
+ super("Bundler returned an explicit JSON-RPC rejection");
43058
+ this.name = "DefinitiveBundlerJsonRpcRejection";
42639
43059
  }
42640
43060
  };
42641
43061
  async function alchemyRpc(chainId, method, params, timeoutMs, externalSignal) {
42642
43062
  const bundlerUrl = BUNDLER_RPC_METHODS.has(method) ? accountAbstractionUrl(chainId) : void 0;
42643
43063
  const evidenceUrl = chainId === 84532 && EVIDENCE_RPC_METHODS.has(method) ? optionalEnv("BASE_SEPOLIA_EVIDENCE_RPC_URL") : void 0;
42644
- const url = bundlerUrl?.replace(/\/+$/u, "") ?? evidenceUrl?.replace(/\/+$/u, "") ?? alchemyUrl(chainId);
43064
+ const url = bundlerUrl?.replace(/\/+$/u, "") ?? evidenceUrl?.replace(/\/+$/u, "") ?? nodeRpcUrl(chainId);
42645
43065
  const timeoutSignal = timeoutMs === void 0 ? void 0 : AbortSignal.timeout(timeoutMs);
42646
43066
  const signal = externalSignal === void 0 ? timeoutSignal : timeoutSignal === void 0 ? externalSignal : AbortSignal.any([externalSignal, timeoutSignal]);
42647
43067
  const res = await fetch(url, {
@@ -42654,47 +43074,47 @@ async function alchemyRpc(chainId, method, params, timeoutMs, externalSignal) {
42654
43074
  params
42655
43075
  }),
42656
43076
  ...signal === void 0 ? {} : { signal }
42657
- }).catch(rethrowProvider(method));
43077
+ }).catch(rethrowProvider(chainId, method));
42658
43078
  if (!res.ok) {
42659
43079
  const body = await res.text().catch(() => "<no body>");
42660
- throw Errors.providerError(providerFor(method), `${method} ${res.status}`, body);
43080
+ throw rpcProviderError(`${method} ${res.status}`, body, chainId);
42661
43081
  }
42662
43082
  let json;
42663
43083
  try {
42664
43084
  json = await res.json();
42665
43085
  } catch (cause) {
42666
- throw Errors.providerError(providerFor(method), `${method} json`, cause);
43086
+ throw rpcProviderError(`${method} json`, cause, chainId);
42667
43087
  }
42668
- if (!isValidJsonRpcEnvelope(json)) throw Errors.providerError(providerFor(method), method, "malformed JSON-RPC envelope");
43088
+ if (!isValidJsonRpcEnvelope(json)) throw rpcProviderError(method, "malformed JSON-RPC envelope", chainId);
42669
43089
  if (json.error !== void 0) {
42670
- if (!isValidJsonRpcError(json.error)) throw Errors.providerError(providerFor(method), method, "malformed JSON-RPC error");
42671
- throw Errors.providerError(providerFor(method), method, method === "eth_sendUserOperation" ? new DefinitiveUserOperationRpcRejection() : json.error.message);
43090
+ if (!isValidJsonRpcError(json.error)) throw rpcProviderError(method, "malformed JSON-RPC error", chainId);
43091
+ throw rpcProviderError(method, method === "eth_sendUserOperation" ? new DefinitiveBundlerJsonRpcRejection() : json.error.message, chainId);
42672
43092
  }
42673
- if (json.result === void 0) throw Errors.providerError(providerFor(method), method, "missing result");
43093
+ if (json.result === void 0) throw rpcProviderError(method, "missing result", chainId);
42674
43094
  return json.result;
42675
43095
  }
42676
- function parseReceiptLogs(raw) {
43096
+ function parseReceiptLogs(raw, chainId) {
42677
43097
  if (raw === void 0 || raw === null) return [];
42678
- if (!Array.isArray(raw)) throw Errors.providerError("account-abstraction", "eth_getUserOperationReceipt", "logs is not an array");
43098
+ if (!Array.isArray(raw)) throw rpcProviderError("eth_getUserOperationReceipt", "logs is not an array", chainId);
42679
43099
  return raw.map((entry) => {
42680
- if (typeof entry !== "object" || entry === null || typeof entry.address !== "string" || !Array.isArray(entry.topics) || typeof entry.data !== "string") throw Errors.providerError("account-abstraction", "eth_getUserOperationReceipt", `malformed receipt log: ${JSON.stringify(entry)}`);
43100
+ if (typeof entry !== "object" || entry === null || typeof entry.address !== "string" || !Array.isArray(entry.topics) || typeof entry.data !== "string") throw rpcProviderError("eth_getUserOperationReceipt", `malformed receipt log: ${JSON.stringify(entry)}`, chainId);
42681
43101
  const log = entry;
42682
43102
  const operation = "eth_getUserOperationReceipt";
42683
- if (log.logIndex !== void 0 && typeof log.logIndex !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid logIndex");
42684
- if (log.blockNumber !== void 0 && typeof log.blockNumber !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid blockNumber");
42685
- if (log.blockHash !== void 0 && typeof log.blockHash !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid blockHash");
42686
- if (log.transactionHash !== void 0 && typeof log.transactionHash !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid transactionHash");
42687
- if (log.transactionIndex !== void 0 && typeof log.transactionIndex !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid transactionIndex");
42688
- if (log.removed !== void 0 && typeof log.removed !== "boolean") throw Errors.providerError(providerFor(operation), operation, "invalid removed");
43103
+ if (log.logIndex !== void 0 && typeof log.logIndex !== "string") throw rpcProviderError(operation, "invalid logIndex", chainId);
43104
+ if (log.blockNumber !== void 0 && typeof log.blockNumber !== "string") throw rpcProviderError(operation, "invalid blockNumber", chainId);
43105
+ if (log.blockHash !== void 0 && typeof log.blockHash !== "string") throw rpcProviderError(operation, "invalid blockHash", chainId);
43106
+ if (log.transactionHash !== void 0 && typeof log.transactionHash !== "string") throw rpcProviderError(operation, "invalid transactionHash", chainId);
43107
+ if (log.transactionIndex !== void 0 && typeof log.transactionIndex !== "string") throw rpcProviderError(operation, "invalid transactionIndex", chainId);
43108
+ if (log.removed !== void 0 && typeof log.removed !== "boolean") throw rpcProviderError(operation, "invalid removed", chainId);
42689
43109
  return {
42690
- address: providerAddress(log.address, operation, "log address"),
42691
- topics: log.topics.map((topic, index) => providerBytes32(topic, operation, `topic ${String(index)}`)),
42692
- data: providerData(log.data, operation, "log data"),
42693
- ...typeof log.logIndex === "string" ? { logIndex: hexToSafeInteger(log.logIndex, operation) } : {},
42694
- ...typeof log.blockNumber === "string" ? { blockNumber: hexToSafeInteger(log.blockNumber, operation) } : {},
42695
- ...typeof log.blockHash === "string" ? { blockHash: providerBytes32(log.blockHash, operation, "blockHash") } : {},
42696
- ...typeof log.transactionHash === "string" ? { transactionHash: providerBytes32(log.transactionHash, operation, "transactionHash") } : {},
42697
- ...typeof log.transactionIndex === "string" ? { transactionIndex: hexToSafeInteger(log.transactionIndex, operation) } : {},
43110
+ address: providerAddress(log.address, operation, "log address", chainId),
43111
+ topics: log.topics.map((topic, index) => providerBytes32(topic, operation, `topic ${String(index)}`, chainId)),
43112
+ data: providerData(log.data, operation, "log data", chainId),
43113
+ ...typeof log.logIndex === "string" ? { logIndex: hexToSafeInteger(log.logIndex, operation, chainId) } : {},
43114
+ ...typeof log.blockNumber === "string" ? { blockNumber: hexToSafeInteger(log.blockNumber, operation, chainId) } : {},
43115
+ ...typeof log.blockHash === "string" ? { blockHash: providerBytes32(log.blockHash, operation, "blockHash", chainId) } : {},
43116
+ ...typeof log.transactionHash === "string" ? { transactionHash: providerBytes32(log.transactionHash, operation, "transactionHash", chainId) } : {},
43117
+ ...typeof log.transactionIndex === "string" ? { transactionIndex: hexToSafeInteger(log.transactionIndex, operation, chainId) } : {},
42698
43118
  ...typeof log.removed === "boolean" ? { removed: log.removed } : {}
42699
43119
  };
42700
43120
  });
@@ -42702,17 +43122,17 @@ function parseReceiptLogs(raw) {
42702
43122
  async function fetchUserOperationReceipt(args) {
42703
43123
  const raw = await alchemyRpc(args.chainId, "eth_getUserOperationReceipt", [args.userOpHash]);
42704
43124
  if (raw === null) return null;
42705
- if (typeof raw !== "object" || typeof raw.userOpHash !== "string" || typeof raw.sender !== "string" || typeof raw.success !== "boolean" || typeof raw.receipt !== "object" || typeof raw.receipt.blockNumber !== "string" || typeof raw.receipt.blockHash !== "string" || typeof raw.receipt.transactionHash !== "string" || typeof raw.receipt.transactionIndex !== "string") throw Errors.providerError("account-abstraction", "eth_getUserOperationReceipt", `unexpected shape: ${JSON.stringify(raw)}`);
43125
+ if (typeof raw !== "object" || typeof raw.userOpHash !== "string" || typeof raw.sender !== "string" || typeof raw.success !== "boolean" || typeof raw.receipt !== "object" || typeof raw.receipt.blockNumber !== "string" || typeof raw.receipt.blockHash !== "string" || typeof raw.receipt.transactionHash !== "string" || typeof raw.receipt.transactionIndex !== "string") throw rpcProviderError("eth_getUserOperationReceipt", `unexpected shape: ${JSON.stringify(raw)}`, args.chainId);
42706
43126
  return {
42707
- userOpHash: providerBytes32(raw.userOpHash, "eth_getUserOperationReceipt", "userOpHash"),
42708
- sender: providerAddress(raw.sender, "eth_getUserOperationReceipt", "sender"),
43127
+ userOpHash: providerBytes32(raw.userOpHash, "eth_getUserOperationReceipt", "userOpHash", args.chainId),
43128
+ sender: providerAddress(raw.sender, "eth_getUserOperationReceipt", "sender", args.chainId),
42709
43129
  success: raw.success,
42710
43130
  receipt: {
42711
- blockNumber: hexToSafeInteger(raw.receipt.blockNumber, "eth_getUserOperationReceipt"),
42712
- blockHash: providerBytes32(raw.receipt.blockHash, "eth_getUserOperationReceipt", "blockHash"),
42713
- transactionHash: providerBytes32(raw.receipt.transactionHash, "eth_getUserOperationReceipt", "transactionHash"),
42714
- transactionIndex: hexToSafeInteger(raw.receipt.transactionIndex, "eth_getUserOperationReceipt"),
42715
- logs: parseReceiptLogs(raw.logs)
43131
+ blockNumber: hexToSafeInteger(raw.receipt.blockNumber, "eth_getUserOperationReceipt", args.chainId),
43132
+ blockHash: providerBytes32(raw.receipt.blockHash, "eth_getUserOperationReceipt", "blockHash", args.chainId),
43133
+ transactionHash: providerBytes32(raw.receipt.transactionHash, "eth_getUserOperationReceipt", "transactionHash", args.chainId),
43134
+ transactionIndex: hexToSafeInteger(raw.receipt.transactionIndex, "eth_getUserOperationReceipt", args.chainId),
43135
+ logs: parseReceiptLogs(raw.logs, args.chainId)
42716
43136
  }
42717
43137
  };
42718
43138
  }
@@ -42721,16 +43141,16 @@ async function fetchUserOperationReceipt(args) {
42721
43141
  * `Errors.providerError` if the value exceeds `Number.MAX_SAFE_INTEGER`
42722
43142
  * (would silently round under `parseInt` per `.claude/rules/numeric-parsing.md`).
42723
43143
  */
42724
- function hexToSafeInteger(hex, op) {
42725
- if (typeof hex !== "string" || !QUANTITY_HEX.test(hex)) throw Errors.providerError(providerFor(op), op, `expected a canonical hex quantity, got ${String(hex)}`);
43144
+ function hexToSafeInteger(hex, op, chainId) {
43145
+ if (typeof hex !== "string" || !QUANTITY_HEX.test(hex)) throw rpcProviderError(op, `expected a canonical hex quantity, got ${String(hex)}`, chainId);
42726
43146
  let big;
42727
43147
  try {
42728
43148
  big = BigInt(hex);
42729
43149
  } catch (cause) {
42730
- throw Errors.providerError(providerFor(op), op, `invalid hex integer: ${hex} (${String(cause)})`);
43150
+ throw rpcProviderError(op, `invalid hex integer: ${hex} (${String(cause)})`, chainId);
42731
43151
  }
42732
43152
  const n = Number(big);
42733
- if (!Number.isSafeInteger(n)) throw Errors.providerError(providerFor(op), op, `hex value ${hex} exceeds MAX_SAFE_INTEGER`);
43153
+ if (!Number.isSafeInteger(n)) throw rpcProviderError(op, `hex value ${hex} exceeds MAX_SAFE_INTEGER`, chainId);
42734
43154
  return n;
42735
43155
  }
42736
43156
  /**
@@ -42751,8 +43171,8 @@ async function fetchCommitmentState(args) {
42751
43171
  to: CAPXUL_PAYMENTS_V2_ADDRESS,
42752
43172
  data
42753
43173
  }, "latest"]);
42754
- if (typeof raw !== "string" || !raw.startsWith("0x")) throw Errors.providerError("alchemy", "eth_call commitments", `unexpected shape: ${String(raw)}`);
42755
- if (raw === "0x") throw Errors.providerError("alchemy", "eth_call commitments", "empty commitments() return (0x)");
43174
+ if (typeof raw !== "string" || !raw.startsWith("0x")) throw rpcProviderError("eth_call commitments", `unexpected shape: ${String(raw)}`, args.chainId);
43175
+ if (raw === "0x") throw rpcProviderError("eth_call commitments", "empty commitments() return (0x)", args.chainId);
42756
43176
  let decoded;
42757
43177
  try {
42758
43178
  decoded = decodeFunctionResult({
@@ -42761,7 +43181,7 @@ async function fetchCommitmentState(args) {
42761
43181
  data: raw
42762
43182
  });
42763
43183
  } catch (cause) {
42764
- throw Errors.providerError("alchemy", "eth_call commitments", `decode failed: ${String(cause)}`);
43184
+ throw rpcProviderError("eth_call commitments", `decode failed: ${String(cause)}`, args.chainId);
42765
43185
  }
42766
43186
  const [settlementId, creator, recipient, token, totalAmount, claimed, startTime, cliffTime, endTime, kind, documentHash, cancelled] = decoded;
42767
43187
  return {
@@ -42810,31 +43230,28 @@ async function fetchEntryPointNonce(args) {
42810
43230
  try {
42811
43231
  return BigInt(result);
42812
43232
  } catch (cause) {
42813
- throw Errors.providerError("alchemy", "eth_call getNonce", `invalid nonce ${result} (${String(cause)})`);
43233
+ throw rpcProviderError("eth_call getNonce", `invalid nonce ${result} (${String(cause)})`, args.chainId);
42814
43234
  }
42815
43235
  }
42816
43236
  /** EIP-1559 max + priority fees with a 2x base-fee inclusion buffer. */
42817
43237
  async function fetchUserOperationFees(args) {
42818
- const priority = parseAlchemyQuantity(await alchemyRpc(args.chainId, "eth_maxPriorityFeePerGas", []), "eth_maxPriorityFeePerGas", "maxPriorityFeePerGas");
43238
+ const priority = parseRpcQuantity(await alchemyRpc(args.chainId, "eth_maxPriorityFeePerGas", []), "eth_maxPriorityFeePerGas", "maxPriorityFeePerGas", args.chainId);
42819
43239
  const block = await alchemyRpc(args.chainId, "eth_getBlockByNumber", ["latest", false]);
42820
- if (block.baseFeePerGas === void 0) {
42821
- const blockRef = block.number ?? block.hash ?? "<unknown>";
42822
- throw Errors.providerError("alchemy", "eth_getBlockByNumber baseFeePerGas", `missing baseFeePerGas in latest block ${blockRef}: ${JSON.stringify(block)}`);
42823
- }
43240
+ if (block.baseFeePerGas === void 0) throw rpcProviderError("eth_getBlockByNumber baseFeePerGas", `missing baseFeePerGas in latest block ${block.number ?? block.hash ?? "<unknown>"}: ${JSON.stringify(block)}`, args.chainId);
42824
43241
  return {
42825
- maxFeePerGas: parseAlchemyQuantity(block.baseFeePerGas, "eth_getBlockByNumber", "baseFeePerGas") * EIP1559_BASE_FEE_BUFFER_MULTIPLIER + priority,
43242
+ maxFeePerGas: parseRpcQuantity(block.baseFeePerGas, "eth_getBlockByNumber", "baseFeePerGas", args.chainId) * EIP1559_BASE_FEE_BUFFER_MULTIPLIER + priority,
42826
43243
  maxPriorityFeePerGas: priority
42827
43244
  };
42828
43245
  }
42829
43246
  async function estimateUserOperationGas(args) {
42830
43247
  const raw = await alchemyRpc(args.chainId, "eth_estimateUserOperationGas", [args.userOp, ENTRY_POINT_07_ADDRESS]);
42831
- if (typeof raw !== "object" || typeof raw.preVerificationGas !== "string" || typeof raw.verificationGasLimit !== "string" || typeof raw.callGasLimit !== "string") throw Errors.providerError("account-abstraction", "eth_estimateUserOperationGas", `unexpected shape: ${JSON.stringify(raw)}`);
43248
+ if (typeof raw !== "object" || typeof raw.preVerificationGas !== "string" || typeof raw.verificationGasLimit !== "string" || typeof raw.callGasLimit !== "string") throw rpcProviderError("eth_estimateUserOperationGas", `unexpected shape: ${JSON.stringify(raw)}`, args.chainId);
42832
43249
  return raw;
42833
43250
  }
42834
- function optionalPaymasterHex(raw, method, field) {
43251
+ function optionalPaymasterHex(raw, method, field, chainId) {
42835
43252
  const value = raw[field];
42836
43253
  if (value === void 0) return void 0;
42837
- if (typeof value !== "string" || !isHex(value)) throw Errors.providerError("account-abstraction", method, `unexpected ${field}: expected hex string`);
43254
+ if (typeof value !== "string" || !isHex(value)) throw rpcProviderError(method, `unexpected ${field}: expected hex string`, chainId);
42838
43255
  return value;
42839
43256
  }
42840
43257
  function definedPaymasterFields(result) {
@@ -42852,12 +43269,12 @@ async function paymasterRpc(method, args) {
42852
43269
  toHex(args.chainId),
42853
43270
  {}
42854
43271
  ]);
42855
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw Errors.providerError("account-abstraction", method, `unexpected shape: ${JSON.stringify(raw)}`);
43272
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw rpcProviderError(method, `unexpected shape: ${JSON.stringify(raw)}`, args.chainId);
42856
43273
  const result = raw;
42857
- const paymaster = optionalPaymasterHex(result, method, "paymaster");
42858
- const paymasterData = optionalPaymasterHex(result, method, "paymasterData");
42859
- const paymasterVerificationGasLimit = optionalPaymasterHex(result, method, "paymasterVerificationGasLimit");
42860
- const paymasterPostOpGasLimit = optionalPaymasterHex(result, method, "paymasterPostOpGasLimit");
43274
+ const paymaster = optionalPaymasterHex(result, method, "paymaster", args.chainId);
43275
+ const paymasterData = optionalPaymasterHex(result, method, "paymasterData", args.chainId);
43276
+ const paymasterVerificationGasLimit = optionalPaymasterHex(result, method, "paymasterVerificationGasLimit", args.chainId);
43277
+ const paymasterPostOpGasLimit = optionalPaymasterHex(result, method, "paymasterPostOpGasLimit", args.chainId);
42861
43278
  return {
42862
43279
  ...paymaster === void 0 ? {} : { paymaster },
42863
43280
  ...paymasterData === void 0 ? {} : { paymasterData },
@@ -42873,7 +43290,7 @@ function getPaymasterStubData(args) {
42873
43290
  function getPaymasterData(args) {
42874
43291
  return paymasterRpc("pm_getPaymasterData", args);
42875
43292
  }
42876
- /** Sponsor one Base Sepolia UserOperation through the owned ERC-7677 gateway. */
43293
+ /** Run the owned ERC-7677 sponsorship flow. */
42877
43294
  async function sponsorUserOperation(args) {
42878
43295
  let request = args.userOp;
42879
43296
  request = {
@@ -42904,7 +43321,7 @@ async function sponsorUserOperation(args) {
42904
43321
  userOp: request
42905
43322
  }))
42906
43323
  };
42907
- if (request.paymaster === void 0 || request.paymasterData === void 0) throw Errors.providerError("account-abstraction", "pm_getPaymasterData", "missing paymaster sponsorship");
43324
+ if (request.paymaster === void 0 || request.paymasterData === void 0) throw rpcProviderError("pm_getPaymasterData", "missing paymaster sponsorship", args.chainId);
42908
43325
  return {
42909
43326
  ...request,
42910
43327
  paymaster: request.paymaster,
@@ -42914,7 +43331,7 @@ async function sponsorUserOperation(args) {
42914
43331
  /** Submit the signed UserOperation through the bundler — returns the userOpHash. */
42915
43332
  async function sendUserOperation(args) {
42916
43333
  const hash = await alchemyRpc(args.chainId, "eth_sendUserOperation", [args.userOp, ENTRY_POINT_07_ADDRESS]);
42917
- if (typeof hash !== "string" || !TX_HASH_HEX.test(hash)) throw Errors.providerError("account-abstraction", "eth_sendUserOperation", `unexpected hash: ${String(hash)}; expected 0x-prefixed 32-byte hex`);
43334
+ if (typeof hash !== "string" || !TX_HASH_HEX.test(hash)) throw rpcProviderError("eth_sendUserOperation", `unexpected hash: ${String(hash)}; expected 0x-prefixed 32-byte hex`, args.chainId);
42918
43335
  return hash;
42919
43336
  }
42920
43337
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capxul/mcp",
3
- "version": "2.3.2",
3
+ "version": "2.5.0",
4
4
  "private": false,
5
5
  "description": "Capxul MCP server for auth, Account readiness, identity, Organizations, relationships, requests, destinations, and testnet funding over Streamable HTTP.",
6
6
  "keywords": [
@@ -47,12 +47,12 @@
47
47
  "typescript": "npm:@typescript/typescript6@6.0.2",
48
48
  "vite": "npm:@voidzero-dev/vite-plus-core@0.1.23",
49
49
  "vite-plus": "0.1.23",
50
- "@capxul/backend": "0.2.5",
50
+ "@capxul/backend": "0.2.7",
51
51
  "@capxul/config": "0.2.0",
52
- "@capxul/sdk": "2.3.2",
52
+ "@capxul/sdk": "2.5.0",
53
53
  "@capxul/types": "0.2.0",
54
54
  "@capxul/typescript-config": "0.0.0",
55
- "@capxul/wire": "0.4.0"
55
+ "@capxul/wire": "0.5.0"
56
56
  },
57
57
  "scripts": {
58
58
  "dev": "vp exec tsx src/main.ts serve",