@capxul/sdk 1.2.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { D as toRoleKey, M as EXPECTED_OPERATION_OUTCOMES, N as Errors, P as isCapxulError, T as toOrgId, _ as toCountryCode, b as toEmail, c as BYTES32_RE, d as toAccountId, f as toAddress, g as toChainId, h as toAuthUserId, j as CapxulError, k as toSubAccountId, l as EVM_ADDRESS_RE$1, n as BrowserAuthCacheAdapter, s as APP_ID_RE, t as InMemoryAuthCacheAdapter, u as SUPPORTED_CURRENCY_CODES, v as toCurrencyCode } from "./InMemoryAuthCacheAdapter-Dr1sEd9y.mjs";
1
+ import { D as toOrgId, F as isCapxulError, M as CapxulError, N as EXPECTED_OPERATION_OUTCOMES, P as Errors, S as toEmail, _ as toAuthUserId, b as toCurrencyCode, c as BYTES32_RE, d as WEI_RE, f as ZERO_BYTES32, k as toRoleKey, l as EVM_ADDRESS_RE$1, m as toAddress, n as BrowserAuthCacheAdapter, p as toAccountId, s as APP_ID_RE, t as InMemoryAuthCacheAdapter, u as SUPPORTED_CURRENCY_CODES, v as toChainId, y as toCountryCode } from "./InMemoryAuthCacheAdapter-Rc8tCtml.mjs";
2
2
  import { concat, encodeAbiParameters, encodeFunctionData, encodePacked, formatUnits, getContractAddress, keccak256, padHex, parseUnits, stringToHex, toBytes, toEventSelector, toFunctionSelector } from "viem";
3
3
  import { Context, Data, Deferred, Effect, Exit, Fiber, Layer, Queue, Ref, Result, Schema, SchemaGetter, Scope } from "effect";
4
4
  import { makeFunctionReference } from "convex/server";
@@ -591,8 +591,6 @@ const EXEC_TRANSACTION_WITH_ROLE = "zodiac.roles.execTransactionWithRole";
591
591
  const ASSIGN_ROLES = "zodiac.roles.assignRoles";
592
592
  const SCOPE_TARGET = "zodiac.roles.scopeTarget";
593
593
  const OWNER_ROLE_LABEL = "Owner";
594
- const MARKETING_SUB_ACCOUNT_ID = "subaccount_marketing";
595
- const PAYROLL_SUB_ACCOUNT_ID = "subaccount_payroll";
596
594
  function usd(value) {
597
595
  return {
598
596
  currency: "USD",
@@ -630,7 +628,6 @@ function orgRoleKeyForLabel(label) {
630
628
  function soloOrgRoleTemplate() {
631
629
  return [{
632
630
  label: "Owner",
633
- subAccounts: { scope: "all" },
634
631
  canManageMembers: true,
635
632
  canManageRoles: true
636
633
  }];
@@ -644,8 +641,7 @@ function startupOrgRoleTemplate() {
644
641
  perTx: usd("25000"),
645
642
  perDay: usd("100000"),
646
643
  toRecipients: "anyone"
647
- },
648
- subAccounts: { scope: [MARKETING_SUB_ACCOUNT_ID] }
644
+ }
649
645
  },
650
646
  {
651
647
  label: "Team Lead",
@@ -653,8 +649,7 @@ function startupOrgRoleTemplate() {
653
649
  perTx: usd("5000"),
654
650
  perDay: usd("15000"),
655
651
  toRecipients: "anyone"
656
- },
657
- subAccounts: { scope: [PAYROLL_SUB_ACCOUNT_ID] }
652
+ }
658
653
  }
659
654
  ];
660
655
  }
@@ -723,6 +718,10 @@ new Map([
723
718
  ["setAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)", "SetAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)"]
724
719
  ].map(([functionSignature, eventSignature]) => [toFunctionSelector(functionSignature), toEventSelector(eventSignature)]));
725
720
  //#endregion
721
+ //#region ../config/src/capxul-payments-v2.ts
722
+ /** Immutable CapxulPaymentsV2 deployment on Base Sepolia. */
723
+ const CAPXUL_PAYMENTS_V2_ADDRESS = "0xA3ACDD016f706eD432A9a0545C45F0943f996b60";
724
+ //#endregion
726
725
  //#region src/telemetry/stack-frame-parser.ts
727
726
  /**
728
727
  * Regex for V8/Chrome stack trace frame lines.
@@ -925,6 +924,50 @@ function isProvisioningTelemetryDebugEnabled() {
925
924
  return globalThis.process?.env?.CAPXUL_DEBUG_TELEMETRY === "1";
926
925
  }
927
926
  //#endregion
927
+ //#region src/internal/invocation-observation.ts
928
+ const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
929
+ const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
930
+ /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
931
+ function attachInvocationObservation(target, source) {
932
+ const snapshot = Object.freeze(source.context === void 0 ? { active: source.active } : {
933
+ active: source.active,
934
+ context: Object.freeze({ ...source.context })
935
+ });
936
+ Object.defineProperty(target, INVOCATION_OBSERVATION, {
937
+ configurable: false,
938
+ enumerable: false,
939
+ value: snapshot,
940
+ writable: false
941
+ });
942
+ return target;
943
+ }
944
+ /** @internal Read the snapshot without exposing its symbol or adding a wire field. */
945
+ function readInvocationObservation(source) {
946
+ if (typeof source !== "object" || source === null) return void 0;
947
+ return source[INVOCATION_OBSERVATION];
948
+ }
949
+ /** @internal Carry a snapshot across an SDK adapter projection without resolving again. */
950
+ function copyInvocationObservation(source, target) {
951
+ const snapshot = readInvocationObservation(source);
952
+ return snapshot === void 0 ? target : attachInvocationObservation(target, snapshot);
953
+ }
954
+ /** @internal Carry the public call-start delivery decision with its failure envelope. */
955
+ function markFailureInvocationSnapshot(failure, snapshot) {
956
+ Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {
957
+ configurable: false,
958
+ enumerable: false,
959
+ value: Object.freeze(snapshot),
960
+ writable: false
961
+ });
962
+ return failure;
963
+ }
964
+ /** @internal Read the call-start delivery decision; undefined means a direct adapter call. */
965
+ function readFailureInvocationSnapshot(failure) {
966
+ if (typeof failure !== "object" || failure === null) return void 0;
967
+ const snapshot = failure[FAILURE_INVOCATION_SNAPSHOT];
968
+ return typeof snapshot === "object" && snapshot !== null && "active" in snapshot ? snapshot : void 0;
969
+ }
970
+ //#endregion
928
971
  //#region src/domain/machine/telemetry.ts
929
972
  const definedEntries = (values) => Object.fromEntries(Object.entries(values).filter((entry) => entry[1] !== void 0));
930
973
  const SAFE_ENGINEERING_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
@@ -1067,7 +1110,7 @@ const boot = (spec, options = {}) => Effect.gen(function* () {
1067
1110
  const makeFailure = (state, event, reason, details) => new ActorFailure(reason, spec.machine, spec.label(state), event._tag, details);
1068
1111
  const nonApplied = (state, event, reason, outcome, env) => {
1069
1112
  const slot = env.origin?.slot ?? spec.slot(event);
1070
- return {
1113
+ return copyInvocationObservation(env.invocation, {
1071
1114
  machine: spec.machine,
1072
1115
  state: spec.label(state),
1073
1116
  event: event._tag,
@@ -1077,9 +1120,9 @@ const boot = (spec, options = {}) => Effect.gen(function* () {
1077
1120
  duration_ms: duration(env.startedAt),
1078
1121
  ...withCarriage(env.invocation),
1079
1122
  ...outcome === "refused" ? { refusal_code: reason } : { error_code: reason }
1080
- };
1123
+ });
1081
1124
  };
1082
- const applied = (from, to, event, slot, epoch, env) => ({
1125
+ const applied = (from, to, event, slot, epoch, env) => copyInvocationObservation(env.invocation, {
1083
1126
  machine: spec.machine,
1084
1127
  from: spec.label(from),
1085
1128
  event: event._tag,
@@ -1564,6 +1607,24 @@ function mapAccountLifecycle(input) {
1564
1607
  }
1565
1608
  //#endregion
1566
1609
  //#region ../wire/src/brands.ts
1610
+ const lowercasedString = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1611
+ decode: SchemaGetter.transform((value) => value.toLowerCase()),
1612
+ encode: SchemaGetter.transform((value) => value)
1613
+ }));
1614
+ const addressSchema = (name) => lowercasedString.pipe(Schema.refine((value) => EVM_ADDRESS_RE$1.test(value), { message: `${name} must be a 0x-prefixed EVM address` }));
1615
+ const bytes32BrandSchema = (name) => lowercasedString.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: `${name} must be a 0x-prefixed bytes32 value` }));
1616
+ /** Lowercase, 0x-prefixed bytes32 evidence without a public brand. */
1617
+ const Bytes32Schema = bytes32BrandSchema("value");
1618
+ const AddressSchema$1 = addressSchema("address");
1619
+ const SafeAddressSchema = addressSchema("safe address");
1620
+ const ModuleAddressSchema = addressSchema("module address");
1621
+ const TxHashSchema$1 = bytes32BrandSchema("transaction hash");
1622
+ const RoleKeySchema = bytes32BrandSchema("role key");
1623
+ const AllowanceKeySchema = bytes32BrandSchema("allowance key");
1624
+ const BlockNumberSchema$1 = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1625
+ const LogIndexSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1626
+ const WeiAmountSchema$1 = Schema.String.pipe(Schema.refine((value) => WEI_RE.test(value), { message: "must be a non-negative integer string" }));
1627
+ const SettlementIdSchema = bytes32BrandSchema("settlementId").pipe(Schema.refine((value) => value !== ZERO_BYTES32, { message: "settlementId must not be zero" }));
1567
1628
  /**
1568
1629
  * `AppId` schema. Mirrors `toAppId` from `@capxul/types`:
1569
1630
  * `app_` + Crockford-base32 ULID (26 chars, first char in `[0-7]`).
@@ -1583,13 +1644,15 @@ const DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;
1583
1644
  * `DocumentHash` schema. Mirrors `toDocumentHash`: bare or 0x-prefixed bytes32,
1584
1645
  * normalized to lowercase 0x-prefixed form.
1585
1646
  */
1586
- const DocumentHashSchema$1 = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1647
+ const DocumentHashSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1587
1648
  decode: SchemaGetter.transform((s) => {
1588
1649
  const stripped = s.startsWith("0x") || s.startsWith("0X") ? s.slice(2) : s;
1589
1650
  return DOCUMENT_HASH_HEX_RE.test(stripped) ? `0x${stripped.toLowerCase()}` : s;
1590
1651
  }),
1591
1652
  encode: SchemaGetter.transform((s) => s)
1592
1653
  }), Schema.refine((s) => BYTES32_RE.test(s), { message: "must be 32 bytes of hex" }));
1654
+ /** L2 orchestrated money evidence requires a nonzero Document hash. */
1655
+ const NonzeroDocumentHashSchema = DocumentHashSchema.pipe(Schema.refine((value) => value !== ZERO_BYTES32, { message: "documentHash must not be zero" }));
1593
1656
  /**
1594
1657
  * `SessionToken` schema. Mirrors `toSessionToken`: non-empty string.
1595
1658
  * Issuance source distinguishes SDK-handshake tokens from auth-session
@@ -1606,6 +1669,25 @@ const EpochMsSchema$1 = Schema.Number.pipe(Schema.refine((n) => Number.isSafeInt
1606
1669
  const DurationMsSchema$1 = Schema.Number.pipe(Schema.refine((n) => Number.isSafeInteger(n) && n >= 0, { message: "must be a non-negative safe integer" }));
1607
1670
  //#endregion
1608
1671
  //#region ../wire/src/bootstrap.ts
1672
+ const PUBLIC_POSTHOG_PROJECT_TOKEN = /^phc_[A-Za-z0-9_-]{1,191}$/u;
1673
+ const PostHogIngestOrigin = Schema.String.pipe(Schema.refine((value) => {
1674
+ try {
1675
+ const url = new URL(value);
1676
+ return 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"));
1677
+ } catch {
1678
+ return false;
1679
+ }
1680
+ }, { message: "must be a credential-free PostHog HTTPS ingest origin" }));
1681
+ const EngineeringTelemetryBootstrapPolicy = Schema.Struct({
1682
+ host: PostHogIngestOrigin,
1683
+ projectToken: Schema.String.pipe(Schema.refine((value) => PUBLIC_POSTHOG_PROJECT_TOKEN.test(value), { message: "must be a public PostHog project token" })),
1684
+ capxulEnv: Schema.Union([
1685
+ Schema.Literal("development"),
1686
+ Schema.Literal("e2e"),
1687
+ Schema.Literal("staging"),
1688
+ Schema.Literal("production")
1689
+ ])
1690
+ });
1609
1691
  /**
1610
1692
  * `BootstrapEnvelope` v1.
1611
1693
  *
@@ -1631,7 +1713,8 @@ const BootstrapEnvelope = Schema.Struct({
1631
1713
  convexUrl: Schema.String,
1632
1714
  siteBaseUrl: Schema.String,
1633
1715
  openfortPublishableKey: Schema.String,
1634
- shieldPublishableKey: Schema.String
1716
+ shieldPublishableKey: Schema.String,
1717
+ engineeringTelemetry: Schema.optional(EngineeringTelemetryBootstrapPolicy)
1635
1718
  })
1636
1719
  });
1637
1720
  //#endregion
@@ -1646,15 +1729,6 @@ const CAPXUL_FUNCTIONS = {
1646
1729
  faucetMint: "account/actions:faucetMint",
1647
1730
  readBalance: "account/actions:readBalance"
1648
1731
  },
1649
- "financialOps/actions": {
1650
- cancelCommitment: "financialOps/actions:cancelCommitment",
1651
- claimCommitment: "financialOps/actions:claimCommitment",
1652
- markCommitmentCreated: "financialOps/actions:markCommitmentCreated",
1653
- markPaymentSettled: "financialOps/actions:markPaymentSettled",
1654
- markWithdrawalSettled: "financialOps/actions:markWithdrawalSettled",
1655
- recordOrgPayment: "financialOps/actions:recordOrgPayment",
1656
- redirectCommitment: "financialOps/actions:redirectCommitment"
1657
- },
1658
1732
  "financialOps/addressBook": {
1659
1733
  add: "financialOps/addressBook:add",
1660
1734
  get: "financialOps/addressBook:get",
@@ -1666,28 +1740,11 @@ const CAPXUL_FUNCTIONS = {
1666
1740
  "financialOps/destinations": {
1667
1741
  add: "financialOps/destinations:add",
1668
1742
  list: "financialOps/destinations:list",
1669
- payout: "financialOps/destinations:payout",
1670
1743
  remove: "financialOps/destinations:remove"
1671
1744
  },
1672
- "financialOps/insights": {
1673
- history: "financialOps/insights:history",
1674
- summary: "financialOps/insights:summary"
1675
- },
1676
- "financialOps/mutations": {
1677
- createPayee: "financialOps/mutations:createPayee",
1678
- pay: "financialOps/mutations:pay",
1679
- withdraw: "financialOps/mutations:withdraw"
1680
- },
1681
- "financialOps/payrollRoster": {
1682
- add: "financialOps/payrollRoster:add",
1683
- list: "financialOps/payrollRoster:list",
1684
- remove: "financialOps/payrollRoster:remove",
1685
- run: "financialOps/payrollRoster:run",
1686
- update: "financialOps/payrollRoster:update"
1687
- },
1745
+ "financialOps/mutations": { createPayee: "financialOps/mutations:createPayee" },
1688
1746
  "financialOps/queries": {
1689
1747
  depositInstructions: "financialOps/queries:depositInstructions",
1690
- getCommitmentRef: "financialOps/queries:getCommitmentRef",
1691
1748
  getPayee: "financialOps/queries:getPayee",
1692
1749
  getPayment: "financialOps/queries:getPayment",
1693
1750
  listPayments: "financialOps/queries:listPayments",
@@ -1704,8 +1761,7 @@ const CAPXUL_FUNCTIONS = {
1704
1761
  get: "financialOps/requestsInbox:get",
1705
1762
  inboxList: "financialOps/requestsInbox:inboxList",
1706
1763
  issue: "financialOps/requestsInbox:issue",
1707
- list: "financialOps/requestsInbox:list",
1708
- reconcile: "financialOps/requestsInbox:reconcile"
1764
+ list: "financialOps/requestsInbox:list"
1709
1765
  },
1710
1766
  "identity/mutations": {
1711
1767
  completeOnboarding: "identity/mutations:completeOnboarding",
@@ -1716,24 +1772,44 @@ const CAPXUL_FUNCTIONS = {
1716
1772
  loadByAuthUserId: "identity/queries:loadByAuthUserId",
1717
1773
  usernameAvailable: "identity/queries:usernameAvailable"
1718
1774
  },
1775
+ "holdings/actions": { current: "holdings/actions:current" },
1776
+ "movement/activity": {
1777
+ annotate: "movement/activity:annotate",
1778
+ get: "movement/activity:get",
1779
+ list: "movement/activity:list"
1780
+ },
1781
+ "moneyExecution/actions": {
1782
+ preparePermissionExecution: "moneyExecution/actions:preparePermissionExecution",
1783
+ preparePaymentExecution: "moneyExecution/actions:preparePaymentExecution",
1784
+ submitPermissionExecution: "moneyExecution/actions:submitPermissionExecution",
1785
+ submitPaymentExecution: "moneyExecution/actions:submitPaymentExecution"
1786
+ },
1787
+ "moneyExecution/paymentCommandActions": {
1788
+ preparePaymentLifecycleExecution: "moneyExecution/paymentCommandActions:preparePaymentLifecycleExecution",
1789
+ prepareOrganizationPaymentExecution: "moneyExecution/paymentCommandActions:prepareOrganizationPaymentExecution",
1790
+ submitPaymentCommandExecution: "moneyExecution/paymentCommandActions:submitPaymentCommandExecution"
1791
+ },
1719
1792
  media: {
1720
1793
  generateUploadUrl: "media:generateUploadUrl",
1721
1794
  setOrgLogo: "media:setOrgLogo",
1722
1795
  setProfileImage: "media:setProfileImage"
1723
1796
  },
1724
1797
  "org/actions": {
1725
- assignRole: "org/actions:assignRole",
1726
1798
  confirmBootstrap: "org/actions:confirmBootstrap",
1727
- deployOrgRoles: "org/actions:deployOrgRoles",
1728
1799
  detectAndAcceptPendingInvitations: "org/actions:detectAndAcceptPendingInvitations",
1729
1800
  inviteMember: "org/actions:inviteMember",
1730
1801
  prepareBootstrap: "org/actions:prepareBootstrap",
1731
1802
  prepareFounderAccount: "org/actions:prepareFounderAccount",
1732
1803
  readTreasury: "org/actions:readTreasury",
1733
- removeMember: "org/actions:removeMember",
1734
1804
  resumeBootstrapSubmission: "org/actions:resumeBootstrapSubmission",
1735
1805
  submitBootstrap: "org/actions:submitBootstrap"
1736
1806
  },
1807
+ "permission/actions": { verify: "permission/actions:verify" },
1808
+ "permission/mutations": { command: "permission/mutations:command" },
1809
+ "permission/queries": {
1810
+ authorize: "permission/queries:authorize",
1811
+ read: "permission/queries:read"
1812
+ },
1737
1813
  "org/lifecycle": {
1738
1814
  getProofReceipt: "org/lifecycle:getProofReceipt",
1739
1815
  load: "org/lifecycle:load",
@@ -1761,31 +1837,19 @@ const CAPXUL_FUNCTIONS = {
1761
1837
  loadByAuthUserId: "smartAccount/queries:loadByAuthUserId",
1762
1838
  loadBySmartAccountAddress: "smartAccount/queries:loadBySmartAccountAddress"
1763
1839
  },
1764
- "subAccount/actions": { transfer: "subAccount/actions:transfer" },
1765
- "subAccount/mutations": {
1766
- create: "subAccount/mutations:create",
1767
- remove: "subAccount/mutations:remove",
1768
- rename: "subAccount/mutations:rename"
1769
- },
1770
- "subAccount/queries": {
1771
- get: "subAccount/queries:get",
1772
- list: "subAccount/queries:list"
1773
- },
1774
1840
  system: { health: "system:health" }
1775
1841
  };
1776
1842
  //#endregion
1777
1843
  //#region ../wire/src/status.ts
1778
- /** Payment lifecycle states carried on the wire (ADR-0018 P1). */
1779
- const PAYMENT_STATUSES = [
1844
+ /** The closed L2 Payment status authority. */
1845
+ const L2_PAYMENT_STATUSES = [
1780
1846
  "pending",
1781
- "submitted",
1782
- "pending_claim",
1847
+ "settling",
1783
1848
  "scheduled",
1784
1849
  "streaming",
1850
+ "pending_claim",
1785
1851
  "settled",
1786
1852
  "cancelled",
1787
- "redirected",
1788
- "expired",
1789
1853
  "failed"
1790
1854
  ];
1791
1855
  /** What a payment is FOR. Pairs with `PAYMENT_DOCUMENT_KINDS`. */
@@ -1824,7 +1888,7 @@ const HANDLE_RE = /^@?[a-z0-9][a-z0-9-]{2,31}$/;
1824
1888
  const ORG_HANDLE_RE = /^[a-z0-9][a-z0-9-]{2,31}$/;
1825
1889
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1826
1890
  const MinorUnitStringSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => MINOR_UNIT_STRING_RE.test(value), { message: "must be a non-negative integer minor-unit string" })));
1827
- const PaymentIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PAYMENT_ID_RE.test(value), { message: "must be payment_ plus an alphanumeric id" })));
1891
+ const PaymentIdSchema$1 = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PAYMENT_ID_RE.test(value), { message: "must be payment_ plus an alphanumeric id" })));
1828
1892
  const PayeeIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PAYEE_ID_RE.test(value), { message: "must be payee_ plus an alphanumeric id" })));
1829
1893
  const OrgIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => ORG_ID_RE.test(value), { message: "must be org_ plus an alphanumeric id" })));
1830
1894
  const UserIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => USER_ID_RE.test(value), { message: "must be user_ plus an alphanumeric id" })));
@@ -1832,7 +1896,7 @@ const DecimalStringSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((v
1832
1896
  const HandleValueSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => !EVM_ADDRESS_RE.test(value) && HANDLE_RE.test(value), { message: "must be a handle; raw addresses are not accepted" })));
1833
1897
  const OrgHandleValueSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => !EVM_ADDRESS_RE.test(value) && ORG_HANDLE_RE.test(value), { message: "must be an org handle; raw addresses are not accepted" })));
1834
1898
  const EmailValueSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => !EVM_ADDRESS_RE.test(value) && EMAIL_RE.test(value), { message: "must be an email; raw addresses are not accepted" })));
1835
- const Uint8Schema = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0 && value <= 255, { message: "must be a uint8" })));
1899
+ const Uint8Schema$1 = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0 && value <= 255, { message: "must be a uint8" })));
1836
1900
  const Uint64Schema = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" })));
1837
1901
  const PaymentDocumentDomain = Schema.Struct({
1838
1902
  name: Schema.Literal("CapxulPayments"),
@@ -1853,10 +1917,10 @@ const InvoiceDocument = Schema.Struct({
1853
1917
  payeeRef: Schema.String,
1854
1918
  amount: MinorUnitStringSchema,
1855
1919
  currency: CurrencyCodeSchema$1,
1856
- decimals: Uint8Schema,
1920
+ decimals: Uint8Schema$1,
1857
1921
  issuedAt: Uint64Schema,
1858
1922
  dueAt: Uint64Schema,
1859
- lineItemsHash: DocumentHashSchema$1
1923
+ lineItemsHash: DocumentHashSchema
1860
1924
  });
1861
1925
  const PayslipDocument = Schema.Struct({
1862
1926
  kind: Schema.Literal(2),
@@ -1866,7 +1930,7 @@ const PayslipDocument = Schema.Struct({
1866
1930
  gross: MinorUnitStringSchema,
1867
1931
  net: MinorUnitStringSchema,
1868
1932
  currency: CurrencyCodeSchema$1,
1869
- decimals: Uint8Schema,
1933
+ decimals: Uint8Schema$1,
1870
1934
  issuedAt: Uint64Schema
1871
1935
  });
1872
1936
  const ReceiptDocument = Schema.Struct({
@@ -1874,7 +1938,7 @@ const ReceiptDocument = Schema.Struct({
1874
1938
  reference: Schema.String,
1875
1939
  amount: MinorUnitStringSchema,
1876
1940
  currency: CurrencyCodeSchema$1,
1877
- decimals: Uint8Schema,
1941
+ decimals: Uint8Schema$1,
1878
1942
  paidAt: Uint64Schema,
1879
1943
  note: Schema.String
1880
1944
  });
@@ -1884,7 +1948,7 @@ const WithdrawalDocument = Schema.Struct({
1884
1948
  reference: Schema.String,
1885
1949
  amount: MinorUnitStringSchema,
1886
1950
  currency: CurrencyCodeSchema$1,
1887
- decimals: Uint8Schema,
1951
+ decimals: Uint8Schema$1,
1888
1952
  destChain: ChainIdSchema$1,
1889
1953
  destAddress: WithdrawalDestAddressSchema,
1890
1954
  settledAt: Uint64Schema,
@@ -1897,7 +1961,7 @@ const FinancialOpsMoney = Schema.Struct({
1897
1961
  decimals: Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" })))
1898
1962
  });
1899
1963
  const PaymentDocument = Schema.Struct({
1900
- documentHash: DocumentHashSchema$1,
1964
+ documentHash: DocumentHashSchema,
1901
1965
  kind: Schema.Literals(PAYMENT_DOCUMENT_KINDS),
1902
1966
  title: Schema.optional(Schema.String),
1903
1967
  uri: Schema.optional(Schema.String),
@@ -2023,8 +2087,8 @@ const PaymentRef = Schema.Union([
2023
2087
  })
2024
2088
  ]);
2025
2089
  const Payment = Schema.Struct({
2026
- id: PaymentIdSchema,
2027
- status: Schema.Literals(PAYMENT_STATUSES),
2090
+ id: PaymentIdSchema$1,
2091
+ status: Schema.Literals(L2_PAYMENT_STATUSES),
2028
2092
  amount: FinancialOpsMoney,
2029
2093
  paymentType: PaymentType,
2030
2094
  recipient: PaymentRecipient,
@@ -2088,260 +2152,1276 @@ Schema.Struct({
2088
2152
  version: Schema.Literal(1),
2089
2153
  payments: Schema.Array(Payment)
2090
2154
  });
2091
- `
2092
- .capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;
2093
- font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;
2094
- color:var(--ink);background:var(--bg);max-width:44rem;margin:0 auto;padding:2.75rem 3rem;
2095
- border:1px solid var(--line);border-radius:16px;box-shadow:0 1px 2px rgba(0,0,0,.04),0 12px 32px rgba(0,0,0,.06);
2096
- line-height:1.5;font-size:15px;overflow-wrap:anywhere;word-break:break-word}
2097
- .capxul-doc *{box-sizing:border-box;min-width:0}
2098
- .capxul-doc .doc-header{display:flex;flex-direction:column;gap:1.25rem;padding-bottom:1.5rem;border-bottom:1px solid var(--line);margin-bottom:1.75rem}
2099
- .capxul-doc .doc-brand{display:flex;align-items:center;gap:.5rem;color:var(--accent);font-weight:600}
2100
- .capxul-doc .doc-brand-mark{font-size:1.1rem}
2101
- .capxul-doc .doc-brand-name{letter-spacing:.02em}
2102
- .capxul-doc .doc-headline{display:flex;align-items:baseline;justify-content:space-between;gap:1rem;flex-wrap:wrap}
2103
- .capxul-doc .doc-title{font-size:1.9rem;font-weight:700;letter-spacing:-.02em;margin:0}
2104
- .capxul-doc .doc-badge{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;
2105
- color:var(--accent);background:rgba(10,125,75,.1);padding:.3rem .6rem;border-radius:999px;max-width:100%;text-align:right}
2106
- .capxul-doc .doc-parties{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;margin-bottom:1.75rem}
2107
- .capxul-doc .doc-party{display:flex;flex-direction:column;gap:.15rem}
2108
- .capxul-doc .doc-party-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
2109
- .capxul-doc .doc-party-name{font-weight:600}
2110
- .capxul-doc .doc-meta{display:flex;flex-direction:column;gap:.4rem;margin-bottom:1.75rem}
2111
- .capxul-doc .doc-meta-row{display:flex;justify-content:space-between;gap:1rem;font-size:.92rem}
2112
- .capxul-doc .doc-meta-label{color:var(--muted);flex-shrink:0}
2113
- .capxul-doc .doc-meta-value{font-weight:500;text-align:right}
2114
- .capxul-doc time{color:var(--ink);font-variant-numeric:tabular-nums}
2115
- .capxul-doc .doc-line-items{width:100%;border-collapse:collapse;margin:.5rem 0 1.5rem;font-size:.92rem}
2116
- .capxul-doc .doc-line-items th{text-align:left;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;
2117
- color:var(--muted);font-weight:600;padding:.5rem .25rem;border-bottom:1px solid var(--line)}
2118
- .capxul-doc .doc-line-items td{padding:.7rem .25rem;border-bottom:1px solid var(--line)}
2119
- .capxul-doc .doc-li-qty,.capxul-doc .doc-li-unit,.capxul-doc .doc-li-total{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
2120
- .capxul-doc .doc-li-desc{width:100%}
2121
- .capxul-doc .doc-totals{display:flex;flex-direction:column;gap:.5rem;margin-top:.5rem}
2122
- .capxul-doc .doc-total-line{display:flex;justify-content:space-between;align-items:baseline;gap:1rem}
2123
- .capxul-doc .doc-total-label{color:var(--muted)}
2124
- .capxul-doc .doc-total-deduction .doc-amount-value{color:var(--muted)}
2125
- .capxul-doc .doc-total-grand{border-top:2px solid var(--ink);margin-top:.5rem;padding-top:.75rem;font-size:1.15rem}
2126
- .capxul-doc .doc-total-grand .doc-amount-value{font-weight:700}
2127
- .capxul-doc .doc-amount-value{font-variant-numeric:tabular-nums;font-weight:600}
2128
- .capxul-doc .doc-hero{text-align:center;padding:1.5rem 0 2rem}
2129
- .capxul-doc .doc-hero-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
2130
- .capxul-doc .doc-hero-amount{font-size:2.6rem;font-weight:700;letter-spacing:-.02em;margin-top:.35rem}
2131
- .capxul-doc .doc-note{color:var(--ink);background:#f7f7f8;border-radius:10px;padding:.9rem 1.1rem;margin:0}
2132
- .capxul-doc .doc-dest-address{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9rem}
2133
- .capxul-doc .doc-footer{margin-top:1.75rem;padding-top:1.25rem;border-top:1px solid var(--line);color:var(--muted);font-size:.9rem}
2134
- .capxul-doc code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.82rem;color:var(--muted);word-break:break-all}
2135
- @media (max-width:540px){.capxul-doc{padding:1.75rem 1.25rem}.capxul-doc .doc-parties{grid-template-columns:1fr}}
2136
- `.trim();
2137
- //#endregion
2138
- //#region ../wire/src/secret-material.ts
2139
- const SENSITIVE_MATERIAL_PATTERNS = [
2140
- /0x[a-fA-F0-9]{40,}/u,
2141
- /(?:^|[^a-fA-F0-9])[a-fA-F0-9]{64}(?:$|[^a-fA-F0-9])/u,
2142
- /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/u,
2143
- /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/iu
2144
- ];
2145
- /**
2146
- * Reject: does the value carry any known secret material? Best effort — callers
2147
- * drop the whole value on a match; a false negative is a leak, a false positive
2148
- * merely omits an observation field.
2149
- */
2150
- function containsSensitiveMaterial(value) {
2151
- return SENSITIVE_MATERIAL_PATTERNS.some((pattern) => pattern.test(value));
2152
- }
2153
- //#endregion
2154
- //#region ../wire/src/observation-context.ts
2155
- /** Single bounded HTTP carrier used before a Convex action envelope exists. */
2156
- const OBSERVATION_CONTEXT_HEADER = "x-capxul-observation-context";
2157
- const FIELD_RULES = {
2158
- application: {
2159
- maxLength: 64,
2160
- pattern: /^[A-Za-z0-9][A-Za-z0-9._-]*$/u
2161
- },
2162
- applicationId: {
2163
- maxLength: 30,
2164
- pattern: APP_ID_RE
2165
- },
2166
- release: {
2167
- maxLength: 128,
2168
- pattern: /^[A-Za-z0-9][A-Za-z0-9._+@:/-]*$/u
2169
- },
2170
- sessionId: {
2171
- maxLength: 128,
2172
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2173
- },
2174
- organizationId: {
2175
- maxLength: 128,
2176
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2177
- },
2178
- journeyId: {
2179
- maxLength: 128,
2180
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2181
- },
2182
- correlationId: {
2183
- maxLength: 128,
2184
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2185
- },
2186
- anonymousId: {
2187
- maxLength: 128,
2188
- pattern: /^anon_[A-Za-z0-9-]+$/u
2189
- },
2190
- traceparent: {
2191
- maxLength: 55,
2192
- pattern: /^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/u
2193
- }
2194
- };
2195
- /**
2196
- * Copy only the canonical allowlist and silently omit malformed/sensitive
2197
- * values. Observation metadata is best effort and may never reject a domain
2198
- * operation.
2199
- */
2200
- function sanitizeObservationContext(input) {
2201
- if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
2202
- const source = input;
2203
- const sanitized = {};
2204
- for (const field of Object.keys(FIELD_RULES)) {
2205
- const value = source[field];
2206
- if (!isSafeField(field, value)) continue;
2207
- sanitized[field] = value;
2208
- }
2209
- return Object.keys(sanitized).length === 0 ? void 0 : sanitized;
2210
- }
2211
- /** Encode only the sanitized allowlist; absence stays absence. */
2212
- function encodeObservationContextHeader(input) {
2213
- const sanitized = sanitizeObservationContext(input);
2214
- return sanitized === void 0 ? void 0 : JSON.stringify(sanitized);
2215
- }
2216
- function isSafeField(field, value) {
2217
- if (typeof value !== "string") return false;
2218
- const rule = FIELD_RULES[field];
2219
- return value.length > 0 && value.length <= rule.maxLength && value === value.trim() && !value.includes("://") && !containsSensitiveMaterial(value) && rule.pattern.test(value);
2220
- }
2221
2155
  //#endregion
2222
- //#region src/contract/actor-scope.ts
2223
- const actorScopeContract = {
2224
- addressBookList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].list),
2225
- addressBookGet: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].get),
2226
- addressBookAdd: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].add),
2227
- addressBookHide: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].hide),
2228
- addressBookUnhide: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].unhide),
2229
- addressBookLabel: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].label),
2230
- requestsIssue: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].issue),
2231
- requestsList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].list),
2232
- requestsGet: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].get),
2233
- requestsCancel: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].cancel),
2234
- requestsReconcile: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].reconcile),
2235
- inboxList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].inboxList),
2236
- inboxApprove: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].approve),
2237
- inboxDecline: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].decline),
2238
- insightsSummary: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/insights"].summary),
2239
- insightsHistory: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/insights"].history)
2156
+ //#region ../wire/src/l2-money.ts
2157
+ const nonEmpty = (name) => Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: `${name} must not be empty` }));
2158
+ const nonNegativeInteger = (name) => Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: `${name} must be a non-negative safe integer` }));
2159
+ const BaseSepoliaChainIdSchema = ChainIdSchema$1.pipe(Schema.refine((value) => value === 84532, { message: "chainId must be 84532" }));
2160
+ const Uint16Schema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0 && value <= 65535, { message: "kind must be a uint16 value" }));
2161
+ const Uint8Schema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0 && value <= 255, { message: "must be a uint8 value" }));
2162
+ const Bytes4Schema = Schema.String.pipe(Schema.refine((value) => /^0x[0-9a-fA-F]{8}$/u.test(value), { message: "must be a 0x-prefixed bytes4 value" }));
2163
+ const HexDataSchema = Schema.String.pipe(Schema.refine((value) => /^0x(?:[0-9a-fA-F]{2})*$/u.test(value), { message: "must be 0x-prefixed byte data" }));
2164
+ const Uint48Schema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0 && value <= 0xffffffffffff, { message: "must be a uint48 value" }));
2165
+ const Uint256StringSchema = Schema.String.pipe(Schema.refine((value) => {
2166
+ if (!/^(0|[1-9][0-9]*)$/u.test(value)) return false;
2167
+ return BigInt(value) < 1n << 256n;
2168
+ }, { message: "must be a uint256 base-10 string" }));
2169
+ const PaymentIdSchema = nonEmpty("paymentId").pipe(Schema.refine((value) => value.length > 0));
2170
+ const MovementIdSchema = nonEmpty("movementId").pipe(Schema.refine((value) => value.length > 0));
2171
+ const PermissionIdSchema = nonEmpty("permissionId").pipe(Schema.refine((value) => value.length > 0));
2172
+ const PermissionAssignmentIdSchema = nonEmpty("permissionAssignmentId").pipe(Schema.refine((value) => value.length > 0));
2173
+ const PaymentCommandIdSchema = nonEmpty("commandId").pipe(Schema.refine((value) => value.length > 0));
2174
+ const PAYMENT_PURPOSE_KIND_CODES = {
2175
+ quick_pay: 0,
2176
+ invoice: 1,
2177
+ payroll: 2,
2178
+ reimbursement: 3
2240
2179
  };
2241
- //#endregion
2242
- //#region src/surface/contacts.ts
2243
- function makeActorRelationshipMethods(deps) {
2244
- const domain = deps.actor.kind === "account" ? "account" : "org";
2245
- const actor = deps.actor;
2246
- const convexCall = deps.convexCall;
2247
- if (convexCall === void 0) return makeNotImplementedActorRelationshipMethods(deps, domain);
2248
- const fns = actorScopeContract;
2249
- return {
2250
- addressBook: {
2251
- list: (options) => mapOk$2(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
2252
- get: async (entryId, options) => {
2253
- const ref = refFromEntryId(entryId);
2254
- if (!ref.ok) return ref;
2255
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
2256
- actor,
2257
- ref: ref.value
2258
- })), (entry) => entry === null ? null : mapAddressBookEntry(entry));
2259
- },
2260
- add: async (input, options) => {
2261
- const ref = normalizeRefForBackend$1(input.ref, "ref");
2262
- if (!ref.ok) return ref;
2263
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
2264
- actor,
2265
- ref: ref.value,
2266
- ...input.label === void 0 ? {} : { label: input.label }
2267
- })), mapAddressBookEntry);
2268
- },
2269
- hide: async (entryId, options) => {
2270
- const ref = refFromEntryId(entryId);
2271
- if (!ref.ok) return ref;
2272
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
2273
- actor,
2274
- ref: ref.value
2275
- })), mapAddressBookEntry);
2276
- },
2277
- unhide: async (entryId, options) => {
2278
- const ref = refFromEntryId(entryId);
2279
- if (!ref.ok) return ref;
2280
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
2281
- actor,
2282
- ref: ref.value
2283
- })), mapAddressBookEntry);
2284
- },
2285
- label: async (input, options) => {
2286
- const ref = refFromEntryId(input.entryId);
2287
- if (!ref.ok) return ref;
2288
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
2289
- actor,
2290
- ref: ref.value,
2291
- label: input.label
2292
- })), mapAddressBookEntry);
2293
- }
2294
- },
2295
- requests: {
2296
- issue: async (input, options) => {
2297
- const payer = normalizeRefForBackend$1(input.payer, "payer");
2298
- if (!payer.ok) return payer;
2299
- return mapOk$2(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
2300
- actor,
2301
- payer: payer.value,
2302
- amount: input.amount,
2180
+ const PaymentPurposeKindSchema = Schema.String.pipe(Schema.refine((value) => Object.hasOwn(PAYMENT_PURPOSE_KIND_CODES, value), { message: "purposeKind must be a registered L2 value" }));
2181
+ const AccountActorRefSchema = Schema.Struct({
2182
+ kind: Schema.Literal("account"),
2183
+ accountId: nonEmpty("accountId")
2184
+ });
2185
+ const OrganizationActorRefSchema = Schema.Struct({
2186
+ kind: Schema.Literal("organization"),
2187
+ orgId: nonEmpty("orgId")
2188
+ });
2189
+ const ActorRefSchema = Schema.Union([AccountActorRefSchema, OrganizationActorRefSchema]);
2190
+ const hasActorBoundPermission = (actor, orgId, permissionId) => actor.kind === "organization" ? orgId === actor.orgId && permissionId !== void 0 : orgId === void 0 && permissionId === void 0;
2191
+ const ActorOrDestinationRefSchema = Schema.Union([ActorRefSchema, Schema.Struct({
2192
+ kind: Schema.Literal("destination"),
2193
+ destinationId: nonEmpty("destinationId")
2194
+ })]);
2195
+ Schema.Literals([
2196
+ "Payment",
2197
+ "Payout",
2198
+ "Deposit"
2199
+ ]);
2200
+ const PaymentStatusSchema = Schema.Literals(L2_PAYMENT_STATUSES);
2201
+ const ReleaseTermsSchema = PaymentTiming;
2202
+ const PaymentLedgerBaseSchema = Schema.Struct({
2203
+ paymentId: PaymentIdSchema,
2204
+ status: PaymentStatusSchema,
2205
+ actor: ActorRefSchema,
2206
+ recipient: ActorOrDestinationRefSchema,
2207
+ amount: FinancialOpsMoney,
2208
+ chainId: ChainIdSchema$1,
2209
+ tokenAddress: AddressSchema$1,
2210
+ release: ReleaseTermsSchema,
2211
+ createdAt: nonNegativeInteger("createdAt"),
2212
+ updatedAt: nonNegativeInteger("updatedAt")
2213
+ });
2214
+ const PaymentLedgerRecordSchema = Schema.Union([Schema.Struct({
2215
+ ...PaymentLedgerBaseSchema.fields,
2216
+ ledgerKind: Schema.Literals(["Payment", "Payout"]),
2217
+ purposeKind: PaymentPurposeKindSchema,
2218
+ permissionId: Schema.optional(PermissionIdSchema),
2219
+ settlementId: SettlementIdSchema,
2220
+ movementId: Schema.optional(MovementIdSchema),
2221
+ documentHash: NonzeroDocumentHashSchema,
2222
+ userOpHash: Schema.optional(Bytes32Schema),
2223
+ txHash: Schema.optional(TxHashSchema$1),
2224
+ settlementLogIndex: Schema.optional(LogIndexSchema),
2225
+ settledBlockNumber: Schema.optional(BlockNumberSchema$1),
2226
+ settledBlockHash: Schema.optional(Bytes32Schema),
2227
+ settledEventLogIndex: Schema.optional(LogIndexSchema)
2228
+ }), Schema.Struct({
2229
+ ...PaymentLedgerBaseSchema.fields,
2230
+ ledgerKind: Schema.Literal("Deposit"),
2231
+ movementId: MovementIdSchema,
2232
+ settlementId: Schema.optional(Schema.Never),
2233
+ documentHash: Schema.optional(Schema.Never),
2234
+ permissionId: Schema.optional(Schema.Never),
2235
+ purposeKind: Schema.optional(Schema.Never)
2236
+ })]).pipe(Schema.refine((record) => record.ledgerKind === "Deposit" || hasActorBoundPermission(record.actor, record.actor.kind === "organization" ? record.actor.orgId : void 0, record.permissionId), { message: "Organization Payment and Payout records require permissionId; personal records forbid it" }));
2237
+ const MovementIdentitySchema = Schema.Struct({
2238
+ chainId: ChainIdSchema$1,
2239
+ tokenAddress: AddressSchema$1,
2240
+ txHash: TxHashSchema$1,
2241
+ logIndex: LogIndexSchema
2242
+ });
2243
+ const MovementCanonicalStateSchema = Schema.Literals([
2244
+ "observed",
2245
+ "finalized",
2246
+ "removed"
2247
+ ]);
2248
+ const MovementSchema = Schema.Struct({
2249
+ ...MovementIdentitySchema.fields,
2250
+ movementId: MovementIdSchema,
2251
+ blockNumber: BlockNumberSchema$1,
2252
+ blockHash: Bytes32Schema,
2253
+ source: AddressSchema$1,
2254
+ destination: AddressSchema$1,
2255
+ rawAmount: WeiAmountSchema$1,
2256
+ canonicalState: MovementCanonicalStateSchema
2257
+ });
2258
+ const MovementClassificationSchema = Schema.Literals([
2259
+ "protocol_settlement",
2260
+ "deposit",
2261
+ "movement_only_outflow"
2262
+ ]);
2263
+ const MovementAttributionSchema = Schema.Struct({
2264
+ movementId: MovementIdSchema,
2265
+ actor: ActorRefSchema,
2266
+ side: Schema.Literals(["source", "destination"]),
2267
+ classification: MovementClassificationSchema
2268
+ });
2269
+ Schema.Struct({
2270
+ movementId: MovementIdSchema,
2271
+ actor: ActorRefSchema,
2272
+ counterpartyLabel: Schema.optional(Schema.String),
2273
+ accountingCategory: Schema.optional(Schema.String),
2274
+ memo: Schema.optional(Schema.String),
2275
+ lastEditor: ActorRefSchema,
2276
+ updatedAt: nonNegativeInteger("updatedAt")
2277
+ });
2278
+ const ReceiptRefSchema = Schema.Struct({
2279
+ chainId: BaseSepoliaChainIdSchema,
2280
+ userOpHash: Bytes32Schema,
2281
+ transactionHash: TxHashSchema$1,
2282
+ blockNumber: BlockNumberSchema$1,
2283
+ blockHash: Bytes32Schema
2284
+ });
2285
+ const EventRefSchema = Schema.Struct({
2286
+ ...ReceiptRefSchema.fields,
2287
+ emitter: AddressSchema$1,
2288
+ transactionIndex: LogIndexSchema,
2289
+ logIndex: LogIndexSchema,
2290
+ topic0: Bytes32Schema,
2291
+ dataHash: Bytes32Schema
2292
+ });
2293
+ const PermissionOperationSchema = Schema.Literals([
2294
+ "create",
2295
+ "change",
2296
+ "assign",
2297
+ "revoke",
2298
+ "replace"
2299
+ ]);
2300
+ const PermissionStateSchema = Schema.Literals([
2301
+ "pending",
2302
+ "active",
2303
+ "suspended",
2304
+ "revoked",
2305
+ "superseded",
2306
+ "quarantined"
2307
+ ]);
2308
+ const StoredPermissionCommandSchema = Schema.Struct({
2309
+ commandId: PaymentCommandIdSchema,
2310
+ orgId: nonEmpty("orgId"),
2311
+ operation: PermissionOperationSchema,
2312
+ permissionId: PermissionIdSchema,
2313
+ permissionAssignmentId: Schema.NullOr(PermissionAssignmentIdSchema),
2314
+ expectedRevision: nonNegativeInteger("expectedRevision"),
2315
+ userOpSenderSafe: SafeAddressSchema,
2316
+ organizationSafe: SafeAddressSchema,
2317
+ rolesModule: ModuleAddressSchema,
2318
+ roleKey: RoleKeySchema,
2319
+ allowanceKey: Schema.NullOr(AllowanceKeySchema),
2320
+ memberSafe: Schema.NullOr(SafeAddressSchema),
2321
+ expectedAuthorityEvents: Schema.Array(Bytes32Schema)
2322
+ });
2323
+ Schema.Struct({
2324
+ command: StoredPermissionCommandSchema,
2325
+ userOpHash: Bytes32Schema
2326
+ });
2327
+ Schema.Union([
2328
+ Schema.Struct({
2329
+ status: Schema.Literal("pending"),
2330
+ reason: Schema.Literals(["receipt_missing", "not_finalized"]),
2331
+ receipt: Schema.optional(ReceiptRefSchema)
2332
+ }),
2333
+ Schema.Struct({
2334
+ status: Schema.Literal("verified"),
2335
+ commandId: PaymentCommandIdSchema,
2336
+ receipt: ReceiptRefSchema,
2337
+ events: Schema.Array(EventRefSchema),
2338
+ factsHash: Bytes32Schema
2339
+ }),
2340
+ Schema.Struct({
2341
+ status: Schema.Literal("mismatch"),
2342
+ code: Schema.Literals([
2343
+ "wrong_chain",
2344
+ "wrong_sender",
2345
+ "failed_user_operation",
2346
+ "non_canonical_block",
2347
+ "wrong_contract_identity",
2348
+ "missing_event",
2349
+ "extra_authority_event",
2350
+ "wrong_event_order",
2351
+ "wrong_fact_tuple",
2352
+ "wrong_state",
2353
+ "conflicting_replay"
2354
+ ]),
2355
+ receipt: Schema.optional(ReceiptRefSchema)
2356
+ }),
2357
+ Schema.Struct({
2358
+ status: Schema.Literal("provider_failure"),
2359
+ retryable: Schema.Literal(true)
2360
+ })
2361
+ ]);
2362
+ Schema.Struct({
2363
+ commandId: PaymentCommandIdSchema,
2364
+ expectedRevision: nonNegativeInteger("expectedRevision"),
2365
+ verification: Schema.Struct({
2366
+ status: Schema.Literal("verified"),
2367
+ commandId: PaymentCommandIdSchema,
2368
+ receipt: ReceiptRefSchema,
2369
+ events: Schema.Array(EventRefSchema),
2370
+ factsHash: Bytes32Schema
2371
+ })
2372
+ });
2373
+ Schema.Union([Schema.Struct({
2374
+ status: Schema.Literals(["applied", "replayed"]),
2375
+ revision: nonNegativeInteger("revision")
2376
+ }), Schema.Struct({ status: Schema.Literals(["revision_mismatch", "conflicting_replay"]) })]);
2377
+ const PermissionSchema = Schema.Struct({
2378
+ permissionId: PermissionIdSchema,
2379
+ orgId: nonEmpty("orgId"),
2380
+ type: Schema.Literals(["budget", "managePeople"]),
2381
+ state: PermissionStateSchema,
2382
+ revision: nonNegativeInteger("revision"),
2383
+ roleKey: RoleKeySchema,
2384
+ tokenAddress: Schema.optional(AddressSchema$1),
2385
+ limitRaw: Schema.optional(WeiAmountSchema$1),
2386
+ allowanceKey: Schema.optional(AllowanceKeySchema)
2387
+ });
2388
+ const PermissionAssignmentSchema = Schema.Struct({
2389
+ permissionAssignmentId: PermissionAssignmentIdSchema,
2390
+ permissionId: PermissionIdSchema,
2391
+ actor: ActorRefSchema,
2392
+ state: PermissionStateSchema
2393
+ });
2394
+ Schema.Struct({
2395
+ orgId: nonEmpty("orgId"),
2396
+ actor: ActorRefSchema,
2397
+ permissionId: PermissionIdSchema,
2398
+ tokenAddress: AddressSchema$1,
2399
+ rawAmount: WeiAmountSchema$1
2400
+ });
2401
+ Schema.Struct({
2402
+ permission: PermissionSchema,
2403
+ assignment: PermissionAssignmentSchema
2404
+ });
2405
+ Schema.Struct({
2406
+ chainId: ChainIdSchema$1,
2407
+ tokenAddress: AddressSchema$1,
2408
+ symbol: nonEmpty("symbol"),
2409
+ decimals: nonNegativeInteger("decimals"),
2410
+ deploymentStartBlock: BlockNumberSchema$1
2411
+ });
2412
+ const HoldingRowSchema = Schema.Union([Schema.Struct({
2413
+ assetKind: Schema.Literal("native"),
2414
+ symbol: Schema.optional(Schema.String),
2415
+ decimals: Schema.optional(nonNegativeInteger("decimals")),
2416
+ rawBalance: WeiAmountSchema$1
2417
+ }), Schema.Struct({
2418
+ assetKind: Schema.Literal("erc20"),
2419
+ tokenAddress: AddressSchema$1,
2420
+ symbol: Schema.optional(Schema.String),
2421
+ decimals: Schema.optional(nonNegativeInteger("decimals")),
2422
+ rawBalance: WeiAmountSchema$1
2423
+ })]);
2424
+ Schema.Struct({
2425
+ actor: ActorRefSchema,
2426
+ chainId: ChainIdSchema$1,
2427
+ observedAt: nonNegativeInteger("observedAt"),
2428
+ stale: Schema.Boolean,
2429
+ rows: Schema.Array(HoldingRowSchema)
2430
+ });
2431
+ const PaymentCoreErrorSchema = Schema.Union([
2432
+ Schema.Struct({
2433
+ code: Schema.Literal("INVALID_TRANSITION"),
2434
+ status: PaymentStatusSchema,
2435
+ event: nonEmpty("event")
2436
+ }),
2437
+ Schema.Struct({
2438
+ code: Schema.Literal("ALREADY_SETTLED"),
2439
+ paymentId: PaymentIdSchema
2440
+ }),
2441
+ Schema.Struct({ code: Schema.Literals([
2442
+ "EVIDENCE_MISSING",
2443
+ "EVIDENCE_MISMATCH",
2444
+ "EVIDENCE_REPLAY"
2445
+ ]) })
2446
+ ]);
2447
+ Schema.Union([
2448
+ Schema.Struct({ type: Schema.Literal("commitment_created") }),
2449
+ Schema.Struct({
2450
+ type: Schema.Literal("claim"),
2451
+ rawAmount: WeiAmountSchema$1
2452
+ }),
2453
+ Schema.Struct({ type: Schema.Literal("cancel") }),
2454
+ Schema.Struct({
2455
+ type: Schema.Literal("redirect"),
2456
+ recipient: ActorOrDestinationRefSchema
2457
+ }),
2458
+ Schema.Struct({
2459
+ type: Schema.Literal("fail"),
2460
+ reasonCode: nonEmpty("reasonCode")
2461
+ })
2462
+ ]);
2463
+ const PaymentTransitionEventSchema = Schema.Union([
2464
+ Schema.Struct({
2465
+ type: Schema.Literal("claim"),
2466
+ rawAmount: WeiAmountSchema$1
2467
+ }),
2468
+ Schema.Struct({ type: Schema.Literal("cancel") }),
2469
+ Schema.Struct({
2470
+ type: Schema.Literal("redirect"),
2471
+ recipient: ActorOrDestinationRefSchema
2472
+ }),
2473
+ Schema.Struct({
2474
+ type: Schema.Literal("fail"),
2475
+ reasonCode: nonEmpty("reasonCode")
2476
+ })
2477
+ ]);
2478
+ const ExpectedPaymentCommonSchema = Schema.Struct({
2479
+ chainId: BaseSepoliaChainIdSchema,
2480
+ contractAddress: AddressSchema$1,
2481
+ userOpHash: Bytes32Schema,
2482
+ userOpSenderSafe: SafeAddressSchema
2483
+ });
2484
+ Schema.Union([
2485
+ Schema.Struct({
2486
+ ...ExpectedPaymentCommonSchema.fields,
2487
+ operation: Schema.Literal("send"),
2488
+ paymentSenderSafe: SafeAddressSchema,
2489
+ itemIndex: nonNegativeInteger("itemIndex"),
2490
+ settlementId: SettlementIdSchema,
2491
+ purposeKind: PaymentPurposeKindSchema,
2492
+ kind: Uint16Schema,
2493
+ documentHash: NonzeroDocumentHashSchema,
2494
+ tokenAddress: AddressSchema$1,
2495
+ recipient: AddressSchema$1,
2496
+ rawAmount: WeiAmountSchema$1
2497
+ }),
2498
+ Schema.Struct({
2499
+ ...ExpectedPaymentCommonSchema.fields,
2500
+ operation: Schema.Literal("create_commitment"),
2501
+ paymentSenderSafe: SafeAddressSchema,
2502
+ settlementId: SettlementIdSchema,
2503
+ purposeKind: PaymentPurposeKindSchema,
2504
+ kind: Uint16Schema,
2505
+ documentHash: NonzeroDocumentHashSchema,
2506
+ tokenAddress: AddressSchema$1,
2507
+ recipient: AddressSchema$1,
2508
+ totalAmount: WeiAmountSchema$1,
2509
+ startTime: Uint48Schema,
2510
+ cliffTime: Uint48Schema,
2511
+ endTime: Uint48Schema
2512
+ }),
2513
+ Schema.Struct({
2514
+ ...ExpectedPaymentCommonSchema.fields,
2515
+ operation: Schema.Literal("claim_commitment"),
2516
+ commitmentId: Uint256StringSchema,
2517
+ settlementId: SettlementIdSchema,
2518
+ documentHash: NonzeroDocumentHashSchema,
2519
+ tokenAddress: AddressSchema$1,
2520
+ creator: AddressSchema$1,
2521
+ currentRecipient: AddressSchema$1,
2522
+ totalAmount: WeiAmountSchema$1,
2523
+ claimedBefore: WeiAmountSchema$1
2524
+ }),
2525
+ Schema.Struct({
2526
+ ...ExpectedPaymentCommonSchema.fields,
2527
+ operation: Schema.Literal("cancel_commitment"),
2528
+ commitmentId: Uint256StringSchema,
2529
+ settlementId: SettlementIdSchema,
2530
+ documentHash: NonzeroDocumentHashSchema,
2531
+ tokenAddress: AddressSchema$1,
2532
+ creator: AddressSchema$1,
2533
+ currentRecipient: AddressSchema$1,
2534
+ totalAmount: WeiAmountSchema$1,
2535
+ claimedBefore: WeiAmountSchema$1
2536
+ }),
2537
+ Schema.Struct({
2538
+ ...ExpectedPaymentCommonSchema.fields,
2539
+ operation: Schema.Literal("redirect_commitment"),
2540
+ commitmentId: Uint256StringSchema,
2541
+ settlementId: SettlementIdSchema,
2542
+ documentHash: NonzeroDocumentHashSchema,
2543
+ creator: AddressSchema$1,
2544
+ currentRecipient: AddressSchema$1,
2545
+ newRecipient: AddressSchema$1,
2546
+ claimedBefore: Schema.Literal("0")
2547
+ })
2548
+ ]);
2549
+ const PaymentVerificationMismatchCodeSchema = Schema.Literals([
2550
+ "wrong_chain",
2551
+ "wrong_sender",
2552
+ "failed_user_operation",
2553
+ "wrong_transaction",
2554
+ "failed_transaction",
2555
+ "non_canonical_block",
2556
+ "wrong_contract_identity",
2557
+ "missing_event",
2558
+ "wrong_commitment_id",
2559
+ "wrong_settlement_id",
2560
+ "wrong_event_sender",
2561
+ "wrong_event_recipient",
2562
+ "wrong_event_token",
2563
+ "wrong_event_amount",
2564
+ "wrong_kind",
2565
+ "zero_document_hash",
2566
+ "wrong_document_hash",
2567
+ "missing_bound_transfer",
2568
+ "wrong_token",
2569
+ "wrong_source",
2570
+ "wrong_destination",
2571
+ "wrong_amount"
2572
+ ]);
2573
+ const FinalizedTransferRangeSchema = Schema.Struct({
2574
+ chainId: BaseSepoliaChainIdSchema,
2575
+ tokenAddress: AddressSchema$1,
2576
+ fromBlock: BlockNumberSchema$1,
2577
+ toBlock: BlockNumberSchema$1
2578
+ }).pipe(Schema.refine((range) => range.toBlock >= range.fromBlock && range.toBlock - range.fromBlock < 1e4, { message: "toBlock must be at or after fromBlock and the range must contain fewer than 10,000 block intervals" }));
2579
+ const FinalizedTransferEvidenceSchema = Schema.Struct({
2580
+ ...MovementIdentitySchema.fields,
2581
+ blockNumber: BlockNumberSchema$1,
2582
+ blockHash: Bytes32Schema,
2583
+ source: AddressSchema$1,
2584
+ destination: AddressSchema$1,
2585
+ rawAmount: WeiAmountSchema$1,
2586
+ removed: Schema.Boolean
2587
+ });
2588
+ const FinalizedBlockReferenceSchema = Schema.Struct({
2589
+ chainId: BaseSepoliaChainIdSchema,
2590
+ blockNumber: BlockNumberSchema$1,
2591
+ blockHash: Bytes32Schema
2592
+ });
2593
+ Schema.Struct({
2594
+ range: FinalizedTransferRangeSchema,
2595
+ finalizedHead: FinalizedBlockReferenceSchema,
2596
+ anchor: FinalizedBlockReferenceSchema,
2597
+ transfers: Schema.Array(FinalizedTransferEvidenceSchema),
2598
+ requestCount: nonNegativeInteger("requestCount")
2599
+ });
2600
+ const FinalizedPermissionFactRangeSchema = Schema.Struct({
2601
+ chainId: BaseSepoliaChainIdSchema,
2602
+ organizationSafe: SafeAddressSchema,
2603
+ rolesModules: Schema.Array(ModuleAddressSchema),
2604
+ fromBlock: BlockNumberSchema$1,
2605
+ toBlock: BlockNumberSchema$1
2606
+ }).pipe(Schema.refine((range) => range.toBlock >= range.fromBlock && range.toBlock - range.fromBlock < 1e4, { message: "toBlock must be at or after fromBlock and the range must contain fewer than 10,000 block intervals" }));
2607
+ const FinalizedPermissionFactCommonSchema = Schema.Struct({
2608
+ chainId: BaseSepoliaChainIdSchema,
2609
+ transactionHash: TxHashSchema$1,
2610
+ blockNumber: BlockNumberSchema$1,
2611
+ blockHash: Bytes32Schema,
2612
+ logIndex: LogIndexSchema,
2613
+ emitter: AddressSchema$1,
2614
+ topic0: Bytes32Schema,
2615
+ dataHash: Bytes32Schema,
2616
+ authorityHash: Bytes32Schema
2617
+ });
2618
+ const FinalizedPermissionModuleFactSchema = Schema.Struct({
2619
+ ...FinalizedPermissionFactCommonSchema.fields,
2620
+ kind: Schema.Literals(["module_enabled", "module_disabled"]),
2621
+ organizationSafe: SafeAddressSchema,
2622
+ module: ModuleAddressSchema
2623
+ });
2624
+ const FinalizedPermissionRoleAssignmentFactSchema = Schema.Struct({
2625
+ ...FinalizedPermissionFactCommonSchema.fields,
2626
+ kind: Schema.Literal("assignment"),
2627
+ rolesModule: ModuleAddressSchema,
2628
+ memberSafe: SafeAddressSchema,
2629
+ roleKeys: Schema.Array(RoleKeySchema),
2630
+ memberOf: Schema.Array(Schema.Boolean)
2631
+ });
2632
+ const FinalizedPermissionTargetAuthorityFactSchema = Schema.Union([Schema.Struct({
2633
+ ...FinalizedPermissionFactCommonSchema.fields,
2634
+ kind: Schema.Literal("allow_target"),
2635
+ rolesModule: ModuleAddressSchema,
2636
+ roleKey: RoleKeySchema,
2637
+ target: AddressSchema$1,
2638
+ options: Uint8Schema
2639
+ }), Schema.Struct({
2640
+ ...FinalizedPermissionFactCommonSchema.fields,
2641
+ kind: Schema.Literals(["scope_target", "revoke_target"]),
2642
+ rolesModule: ModuleAddressSchema,
2643
+ roleKey: RoleKeySchema,
2644
+ target: AddressSchema$1
2645
+ })]);
2646
+ const PermissionScopeConditionSchema = Schema.Struct({
2647
+ parent: Uint8Schema,
2648
+ paramType: Uint8Schema,
2649
+ operator: Uint8Schema,
2650
+ compValue: HexDataSchema
2651
+ });
2652
+ const FinalizedPermissionFunctionAuthorityFactSchema = Schema.Union([
2653
+ Schema.Struct({
2654
+ ...FinalizedPermissionFactCommonSchema.fields,
2655
+ kind: Schema.Literal("allow_function"),
2656
+ rolesModule: ModuleAddressSchema,
2657
+ roleKey: RoleKeySchema,
2658
+ target: AddressSchema$1,
2659
+ selector: Bytes4Schema,
2660
+ options: Uint8Schema
2661
+ }),
2662
+ Schema.Struct({
2663
+ ...FinalizedPermissionFactCommonSchema.fields,
2664
+ kind: Schema.Literal("scope_function"),
2665
+ rolesModule: ModuleAddressSchema,
2666
+ roleKey: RoleKeySchema,
2667
+ target: AddressSchema$1,
2668
+ selector: Bytes4Schema,
2669
+ options: Uint8Schema,
2670
+ conditions: Schema.Array(PermissionScopeConditionSchema)
2671
+ }),
2672
+ Schema.Struct({
2673
+ ...FinalizedPermissionFactCommonSchema.fields,
2674
+ kind: Schema.Literal("revoke_function"),
2675
+ rolesModule: ModuleAddressSchema,
2676
+ roleKey: RoleKeySchema,
2677
+ target: AddressSchema$1,
2678
+ selector: Bytes4Schema
2679
+ })
2680
+ ]);
2681
+ const FinalizedPermissionAllowanceAuthorityFactSchema = Schema.Struct({
2682
+ ...FinalizedPermissionFactCommonSchema.fields,
2683
+ kind: Schema.Literal("allowance"),
2684
+ rolesModule: ModuleAddressSchema,
2685
+ allowanceKey: AllowanceKeySchema,
2686
+ balance: WeiAmountSchema$1,
2687
+ maxRefill: WeiAmountSchema$1,
2688
+ refill: WeiAmountSchema$1,
2689
+ period: Uint256StringSchema,
2690
+ timestamp: Uint256StringSchema
2691
+ });
2692
+ const FinalizedPermissionFactSchema = Schema.Union([
2693
+ FinalizedPermissionModuleFactSchema,
2694
+ FinalizedPermissionRoleAssignmentFactSchema,
2695
+ FinalizedPermissionTargetAuthorityFactSchema,
2696
+ FinalizedPermissionFunctionAuthorityFactSchema,
2697
+ FinalizedPermissionAllowanceAuthorityFactSchema
2698
+ ]);
2699
+ Schema.Struct({
2700
+ range: FinalizedPermissionFactRangeSchema,
2701
+ finalizedHead: FinalizedBlockReferenceSchema,
2702
+ anchor: FinalizedBlockReferenceSchema,
2703
+ facts: Schema.Array(FinalizedPermissionFactSchema),
2704
+ requestCount: nonNegativeInteger("requestCount")
2705
+ });
2706
+ const FinalizedMoneyEvidenceCommonSchema = Schema.Struct({
2707
+ chainId: BaseSepoliaChainIdSchema,
2708
+ contractAddress: AddressSchema$1,
2709
+ userOpHash: Bytes32Schema,
2710
+ txHash: TxHashSchema$1,
2711
+ blockNumber: BlockNumberSchema$1,
2712
+ blockHash: Bytes32Schema,
2713
+ blockTimestamp: Uint48Schema,
2714
+ eventLogIndex: LogIndexSchema
2715
+ });
2716
+ const FinalizedPaymentEvidenceSchema = Schema.Struct({
2717
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
2718
+ operation: Schema.Literal("send"),
2719
+ settlementId: SettlementIdSchema,
2720
+ purposeKind: PaymentPurposeKindSchema,
2721
+ kind: Uint16Schema,
2722
+ documentHash: NonzeroDocumentHashSchema,
2723
+ tokenAddress: AddressSchema$1,
2724
+ transferLogIndex: LogIndexSchema,
2725
+ source: AddressSchema$1,
2726
+ destination: AddressSchema$1,
2727
+ rawAmount: WeiAmountSchema$1
2728
+ });
2729
+ const FinalizedCommitmentCreationEvidenceSchema = Schema.Struct({
2730
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
2731
+ operation: Schema.Literal("create_commitment"),
2732
+ commitmentId: Uint256StringSchema,
2733
+ settlementId: SettlementIdSchema,
2734
+ creator: AddressSchema$1,
2735
+ recipient: AddressSchema$1,
2736
+ tokenAddress: AddressSchema$1,
2737
+ totalAmount: WeiAmountSchema$1,
2738
+ startTime: Uint48Schema,
2739
+ cliffTime: Uint48Schema,
2740
+ endTime: Uint48Schema,
2741
+ kind: Uint16Schema,
2742
+ purposeKind: PaymentPurposeKindSchema,
2743
+ documentHash: NonzeroDocumentHashSchema,
2744
+ transferLogIndex: LogIndexSchema
2745
+ });
2746
+ const FinalizedCommitmentClaimEvidenceSchema = Schema.Struct({
2747
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
2748
+ operation: Schema.Literal("claim_commitment"),
2749
+ commitmentId: Uint256StringSchema,
2750
+ settlementId: SettlementIdSchema,
2751
+ creator: AddressSchema$1,
2752
+ recipient: AddressSchema$1,
2753
+ tokenAddress: AddressSchema$1,
2754
+ totalAmount: WeiAmountSchema$1,
2755
+ claimedBefore: WeiAmountSchema$1,
2756
+ rawAmount: WeiAmountSchema$1,
2757
+ documentHash: NonzeroDocumentHashSchema,
2758
+ transferLogIndex: LogIndexSchema
2759
+ });
2760
+ const FinalizedCommitmentCancelEvidenceSchema = Schema.Struct({
2761
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
2762
+ operation: Schema.Literal("cancel_commitment"),
2763
+ commitmentId: Uint256StringSchema,
2764
+ settlementId: SettlementIdSchema,
2765
+ creator: AddressSchema$1,
2766
+ currentRecipient: AddressSchema$1,
2767
+ tokenAddress: AddressSchema$1,
2768
+ totalAmount: WeiAmountSchema$1,
2769
+ claimedBefore: WeiAmountSchema$1,
2770
+ vestedUnclaimed: WeiAmountSchema$1,
2771
+ unvestedReturned: WeiAmountSchema$1,
2772
+ documentHash: NonzeroDocumentHashSchema,
2773
+ transfer: Schema.NullOr(FinalizedTransferEvidenceSchema)
2774
+ });
2775
+ const FinalizedCommitmentRedirectEvidenceSchema = Schema.Struct({
2776
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
2777
+ operation: Schema.Literal("redirect_commitment"),
2778
+ commitmentId: Uint256StringSchema,
2779
+ settlementId: SettlementIdSchema,
2780
+ creator: AddressSchema$1,
2781
+ oldRecipient: AddressSchema$1,
2782
+ newRecipient: AddressSchema$1,
2783
+ claimedBefore: Schema.Literal("0"),
2784
+ documentHash: NonzeroDocumentHashSchema,
2785
+ transfer: Schema.Null
2786
+ });
2787
+ const FinalizedMoneyEvidenceSchema = Schema.Union([
2788
+ FinalizedPaymentEvidenceSchema,
2789
+ FinalizedCommitmentCreationEvidenceSchema,
2790
+ FinalizedCommitmentClaimEvidenceSchema,
2791
+ FinalizedCommitmentCancelEvidenceSchema,
2792
+ FinalizedCommitmentRedirectEvidenceSchema
2793
+ ]);
2794
+ Schema.Union([
2795
+ Schema.Struct({
2796
+ status: Schema.Literal("pending"),
2797
+ reason: Schema.Literals(["receipt_missing", "not_finalized"]),
2798
+ receipt: Schema.optional(ReceiptRefSchema)
2799
+ }),
2800
+ Schema.Struct({
2801
+ status: Schema.Literal("verified"),
2802
+ evidence: FinalizedMoneyEvidenceSchema
2803
+ }),
2804
+ Schema.Struct({
2805
+ status: Schema.Literal("mismatch"),
2806
+ code: PaymentVerificationMismatchCodeSchema,
2807
+ receipt: Schema.optional(ReceiptRefSchema)
2808
+ }),
2809
+ Schema.Struct({
2810
+ status: Schema.Literal("provider_failure"),
2811
+ retryable: Schema.Literal(true)
2812
+ })
2813
+ ]);
2814
+ const FinalizedAttributedInboundMovementSchema = Schema.Struct({
2815
+ movement: MovementSchema,
2816
+ attribution: MovementAttributionSchema
2817
+ });
2818
+ const PaymentCommandLineageSchema = Schema.Union([Schema.Struct({
2819
+ kind: Schema.Literal("payroll"),
2820
+ runId: nonEmpty("runId")
2821
+ }), Schema.Struct({
2822
+ kind: Schema.Literal("payment_request"),
2823
+ requestId: nonEmpty("requestId")
2824
+ })]);
2825
+ const ProtocolBirthInputSchema = Schema.Struct({
2826
+ requestKey: nonEmpty("requestKey"),
2827
+ actor: ActorRefSchema,
2828
+ recipient: ActorOrDestinationRefSchema,
2829
+ recipientSafe: SafeAddressSchema,
2830
+ paymentSenderSafe: SafeAddressSchema,
2831
+ amount: FinancialOpsMoney,
2832
+ ledgerKind: Schema.Literals(["Payment", "Payout"]),
2833
+ purposeKind: PaymentPurposeKindSchema,
2834
+ permissionId: Schema.optional(PermissionIdSchema),
2835
+ settlementId: SettlementIdSchema,
2836
+ documentHash: NonzeroDocumentHashSchema,
2837
+ release: ReleaseTermsSchema,
2838
+ lineage: Schema.optional(PaymentCommandLineageSchema)
2839
+ }).pipe(Schema.refine((birth) => hasActorBoundPermission(birth.actor, birth.actor.kind === "organization" ? birth.actor.orgId : void 0, birth.permissionId), { message: "Organization Payment and Payout births require permissionId; personal births forbid it" }));
2840
+ Schema.Union([
2841
+ Schema.Struct({
2842
+ kind: Schema.Literal("birth"),
2843
+ birth: ProtocolBirthInputSchema
2844
+ }),
2845
+ Schema.Struct({
2846
+ kind: Schema.Literal("birth_deposit"),
2847
+ movement: FinalizedAttributedInboundMovementSchema
2848
+ }),
2849
+ Schema.Struct({
2850
+ kind: Schema.Literal("rollback_deposit"),
2851
+ movementId: MovementIdSchema
2852
+ }),
2853
+ Schema.Struct({
2854
+ kind: Schema.Literal("record_submission"),
2855
+ commandId: PaymentCommandIdSchema,
2856
+ paymentIds: Schema.Array(PaymentIdSchema),
2857
+ userOpHash: Bytes32Schema
2858
+ }),
2859
+ Schema.Struct({
2860
+ kind: Schema.Literal("apply_finalized_evidence"),
2861
+ paymentId: PaymentIdSchema,
2862
+ evidence: FinalizedMoneyEvidenceSchema
2863
+ }),
2864
+ Schema.Struct({
2865
+ kind: Schema.Literal("transition"),
2866
+ paymentId: PaymentIdSchema,
2867
+ event: PaymentTransitionEventSchema
2868
+ })
2869
+ ]);
2870
+ Schema.Union([
2871
+ Schema.Struct({
2872
+ outcome: Schema.Literal("created"),
2873
+ payments: Schema.Array(PaymentLedgerRecordSchema)
2874
+ }),
2875
+ Schema.Struct({
2876
+ outcome: Schema.Literal("changed"),
2877
+ payment: PaymentLedgerRecordSchema
2878
+ }),
2879
+ Schema.Struct({
2880
+ outcome: Schema.Literal("replayed"),
2881
+ payment: PaymentLedgerRecordSchema
2882
+ }),
2883
+ Schema.Struct({
2884
+ outcome: Schema.Literal("removed"),
2885
+ paymentId: PaymentIdSchema,
2886
+ movementId: MovementIdSchema
2887
+ }),
2888
+ Schema.Struct({
2889
+ outcome: Schema.Literal("refused"),
2890
+ error: PaymentCoreErrorSchema
2891
+ })
2892
+ ]);
2893
+ const PaymentBirthItemSchema = Schema.Union([Schema.Struct({
2894
+ operation: Schema.Literal("send"),
2895
+ recipient: ActorOrDestinationRefSchema,
2896
+ amount: FinancialOpsMoney,
2897
+ purposeKind: PaymentPurposeKindSchema,
2898
+ documentHash: Schema.optional(NonzeroDocumentHashSchema)
2899
+ }), Schema.Struct({
2900
+ operation: Schema.Literal("create_commitment"),
2901
+ recipient: ActorOrDestinationRefSchema,
2902
+ amount: FinancialOpsMoney,
2903
+ release: ReleaseTermsSchema.pipe(Schema.refine((release) => release.kind === "scheduled" || release.kind === "stream", { message: "Commitment release must be scheduled or stream" })),
2904
+ purposeKind: PaymentPurposeKindSchema,
2905
+ documentHash: Schema.optional(NonzeroDocumentHashSchema)
2906
+ })]);
2907
+ const PaymentBirthCommandSchema = Schema.Struct({
2908
+ kind: Schema.Literal("birth"),
2909
+ requestKey: nonEmpty("requestKey"),
2910
+ actor: ActorRefSchema,
2911
+ orgId: Schema.optional(nonEmpty("orgId")),
2912
+ permissionId: Schema.optional(PermissionIdSchema),
2913
+ lineage: Schema.optional(PaymentCommandLineageSchema),
2914
+ items: Schema.Array(PaymentBirthItemSchema)
2915
+ }).pipe(Schema.refine((command) => hasActorBoundPermission(command.actor, command.orgId, command.permissionId), { message: "Organization Payment commands require matching orgId and permissionId; personal commands forbid both" }));
2916
+ Schema.Union([
2917
+ PaymentBirthCommandSchema,
2918
+ Schema.Struct({
2919
+ kind: Schema.Literal("claim_commitment"),
2920
+ actor: AccountActorRefSchema,
2921
+ paymentId: PaymentIdSchema
2922
+ }),
2923
+ Schema.Struct({
2924
+ kind: Schema.Literal("cancel_commitment"),
2925
+ actor: ActorRefSchema,
2926
+ paymentId: PaymentIdSchema
2927
+ }),
2928
+ Schema.Struct({
2929
+ kind: Schema.Literal("redirect_commitment"),
2930
+ actor: ActorRefSchema,
2931
+ paymentId: PaymentIdSchema,
2932
+ recipient: ActorOrDestinationRefSchema
2933
+ })
2934
+ ]);
2935
+ const PaymentExecutionRouteSchema = Schema.Union([Schema.Struct({
2936
+ kind: Schema.Literal("direct"),
2937
+ userOpSenderSafe: SafeAddressSchema
2938
+ }), Schema.Struct({
2939
+ kind: Schema.Literal("zodiac_role"),
2940
+ userOpSenderSafe: SafeAddressSchema,
2941
+ organizationSafe: SafeAddressSchema,
2942
+ rolesModule: ModuleAddressSchema,
2943
+ roleKey: RoleKeySchema
2944
+ })]);
2945
+ const PreparedMoneyItemSchema = Schema.Union([
2946
+ Schema.Struct({
2947
+ operation: Schema.Literal("send"),
2948
+ paymentId: PaymentIdSchema,
2949
+ settlementId: SettlementIdSchema,
2950
+ recipientSafe: SafeAddressSchema,
2951
+ tokenAddress: AddressSchema$1,
2952
+ rawAmount: WeiAmountSchema$1,
2953
+ kind: Uint16Schema,
2954
+ documentHash: NonzeroDocumentHashSchema
2955
+ }),
2956
+ Schema.Struct({
2957
+ operation: Schema.Literal("create_commitment"),
2958
+ paymentId: PaymentIdSchema,
2959
+ settlementId: SettlementIdSchema,
2960
+ recipientSafe: SafeAddressSchema,
2961
+ tokenAddress: AddressSchema$1,
2962
+ totalAmount: WeiAmountSchema$1,
2963
+ startTime: Uint48Schema,
2964
+ cliffTime: Uint48Schema,
2965
+ endTime: Uint48Schema,
2966
+ kind: Uint16Schema,
2967
+ documentHash: NonzeroDocumentHashSchema
2968
+ }),
2969
+ Schema.Struct({
2970
+ operation: Schema.Literal("claim_commitment"),
2971
+ paymentId: PaymentIdSchema,
2972
+ commitmentId: Uint256StringSchema
2973
+ }),
2974
+ Schema.Struct({
2975
+ operation: Schema.Literal("cancel_commitment"),
2976
+ paymentId: PaymentIdSchema,
2977
+ commitmentId: Uint256StringSchema,
2978
+ documentHash: NonzeroDocumentHashSchema
2979
+ }),
2980
+ Schema.Struct({
2981
+ operation: Schema.Literal("redirect_commitment"),
2982
+ paymentId: PaymentIdSchema,
2983
+ commitmentId: Uint256StringSchema,
2984
+ recipientSafe: SafeAddressSchema,
2985
+ documentHash: NonzeroDocumentHashSchema
2986
+ })
2987
+ ]);
2988
+ Schema.Struct({
2989
+ commandId: PaymentCommandIdSchema,
2990
+ chainId: ChainIdSchema$1,
2991
+ contractAddress: AddressSchema$1,
2992
+ senderSafe: SafeAddressSchema,
2993
+ executionRoute: PaymentExecutionRouteSchema,
2994
+ items: Schema.Array(PreparedMoneyItemSchema)
2995
+ });
2996
+ Schema.Struct({
2997
+ commandId: PaymentCommandIdSchema,
2998
+ paymentIds: Schema.Array(PaymentIdSchema),
2999
+ userOpHash: Bytes32Schema
3000
+ });
3001
+ const MoneyExecutionIdSchema = Schema.String.pipe(Schema.refine((value) => /^money_execution_[0-9a-f]{64}$/u.test(value), { message: "executionId must be a money_execution_ identifier" }));
3002
+ const OwnerSignatureSchema = Schema.String.pipe(Schema.refine((value) => /^0x[0-9a-fA-F]{130}$/u.test(value), { message: "signature must be a 65-byte 0x value" }));
3003
+ const PaymentExecutionIntentSchema = Schema.Struct({
3004
+ to: PaymentRef,
3005
+ amount: FinancialOpsMoney,
3006
+ paymentType: Schema.optional(Schema.Literals([
3007
+ "unspecified",
3008
+ "invoice",
3009
+ "payroll",
3010
+ "reimbursement"
3011
+ ])),
3012
+ document: Schema.optional(AttachablePaymentDocumentEnvelope),
3013
+ timing: Schema.optional(PaymentTiming),
3014
+ lineItems: Schema.optional(Schema.Array(LineItem))
3015
+ });
3016
+ Schema.Struct({
3017
+ requestKey: nonEmpty("requestKey"),
3018
+ signerAddress: AddressSchema$1,
3019
+ payment: PaymentExecutionIntentSchema
3020
+ });
3021
+ Schema.Struct({
3022
+ executionId: MoneyExecutionIdSchema,
3023
+ commandId: PaymentCommandIdSchema,
3024
+ paymentId: PaymentIdSchema,
3025
+ requestKey: nonEmpty("requestKey"),
3026
+ payment: PaymentExecutionIntentSchema,
3027
+ purposeKind: PaymentPurposeKindSchema,
3028
+ emitPaymentInitiated: Schema.Boolean,
3029
+ chainId: BaseSepoliaChainIdSchema,
3030
+ signerAddress: AddressSchema$1,
3031
+ userOpSenderSafe: SafeAddressSchema,
3032
+ digest: Bytes32Schema
3033
+ });
3034
+ Schema.Struct({
3035
+ executionId: MoneyExecutionIdSchema,
3036
+ signature: OwnerSignatureSchema
3037
+ });
3038
+ Schema.Struct({
3039
+ executionId: MoneyExecutionIdSchema,
3040
+ commandId: PaymentCommandIdSchema,
3041
+ userOpHash: Bytes32Schema,
3042
+ payment: Payment
3043
+ });
3044
+ Schema.Struct({
3045
+ executionId: MoneyExecutionIdSchema,
3046
+ commandId: PaymentCommandIdSchema,
3047
+ userOpHash: Bytes32Schema,
3048
+ payments: Schema.Array(Payment)
3049
+ });
3050
+ const PaymentLifecycleExecutionIntentSchema = Schema.Union([
3051
+ Schema.Struct({
3052
+ kind: Schema.Literal("claim"),
3053
+ paymentId: PaymentIdSchema
3054
+ }),
3055
+ Schema.Struct({
3056
+ kind: Schema.Literal("cancel"),
3057
+ paymentId: PaymentIdSchema
3058
+ }),
3059
+ Schema.Struct({
3060
+ kind: Schema.Literal("redirect"),
3061
+ paymentId: PaymentIdSchema,
3062
+ recipient: PaymentRef
3063
+ })
3064
+ ]);
3065
+ Schema.Struct({
3066
+ signerAddress: AddressSchema$1,
3067
+ intent: PaymentLifecycleExecutionIntentSchema
3068
+ });
3069
+ const OrganizationPaymentExecutionItemSchema = Schema.Struct({
3070
+ to: PaymentRef,
3071
+ amount: FinancialOpsMoney,
3072
+ paymentType: Schema.optional(Schema.Literals([
3073
+ "unspecified",
3074
+ "invoice",
3075
+ "payroll",
3076
+ "reimbursement"
3077
+ ])),
3078
+ document: Schema.optional(AttachablePaymentDocumentEnvelope)
3079
+ });
3080
+ Schema.Struct({
3081
+ orgId: nonEmpty("orgId"),
3082
+ permissionId: PermissionIdSchema,
3083
+ requestKey: nonEmpty("requestKey"),
3084
+ signerAddress: AddressSchema$1,
3085
+ items: Schema.Array(OrganizationPaymentExecutionItemSchema),
3086
+ lineage: Schema.optional(PaymentCommandLineageSchema)
3087
+ });
3088
+ Schema.Struct({
3089
+ executionId: MoneyExecutionIdSchema,
3090
+ commandId: PaymentCommandIdSchema,
3091
+ paymentIds: Schema.Array(PaymentIdSchema),
3092
+ request: Schema.Union([PaymentLifecycleExecutionIntentSchema, Schema.Struct({
3093
+ orgId: nonEmpty("orgId"),
3094
+ permissionId: PermissionIdSchema,
3095
+ requestKey: nonEmpty("requestKey"),
3096
+ items: Schema.Array(OrganizationPaymentExecutionItemSchema),
3097
+ lineage: Schema.optional(PaymentCommandLineageSchema)
3098
+ })]),
3099
+ chainId: BaseSepoliaChainIdSchema,
3100
+ signerAddress: AddressSchema$1,
3101
+ userOpSenderSafe: SafeAddressSchema,
3102
+ digest: Bytes32Schema
3103
+ });
3104
+ const PermissionIntentSchema = Schema.Union([Schema.Struct({
3105
+ type: Schema.Literal("budget"),
3106
+ limit: FinancialOpsMoney
3107
+ }), Schema.Struct({ type: Schema.Literal("managePeople") })]);
3108
+ const PermissionCommandSchema = Schema.Union([
3109
+ Schema.Struct({
3110
+ operation: Schema.Literal("create"),
3111
+ requestKey: nonEmpty("requestKey"),
3112
+ intent: PermissionIntentSchema
3113
+ }),
3114
+ Schema.Struct({
3115
+ operation: Schema.Literal("change"),
3116
+ requestKey: nonEmpty("requestKey"),
3117
+ permissionId: PermissionIdSchema,
3118
+ intent: PermissionIntentSchema
3119
+ }),
3120
+ Schema.Struct({
3121
+ operation: Schema.Literal("assign"),
3122
+ requestKey: nonEmpty("requestKey"),
3123
+ permissionId: PermissionIdSchema,
3124
+ accountId: nonEmpty("accountId")
3125
+ }),
3126
+ Schema.Struct({
3127
+ operation: Schema.Literal("revoke"),
3128
+ requestKey: nonEmpty("requestKey"),
3129
+ permissionAssignmentId: PermissionAssignmentIdSchema
3130
+ }),
3131
+ Schema.Struct({
3132
+ operation: Schema.Literal("replace"),
3133
+ requestKey: nonEmpty("requestKey")
3134
+ })
3135
+ ]);
3136
+ const PermissionChainCallSchema = Schema.Struct({
3137
+ to: AddressSchema$1,
3138
+ value: Schema.Literal("0"),
3139
+ data: HexDataSchema
3140
+ });
3141
+ const PermissionResourceSchema = Schema.Union([
3142
+ PermissionSchema,
3143
+ PermissionAssignmentSchema,
3144
+ Schema.Array(PermissionSchema)
3145
+ ]);
3146
+ Schema.Struct({
3147
+ status: Schema.Literal("prepared"),
3148
+ commandId: PaymentCommandIdSchema,
3149
+ operation: PermissionOperationSchema,
3150
+ expectedRevision: nonNegativeInteger("expectedRevision"),
3151
+ userOpSenderSafe: SafeAddressSchema,
3152
+ organizationSafe: SafeAddressSchema,
3153
+ calls: Schema.Array(PermissionChainCallSchema),
3154
+ value: PermissionResourceSchema
3155
+ });
3156
+ Schema.Struct({
3157
+ orgId: nonEmpty("orgId"),
3158
+ signerAddress: AddressSchema$1,
3159
+ command: PermissionCommandSchema
3160
+ });
3161
+ Schema.Struct({
3162
+ executionId: MoneyExecutionIdSchema,
3163
+ commandId: PaymentCommandIdSchema,
3164
+ operation: PermissionOperationSchema,
3165
+ orgId: nonEmpty("orgId"),
3166
+ command: PermissionCommandSchema,
3167
+ expectedRevision: nonNegativeInteger("expectedRevision"),
3168
+ chainId: BaseSepoliaChainIdSchema,
3169
+ signerAddress: AddressSchema$1,
3170
+ userOpSenderSafe: SafeAddressSchema,
3171
+ digest: Bytes32Schema,
3172
+ value: PermissionResourceSchema
3173
+ });
3174
+ Schema.Struct({
3175
+ status: Schema.Literal("submitted"),
3176
+ executionId: MoneyExecutionIdSchema,
3177
+ commandId: PaymentCommandIdSchema,
3178
+ userOpHash: Bytes32Schema,
3179
+ value: PermissionResourceSchema
3180
+ });
3181
+ `
3182
+ .capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;
3183
+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;
3184
+ color:var(--ink);background:var(--bg);max-width:44rem;margin:0 auto;padding:2.75rem 3rem;
3185
+ border:1px solid var(--line);border-radius:16px;box-shadow:0 1px 2px rgba(0,0,0,.04),0 12px 32px rgba(0,0,0,.06);
3186
+ line-height:1.5;font-size:15px;overflow-wrap:anywhere;word-break:break-word}
3187
+ .capxul-doc *{box-sizing:border-box;min-width:0}
3188
+ .capxul-doc .doc-header{display:flex;flex-direction:column;gap:1.25rem;padding-bottom:1.5rem;border-bottom:1px solid var(--line);margin-bottom:1.75rem}
3189
+ .capxul-doc .doc-brand{display:flex;align-items:center;gap:.5rem;color:var(--accent);font-weight:600}
3190
+ .capxul-doc .doc-brand-mark{font-size:1.1rem}
3191
+ .capxul-doc .doc-brand-name{letter-spacing:.02em}
3192
+ .capxul-doc .doc-headline{display:flex;align-items:baseline;justify-content:space-between;gap:1rem;flex-wrap:wrap}
3193
+ .capxul-doc .doc-title{font-size:1.9rem;font-weight:700;letter-spacing:-.02em;margin:0}
3194
+ .capxul-doc .doc-badge{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;
3195
+ color:var(--accent);background:rgba(10,125,75,.1);padding:.3rem .6rem;border-radius:999px;max-width:100%;text-align:right}
3196
+ .capxul-doc .doc-parties{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;margin-bottom:1.75rem}
3197
+ .capxul-doc .doc-party{display:flex;flex-direction:column;gap:.15rem}
3198
+ .capxul-doc .doc-party-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
3199
+ .capxul-doc .doc-party-name{font-weight:600}
3200
+ .capxul-doc .doc-meta{display:flex;flex-direction:column;gap:.4rem;margin-bottom:1.75rem}
3201
+ .capxul-doc .doc-meta-row{display:flex;justify-content:space-between;gap:1rem;font-size:.92rem}
3202
+ .capxul-doc .doc-meta-label{color:var(--muted);flex-shrink:0}
3203
+ .capxul-doc .doc-meta-value{font-weight:500;text-align:right}
3204
+ .capxul-doc time{color:var(--ink);font-variant-numeric:tabular-nums}
3205
+ .capxul-doc .doc-line-items{width:100%;border-collapse:collapse;margin:.5rem 0 1.5rem;font-size:.92rem}
3206
+ .capxul-doc .doc-line-items th{text-align:left;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;
3207
+ color:var(--muted);font-weight:600;padding:.5rem .25rem;border-bottom:1px solid var(--line)}
3208
+ .capxul-doc .doc-line-items td{padding:.7rem .25rem;border-bottom:1px solid var(--line)}
3209
+ .capxul-doc .doc-li-qty,.capxul-doc .doc-li-unit,.capxul-doc .doc-li-total{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
3210
+ .capxul-doc .doc-li-desc{width:100%}
3211
+ .capxul-doc .doc-totals{display:flex;flex-direction:column;gap:.5rem;margin-top:.5rem}
3212
+ .capxul-doc .doc-total-line{display:flex;justify-content:space-between;align-items:baseline;gap:1rem}
3213
+ .capxul-doc .doc-total-label{color:var(--muted)}
3214
+ .capxul-doc .doc-total-deduction .doc-amount-value{color:var(--muted)}
3215
+ .capxul-doc .doc-total-grand{border-top:2px solid var(--ink);margin-top:.5rem;padding-top:.75rem;font-size:1.15rem}
3216
+ .capxul-doc .doc-total-grand .doc-amount-value{font-weight:700}
3217
+ .capxul-doc .doc-amount-value{font-variant-numeric:tabular-nums;font-weight:600}
3218
+ .capxul-doc .doc-hero{text-align:center;padding:1.5rem 0 2rem}
3219
+ .capxul-doc .doc-hero-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
3220
+ .capxul-doc .doc-hero-amount{font-size:2.6rem;font-weight:700;letter-spacing:-.02em;margin-top:.35rem}
3221
+ .capxul-doc .doc-note{color:var(--ink);background:#f7f7f8;border-radius:10px;padding:.9rem 1.1rem;margin:0}
3222
+ .capxul-doc .doc-dest-address{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9rem}
3223
+ .capxul-doc .doc-footer{margin-top:1.75rem;padding-top:1.25rem;border-top:1px solid var(--line);color:var(--muted);font-size:.9rem}
3224
+ .capxul-doc code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.82rem;color:var(--muted);word-break:break-all}
3225
+ @media (max-width:540px){.capxul-doc{padding:1.75rem 1.25rem}.capxul-doc .doc-parties{grid-template-columns:1fr}}
3226
+ `.trim();
3227
+ //#endregion
3228
+ //#region ../wire/src/secret-material.ts
3229
+ const SENSITIVE_MATERIAL_PATTERNS = [
3230
+ /0x[a-fA-F0-9]{40,}/u,
3231
+ /(?:^|[^a-fA-F0-9])[a-fA-F0-9]{64}(?:$|[^a-fA-F0-9])/u,
3232
+ /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/u,
3233
+ /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/iu
3234
+ ];
3235
+ /**
3236
+ * Reject: does the value carry any known secret material? Best effort — callers
3237
+ * drop the whole value on a match; a false negative is a leak, a false positive
3238
+ * merely omits an observation field.
3239
+ */
3240
+ function containsSensitiveMaterial(value) {
3241
+ return SENSITIVE_MATERIAL_PATTERNS.some((pattern) => pattern.test(value));
3242
+ }
3243
+ //#endregion
3244
+ //#region ../wire/src/observation-context.ts
3245
+ /** Single bounded HTTP carrier used before a Convex action envelope exists. */
3246
+ const OBSERVATION_CONTEXT_HEADER = "x-capxul-observation-context";
3247
+ const FIELD_RULES = {
3248
+ application: {
3249
+ maxLength: 64,
3250
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._-]*$/u
3251
+ },
3252
+ applicationId: {
3253
+ maxLength: 30,
3254
+ pattern: APP_ID_RE
3255
+ },
3256
+ release: {
3257
+ maxLength: 128,
3258
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._+@:/-]*$/u
3259
+ },
3260
+ sessionId: {
3261
+ maxLength: 128,
3262
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3263
+ },
3264
+ organizationId: {
3265
+ maxLength: 128,
3266
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3267
+ },
3268
+ journeyId: {
3269
+ maxLength: 128,
3270
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3271
+ },
3272
+ correlationId: {
3273
+ maxLength: 128,
3274
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3275
+ },
3276
+ anonymousId: {
3277
+ maxLength: 128,
3278
+ pattern: /^anon_[A-Za-z0-9-]+$/u
3279
+ },
3280
+ traceparent: {
3281
+ maxLength: 55,
3282
+ pattern: /^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/u
3283
+ }
3284
+ };
3285
+ /**
3286
+ * Copy only the canonical allowlist and silently omit malformed/sensitive
3287
+ * values. Observation metadata is best effort and may never reject a domain
3288
+ * operation.
3289
+ */
3290
+ function sanitizeObservationContext(input) {
3291
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
3292
+ const source = input;
3293
+ const sanitized = {};
3294
+ for (const field of Object.keys(FIELD_RULES)) {
3295
+ const value = source[field];
3296
+ if (!isSafeField(field, value)) continue;
3297
+ sanitized[field] = value;
3298
+ }
3299
+ return Object.keys(sanitized).length === 0 ? void 0 : sanitized;
3300
+ }
3301
+ /** Encode only the sanitized allowlist; absence stays absence. */
3302
+ function encodeObservationContextHeader(input) {
3303
+ const sanitized = sanitizeObservationContext(input);
3304
+ return sanitized === void 0 ? void 0 : JSON.stringify(sanitized);
3305
+ }
3306
+ function isSafeField(field, value) {
3307
+ if (typeof value !== "string") return false;
3308
+ const rule = FIELD_RULES[field];
3309
+ return value.length > 0 && value.length <= rule.maxLength && value === value.trim() && !value.includes("://") && !containsSensitiveMaterial(value) && rule.pattern.test(value);
3310
+ }
3311
+ //#endregion
3312
+ //#region src/contract/actor-scope.ts
3313
+ const actorScopeContract = {
3314
+ addressBookList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].list),
3315
+ addressBookGet: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].get),
3316
+ addressBookAdd: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].add),
3317
+ addressBookHide: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].hide),
3318
+ addressBookUnhide: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].unhide),
3319
+ addressBookLabel: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/addressBook"].label),
3320
+ requestsIssue: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].issue),
3321
+ requestsList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].list),
3322
+ requestsGet: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].get),
3323
+ requestsCancel: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].cancel),
3324
+ inboxList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].inboxList),
3325
+ inboxApprove: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].approve),
3326
+ inboxDecline: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].decline)
3327
+ };
3328
+ //#endregion
3329
+ //#region src/surface/contacts.ts
3330
+ function makeActorRelationshipMethods(deps) {
3331
+ const domain = deps.actor.kind === "account" ? "account" : "org";
3332
+ const actor = deps.actor;
3333
+ const convexCall = deps.convexCall;
3334
+ if (convexCall === void 0) return makeNotImplementedActorRelationshipMethods(deps, domain);
3335
+ const fns = actorScopeContract;
3336
+ return {
3337
+ addressBook: {
3338
+ list: (options) => mapOk$1(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
3339
+ get: async (entryId, options) => {
3340
+ const ref = refFromEntryId(entryId);
3341
+ if (!ref.ok) return ref;
3342
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
3343
+ actor,
3344
+ ref: ref.value
3345
+ })), (entry) => entry === null ? null : mapAddressBookEntry(entry));
3346
+ },
3347
+ add: async (input, options) => {
3348
+ const ref = normalizeRefForBackend$1(input.ref, "ref");
3349
+ if (!ref.ok) return ref;
3350
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
3351
+ actor,
3352
+ ref: ref.value,
3353
+ ...input.label === void 0 ? {} : { label: input.label }
3354
+ })), mapAddressBookEntry);
3355
+ },
3356
+ hide: async (entryId, options) => {
3357
+ const ref = refFromEntryId(entryId);
3358
+ if (!ref.ok) return ref;
3359
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
3360
+ actor,
3361
+ ref: ref.value
3362
+ })), mapAddressBookEntry);
3363
+ },
3364
+ unhide: async (entryId, options) => {
3365
+ const ref = refFromEntryId(entryId);
3366
+ if (!ref.ok) return ref;
3367
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
3368
+ actor,
3369
+ ref: ref.value
3370
+ })), mapAddressBookEntry);
3371
+ },
3372
+ label: async (input, options) => {
3373
+ const ref = refFromEntryId(input.entryId);
3374
+ if (!ref.ok) return ref;
3375
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
3376
+ actor,
3377
+ ref: ref.value,
3378
+ label: input.label
3379
+ })), mapAddressBookEntry);
3380
+ }
3381
+ },
3382
+ requests: {
3383
+ issue: async (input, options) => {
3384
+ const payer = normalizeRefForBackend$1(input.payer, "payer");
3385
+ if (!payer.ok) return payer;
3386
+ return mapOk$1(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
3387
+ actor,
3388
+ payer: payer.value,
3389
+ amount: input.amount,
2303
3390
  reference: input.reference,
2304
3391
  ...input.memo === void 0 ? {} : { memo: input.memo },
2305
3392
  ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
2306
3393
  })), (request) => mapActorRequest(request, input.payer));
2307
3394
  },
2308
- list: (options) => mapOk$2(awaitableConvex(options?.signal, "requests.list", () => convexCall.query(fns.requestsList, { actor })), (requests) => requests.map((request) => mapActorRequest(request))),
2309
- get: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "requests.get", () => convexCall.query(fns.requestsGet, {
3395
+ list: (options) => mapOk$1(awaitableConvex(options?.signal, "requests.list", () => convexCall.query(fns.requestsList, { actor })), (requests) => requests.map((request) => mapActorRequest(request))),
3396
+ get: (requestId, options) => mapOk$1(awaitableConvex(options?.signal, "requests.get", () => convexCall.query(fns.requestsGet, {
2310
3397
  actor,
2311
3398
  paymentRequestId: requestId
2312
3399
  })), (request) => request === null ? null : mapActorRequest(request)),
2313
- cancel: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "requests.cancel", () => convexCall.mutation(fns.requestsCancel, {
3400
+ cancel: (requestId, options) => mapOk$1(awaitableConvex(options?.signal, "requests.cancel", () => convexCall.mutation(fns.requestsCancel, {
2314
3401
  actor,
2315
3402
  paymentRequestId: requestId
2316
- })), (request) => mapActorRequest(request)),
2317
- reconcile: async (options) => {
2318
- return mapOk$2(awaitableConvex(options?.signal, "requests.reconcile", () => convexCall.query(fns.requestsReconcile, { actor })), (entries) => entries.map(mapReconciliationEntry));
2319
- }
3403
+ })), (request) => mapActorRequest(request))
2320
3404
  },
2321
3405
  inbox: {
2322
- list: (options) => mapOk$2(awaitableConvex(options?.signal, "inbox.list", () => convexCall.query(fns.inboxList, { actor })), (items) => items.map(mapInboxItem)),
2323
- approve: (input, options) => mapOk$2(awaitableConvex(options?.signal, "inbox.approve", () => convexCall.mutation(fns.inboxApprove, {
3406
+ list: (options) => mapOk$1(awaitableConvex(options?.signal, "inbox.list", () => convexCall.query(fns.inboxList, { actor })), (items) => items.map(mapInboxItem)),
3407
+ approve: (input, options) => mapOk$1(awaitableConvex(options?.signal, "inbox.approve", () => convexCall.mutation(fns.inboxApprove, {
2324
3408
  actor,
2325
3409
  paymentRequestId: input.requestId,
2326
3410
  ...input.timing === void 0 ? {} : { timing: input.timing }
2327
3411
  })), mapApprovedInboxPayment),
2328
- decline: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "inbox.decline", () => convexCall.mutation(fns.inboxDecline, {
3412
+ decline: (requestId, options) => mapOk$1(awaitableConvex(options?.signal, "inbox.decline", () => convexCall.mutation(fns.inboxDecline, {
2329
3413
  actor,
2330
3414
  paymentRequestId: requestId
2331
3415
  })), mapInboxItem)
2332
3416
  },
2333
- insights: {
2334
- summary: (options) => awaitableConvex(options?.signal, "insights.summary", () => convexCall.query(fns.insightsSummary, { actor })),
2335
- history: (options) => mapOk$2(awaitableConvex(options?.signal, "insights.history", () => convexCall.query(fns.insightsHistory, { actor })), (history) => history.transactions.map(normalizePaymentTiming$2))
2336
- },
2337
3417
  profile: {
2338
3418
  get: (options) => {
2339
3419
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
2340
- return missingConvexCall$1(`${domain}.profile.get`);
3420
+ return missingConvexCall(`${domain}.profile.get`);
2341
3421
  },
2342
3422
  depositInstructions: (options) => {
2343
3423
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
2344
- return missingConvexCall$1(`${domain}.profile.depositInstructions`);
3424
+ return missingConvexCall(`${domain}.profile.depositInstructions`);
2345
3425
  }
2346
3426
  }
2347
3427
  };
@@ -2349,37 +3429,32 @@ function makeActorRelationshipMethods(deps) {
2349
3429
  function makeNotImplementedActorRelationshipMethods(deps, domain) {
2350
3430
  return {
2351
3431
  addressBook: {
2352
- list: () => missingConvexCall$1("addressBook.list"),
2353
- get: () => missingConvexCall$1("addressBook.get"),
2354
- add: () => missingConvexCall$1("addressBook.add"),
2355
- hide: () => missingConvexCall$1("addressBook.hide"),
2356
- unhide: () => missingConvexCall$1("addressBook.unhide"),
2357
- label: () => missingConvexCall$1("addressBook.label")
3432
+ list: () => missingConvexCall("addressBook.list"),
3433
+ get: () => missingConvexCall("addressBook.get"),
3434
+ add: () => missingConvexCall("addressBook.add"),
3435
+ hide: () => missingConvexCall("addressBook.hide"),
3436
+ unhide: () => missingConvexCall("addressBook.unhide"),
3437
+ label: () => missingConvexCall("addressBook.label")
2358
3438
  },
2359
3439
  requests: {
2360
- issue: () => missingConvexCall$1("requests.issue"),
2361
- list: () => missingConvexCall$1("requests.list"),
2362
- get: () => missingConvexCall$1("requests.get"),
2363
- cancel: () => missingConvexCall$1("requests.cancel"),
2364
- reconcile: () => missingConvexCall$1("requests.reconcile")
3440
+ issue: () => missingConvexCall("requests.issue"),
3441
+ list: () => missingConvexCall("requests.list"),
3442
+ get: () => missingConvexCall("requests.get"),
3443
+ cancel: () => missingConvexCall("requests.cancel")
2365
3444
  },
2366
3445
  inbox: {
2367
- list: () => missingConvexCall$1("inbox.list"),
2368
- approve: () => missingConvexCall$1("inbox.approve"),
2369
- decline: () => missingConvexCall$1("inbox.decline")
2370
- },
2371
- insights: {
2372
- summary: () => missingConvexCall$1("insights.summary"),
2373
- history: () => missingConvexCall$1("insights.history")
3446
+ list: () => missingConvexCall("inbox.list"),
3447
+ approve: () => missingConvexCall("inbox.approve"),
3448
+ decline: () => missingConvexCall("inbox.decline")
2374
3449
  },
2375
3450
  profile: {
2376
3451
  get: (options) => {
2377
3452
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
2378
- return missingConvexCall$1(`${domain}.profile.get`);
3453
+ return missingConvexCall(`${domain}.profile.get`);
2379
3454
  },
2380
3455
  depositInstructions: (options) => {
2381
3456
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
2382
- return missingConvexCall$1(`${domain}.profile.depositInstructions`);
3457
+ return missingConvexCall(`${domain}.profile.depositInstructions`);
2383
3458
  }
2384
3459
  }
2385
3460
  };
@@ -2396,13 +3471,13 @@ async function mapAccountProfile(resultPromise) {
2396
3471
  }
2397
3472
  };
2398
3473
  }
2399
- function missingConvexCall$1(operation) {
3474
+ function missingConvexCall(operation) {
2400
3475
  return Promise.resolve({
2401
3476
  ok: false,
2402
3477
  error: Errors.providerError("convex", operation, "ConvexCallPort is required")
2403
3478
  });
2404
3479
  }
2405
- async function mapOk$2(resultOrPromise, f) {
3480
+ async function mapOk$1(resultOrPromise, f) {
2406
3481
  const result = await resultOrPromise;
2407
3482
  if (!result.ok) return result;
2408
3483
  return {
@@ -2448,17 +3523,8 @@ function mapInboxItem(item) {
2448
3523
  status: mapInboxStatus(item.status)
2449
3524
  };
2450
3525
  }
2451
- function mapReconciliationEntry(entry) {
2452
- return {
2453
- paymentRequestId: entry.paymentRequestId,
2454
- reference: entry.reference,
2455
- status: entry.status,
2456
- settledPaymentId: entry.settledPaymentId ?? null,
2457
- receiptDocumentHash: entry.receiptDocumentHash ?? null
2458
- };
2459
- }
2460
3526
  function mapApprovedInboxPayment(item) {
2461
- if (item.settledPayment !== void 0) return normalizePaymentTiming$2(item.settledPayment);
3527
+ if (item.settledPayment !== void 0) return normalizePaymentTiming$1(item.settledPayment);
2462
3528
  const zero = {
2463
3529
  ...item.amount,
2464
3530
  value: "0"
@@ -2528,7 +3594,7 @@ function mapInboxStatus(status) {
2528
3594
  default: return "open";
2529
3595
  }
2530
3596
  }
2531
- function normalizePaymentTiming$2(payment) {
3597
+ function normalizePaymentTiming$1(payment) {
2532
3598
  const { release: _release, ...rest } = payment;
2533
3599
  return {
2534
3600
  ...rest,
@@ -2879,6 +3945,9 @@ function makeAccountMethods(deps) {
2879
3945
  };
2880
3946
  }
2881
3947
  //#endregion
3948
+ //#region package.json
3949
+ var version = "2.0.0";
3950
+ //#endregion
2882
3951
  //#region src/ports/auth-client.ts
2883
3952
  var AuthClientError = class extends Data.TaggedError("AuthClientError") {};
2884
3953
  var AuthClientPortTag = class extends Context.Service()("@capxul/sdk/ports/AuthClientPort") {};
@@ -2904,11 +3973,11 @@ function fromResult(operation, run) {
2904
3973
  })
2905
3974
  }).pipe(Effect.flatMap((result) => result.ok ? Effect.succeed(result.value) : Effect.fail(new AuthClientError({
2906
3975
  operation,
2907
- kind: errorKind(result.error),
3976
+ kind: errorKind$1(result.error),
2908
3977
  cause: result.error
2909
3978
  }))));
2910
3979
  }
2911
- function errorKind(error) {
3980
+ function errorKind$1(error) {
2912
3981
  if (error.code === "CANCELLED") return "cancelled";
2913
3982
  if (error.code === "NETWORK_ERROR") return "network";
2914
3983
  if (error.code === "INVALID_INPUT" || error.code === "OTP_EXPIRED") return "validation";
@@ -2945,45 +4014,6 @@ function convexCallErrorFromCapxul(operation, error) {
2945
4014
  }
2946
4015
  var ConvexCallPortTag = class extends Context.Service()("@capxul/sdk/ports/ConvexCallPort") {};
2947
4016
  //#endregion
2948
- //#region src/internal/invocation-observation.ts
2949
- const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
2950
- const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
2951
- /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
2952
- function attachInvocationObservation(target, context) {
2953
- const snapshot = Object.freeze(context === void 0 ? {} : { context: Object.freeze({ ...context }) });
2954
- Object.defineProperty(target, INVOCATION_OBSERVATION, {
2955
- configurable: false,
2956
- enumerable: false,
2957
- value: snapshot,
2958
- writable: false
2959
- });
2960
- return target;
2961
- }
2962
- /** @internal Read the snapshot without exposing its symbol or adding a wire field. */
2963
- function readInvocationObservation(source) {
2964
- if (typeof source !== "object" || source === null) return void 0;
2965
- return source[INVOCATION_OBSERVATION];
2966
- }
2967
- /** @internal Carry a snapshot across an SDK adapter projection without resolving again. */
2968
- function copyInvocationObservation(source, target) {
2969
- const snapshot = readInvocationObservation(source);
2970
- return snapshot === void 0 ? target : attachInvocationObservation(target, snapshot.context);
2971
- }
2972
- /** @internal Mark a failure envelope as already resolved at the public invocation boundary. */
2973
- function markFailureInvocationSnapshot(failure) {
2974
- Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {
2975
- configurable: false,
2976
- enumerable: false,
2977
- value: true,
2978
- writable: false
2979
- });
2980
- return failure;
2981
- }
2982
- /** @internal Distinguish public-boundary failures from direct adapter calls. */
2983
- function hasFailureInvocationSnapshot(failure) {
2984
- return typeof failure === "object" && failure !== null && failure[FAILURE_INVOCATION_SNAPSHOT] === true;
2985
- }
2986
- //#endregion
2987
4017
  //#region src/ports/identity.ts
2988
4018
  var IdentityError = class extends Data.TaggedError("IdentityError") {};
2989
4019
  function identityErrorFromCapxul(operation, error, cause = error) {
@@ -3061,19 +4091,6 @@ function fromWei(rawBalance, decimals, currency) {
3061
4091
  };
3062
4092
  }
3063
4093
  //#endregion
3064
- //#region src/ports/sub-account.ts
3065
- var SubAccountError = class extends Data.TaggedError("SubAccountError") {};
3066
- function subAccountErrorFromCapxul(operation, error, cause = error) {
3067
- return new SubAccountError({
3068
- operation,
3069
- publicCode: error.code,
3070
- publicError: error,
3071
- cause,
3072
- ...error.details === void 0 ? {} : { details: error.details }
3073
- });
3074
- }
3075
- var SubAccountPortTag = class extends Context.Service()("@capxul/sdk/ports/SubAccountPort") {};
3076
- //#endregion
3077
4094
  //#region src/ports/smart-account.ts
3078
4095
  var SmartAccountError = class extends Data.TaggedError("SmartAccountError") {};
3079
4096
  function smartAccountErrorFromCapxul(operation, error, cause = error) {
@@ -3102,31 +4119,15 @@ const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeI
3102
4119
  const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
3103
4120
  const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
3104
4121
  const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
3105
- const SUBACCOUNT_ID_TELEMETRY_RE = /^subaccount_[0-9A-Za-z]+$/;
3106
4122
  const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
3107
4123
  const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
3108
- const SubAccountIdSchema = Schema.String.pipe(Schema.refine((value) => SUBACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be subaccount_ plus an alphanumeric id" }));
3109
4124
  const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
3110
4125
  const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
3111
4126
  const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
3112
- const TransferDirectionSchema = Schema.Literals([
3113
- "add",
3114
- "out",
3115
- "between"
3116
- ]);
3117
- const SubAccountOpSchema = Schema.Literals([
3118
- "create",
3119
- "rename",
3120
- "delete"
3121
- ]);
3122
4127
  const OptionalAccountId = Schema.optional(AccountIdSchema);
3123
- const OptionalSubAccountId = Schema.optional(SubAccountIdSchema);
3124
4128
  const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
3125
4129
  const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
3126
4130
  const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
3127
- const OptionalTransferDirection = Schema.optional(TransferDirectionSchema);
3128
- const OptionalSubAccountOp = Schema.optional(SubAccountOpSchema);
3129
- const OptionalTrue = Schema.optional(Schema.Literal(true));
3130
4131
  const OptionalAddress = Schema.optional(AddressSchema);
3131
4132
  const OptionalAppId = Schema.optional(AppIdSchema);
3132
4133
  const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
@@ -3135,11 +4136,6 @@ const OptionalDurationMs = Schema.optional(DurationMsSchema);
3135
4136
  const OptionalEpochMs = Schema.optional(EpochMsSchema);
3136
4137
  const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
3137
4138
  const OptionalTxHash = Schema.optional(TxHashSchema);
3138
- const PAYMENT_ID_TELEMETRY_RE = /^payment_[0-9A-Za-z]+$/;
3139
- const PAYEE_ID_TELEMETRY_RE = /^payee_[0-9A-Za-z]+$/;
3140
- const PaymentIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => PAYMENT_ID_TELEMETRY_RE.test(value), { message: "must be payment_ plus an alphanumeric id" }));
3141
- const PayeeIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => PAYEE_ID_TELEMETRY_RE.test(value), { message: "must be payee_ plus an alphanumeric id" }));
3142
- const DocumentHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
3143
4139
  /**
3144
4140
  * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
3145
4141
  * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
@@ -3162,7 +4158,6 @@ const TelemetryEnvelopeProps = {
3162
4158
  "mcp",
3163
4159
  "e2e"
3164
4160
  ]),
3165
- capxul_e2e_run_id: OptionalString,
3166
4161
  journey_id: OptionalString,
3167
4162
  correlation_id: OptionalString,
3168
4163
  sdk_version: OptionalString
@@ -3266,45 +4261,6 @@ const FaucetFailedProps = Schema.Struct({
3266
4261
  ...TelemetryEnvelopeProps,
3267
4262
  reason: OptionalString
3268
4263
  });
3269
- const SubaccountCreatedProps = Schema.Struct({
3270
- ...TelemetryEnvelopeProps,
3271
- sub_account_id: OptionalSubAccountId,
3272
- durationMs: OptionalDurationMs
3273
- });
3274
- const SubaccountRenamedProps = Schema.Struct({
3275
- ...TelemetryEnvelopeProps,
3276
- sub_account_id: OptionalSubAccountId
3277
- });
3278
- const SubaccountDeletedProps = Schema.Struct({
3279
- ...TelemetryEnvelopeProps,
3280
- sub_account_id: OptionalSubAccountId
3281
- });
3282
- const SubaccountOpFailedProps = Schema.Struct({
3283
- ...TelemetryEnvelopeProps,
3284
- op: OptionalSubAccountOp,
3285
- reason: OptionalString
3286
- });
3287
- const TransferRequestedProps = Schema.Struct({
3288
- ...TelemetryEnvelopeProps,
3289
- amount: OptionalWeiAmount,
3290
- direction: OptionalTransferDirection
3291
- });
3292
- const TransferBackendReceivedProps = Schema.Struct({
3293
- ...TelemetryEnvelopeProps,
3294
- direction: OptionalTransferDirection
3295
- });
3296
- const TransferConfirmedProps = Schema.Struct({
3297
- ...TelemetryEnvelopeProps,
3298
- amount: OptionalWeiAmount,
3299
- direction: OptionalTransferDirection,
3300
- available_bucket: OptionalBalanceBucket,
3301
- txless: OptionalTrue,
3302
- durationMs: OptionalDurationMs
3303
- });
3304
- const TransferFailedProps = Schema.Struct({
3305
- ...TelemetryEnvelopeProps,
3306
- reason: OptionalString
3307
- });
3308
4264
  const ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;
3309
4265
  const OrgIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => ORG_ID_TELEMETRY_RE.test(value), { message: "must be org_ plus an alphanumeric id" }));
3310
4266
  const OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);
@@ -3429,75 +4385,70 @@ const OrgInviteAcceptedProps = Schema.Struct({
3429
4385
  role: OptionalString,
3430
4386
  status: OptionalString
3431
4387
  });
3432
- const OrgRoleGrantedProps = Schema.Struct({
4388
+ const OrgInviteExpiredProps = Schema.Struct({
3433
4389
  ...TelemetryEnvelopeProps,
3434
4390
  org_id: OptionalOrgId,
4391
+ email_domain: OptionalString,
4392
+ reason: OptionalString,
3435
4393
  role: OptionalString,
3436
- status: OptionalString,
3437
- txHash: OptionalTxHash
4394
+ status: OptionalString
3438
4395
  });
3439
- const OrgMemberActiveProps = Schema.Struct({
4396
+ const PaymentInitiatedProps = Schema.Struct({
3440
4397
  ...TelemetryEnvelopeProps,
3441
- org_id: OptionalOrgId,
3442
- role: OptionalString,
3443
- status: OptionalString,
3444
- durationMs: OptionalDurationMs
4398
+ kind: Schema.String,
4399
+ payment_id: Schema.String
3445
4400
  });
3446
- const OrgMemberRemovedProps = Schema.Struct({
4401
+ const PaymentSettledL2Props = Schema.Struct({
3447
4402
  ...TelemetryEnvelopeProps,
3448
- org_id: OptionalOrgId,
3449
- role: OptionalString,
3450
- status: OptionalString,
3451
- txHash: OptionalTxHash
4403
+ kind: Schema.String,
4404
+ chain_id: Schema.Number,
4405
+ settlement_id: Schema.String
3452
4406
  });
3453
- const OrgInviteExpiredProps = Schema.Struct({
4407
+ const PaymentFailedL2Props = Schema.Struct({
3454
4408
  ...TelemetryEnvelopeProps,
3455
- org_id: OptionalOrgId,
3456
- email_domain: OptionalString,
3457
- reason: OptionalString,
3458
- role: OptionalString,
3459
- status: OptionalString
4409
+ kind: Schema.String,
4410
+ payment_id: Schema.String,
4411
+ reason_code: Schema.String
3460
4412
  });
3461
- const OrgRoleGrantFailedProps = Schema.Struct({
4413
+ const DepositInitiatedProps = Schema.Struct({ ...TelemetryEnvelopeProps });
4414
+ const DepositSettledProps = Schema.Struct({
3462
4415
  ...TelemetryEnvelopeProps,
3463
- org_id: OptionalOrgId,
3464
- reason: OptionalString,
3465
- role: OptionalString
4416
+ chain_id: Schema.Number,
4417
+ tx_hash: Schema.String,
4418
+ log_index: Schema.Number
3466
4419
  });
3467
- const OptionalPaymentId = Schema.optional(PaymentIdTelemetrySchema);
3468
- const OptionalPayeeId = Schema.optional(PayeeIdTelemetrySchema);
3469
- const OptionalDocumentHash = Schema.optional(DocumentHashSchema);
3470
- const PaymentTargetTelemetryProps = Schema.Struct({
4420
+ const PermissionMirrorVerificationProps = Schema.Struct({
3471
4421
  ...TelemetryEnvelopeProps,
3472
- payment_id: OptionalPaymentId,
3473
- payee_id: OptionalPayeeId,
3474
- document_hash: OptionalDocumentHash,
3475
- amount: OptionalWeiAmount,
3476
- currency: OptionalCurrencyCode,
3477
- status: OptionalString,
3478
- reason: OptionalString,
3479
- durationMs: OptionalDurationMs
3480
- });
3481
- const StreamTargetTelemetryProps = Schema.Struct({
4422
+ outcome: Schema.String,
4423
+ reason: Schema.String,
4424
+ chain_id: Schema.Number,
4425
+ finality: Schema.String,
4426
+ lag_blocks: Schema.Number,
4427
+ retry_count: Schema.Number
4428
+ });
4429
+ const MovementScanWindowProps = Schema.Struct({
3482
4430
  ...TelemetryEnvelopeProps,
3483
- payment_id: OptionalPaymentId,
3484
- document_hash: OptionalDocumentHash,
3485
- amount: OptionalWeiAmount,
3486
- currency: OptionalCurrencyCode,
3487
- status: OptionalString,
3488
- available_bucket: OptionalBalanceBucket,
3489
- reason: OptionalString,
3490
- durationMs: OptionalDurationMs
4431
+ chain_id: Schema.Number,
4432
+ token_address: Schema.String,
4433
+ from_block: Schema.Number,
4434
+ to_block: Schema.Number,
4435
+ log_count: Schema.Number,
4436
+ request_count: Schema.Number,
4437
+ outcome: Schema.String
4438
+ });
4439
+ const MovementScanCheckpointProps = Schema.Struct({
4440
+ ...TelemetryEnvelopeProps,
4441
+ chain_id: Schema.Number,
4442
+ token_address: Schema.String,
4443
+ next_block: Schema.Number,
4444
+ anchor_block_number: Schema.Number
3491
4445
  });
3492
- const WithdrawalTargetTelemetryProps = Schema.Struct({
4446
+ const MovementScanIncidentProps = Schema.Struct({
3493
4447
  ...TelemetryEnvelopeProps,
3494
- payment_id: OptionalPaymentId,
3495
- document_hash: OptionalDocumentHash,
3496
- amount: OptionalWeiAmount,
3497
- currency: OptionalCurrencyCode,
3498
- status: OptionalString,
3499
- reason: OptionalString,
3500
- durationMs: OptionalDurationMs
4448
+ chain_id: Schema.Number,
4449
+ token_address: Schema.String,
4450
+ incident_kind: Schema.String,
4451
+ anchor_block_number: Schema.Number
3501
4452
  });
3502
4453
  Schema.Struct({
3503
4454
  name: Schema.Literal("auth_otp_requested"),
@@ -3576,60 +4527,28 @@ Schema.Struct({
3576
4527
  props: OrganizationCreationReadyProps
3577
4528
  });
3578
4529
  Schema.Struct({
3579
- name: Schema.Literal("organization_creation_failed"),
3580
- props: OrganizationCreationFailedProps
3581
- });
3582
- Schema.Struct({
3583
- name: Schema.Literal("account_balance_read"),
3584
- props: AccountBalanceReadProps
3585
- });
3586
- Schema.Struct({
3587
- name: Schema.Literal("account_balance_failed"),
3588
- props: AccountBalanceFailedProps
3589
- });
3590
- Schema.Struct({
3591
- name: Schema.Literal("faucet_requested"),
3592
- props: FaucetRequestedProps
3593
- });
3594
- Schema.Struct({
3595
- name: Schema.Literal("faucet_confirmed"),
3596
- props: FaucetConfirmedProps
3597
- });
3598
- Schema.Struct({
3599
- name: Schema.Literal("faucet_failed"),
3600
- props: FaucetFailedProps
3601
- });
3602
- Schema.Struct({
3603
- name: Schema.Literal("subaccount_created"),
3604
- props: SubaccountCreatedProps
3605
- });
3606
- Schema.Struct({
3607
- name: Schema.Literal("subaccount_renamed"),
3608
- props: SubaccountRenamedProps
3609
- });
3610
- Schema.Struct({
3611
- name: Schema.Literal("subaccount_deleted"),
3612
- props: SubaccountDeletedProps
4530
+ name: Schema.Literal("organization_creation_failed"),
4531
+ props: OrganizationCreationFailedProps
3613
4532
  });
3614
4533
  Schema.Struct({
3615
- name: Schema.Literal("subaccount_op_failed"),
3616
- props: SubaccountOpFailedProps
4534
+ name: Schema.Literal("account_balance_read"),
4535
+ props: AccountBalanceReadProps
3617
4536
  });
3618
4537
  Schema.Struct({
3619
- name: Schema.Literal("transfer_requested"),
3620
- props: TransferRequestedProps
4538
+ name: Schema.Literal("account_balance_failed"),
4539
+ props: AccountBalanceFailedProps
3621
4540
  });
3622
4541
  Schema.Struct({
3623
- name: Schema.Literal("transfer_backend_received"),
3624
- props: TransferBackendReceivedProps
4542
+ name: Schema.Literal("faucet_requested"),
4543
+ props: FaucetRequestedProps
3625
4544
  });
3626
4545
  Schema.Struct({
3627
- name: Schema.Literal("transfer_confirmed"),
3628
- props: TransferConfirmedProps
4546
+ name: Schema.Literal("faucet_confirmed"),
4547
+ props: FaucetConfirmedProps
3629
4548
  });
3630
4549
  Schema.Struct({
3631
- name: Schema.Literal("transfer_failed"),
3632
- props: TransferFailedProps
4550
+ name: Schema.Literal("faucet_failed"),
4551
+ props: FaucetFailedProps
3633
4552
  });
3634
4553
  Schema.Struct({
3635
4554
  name: Schema.Literal("org_create_started"),
@@ -3663,97 +4582,45 @@ Schema.Struct({
3663
4582
  name: Schema.Literal("org_invite_accepted"),
3664
4583
  props: OrgInviteAcceptedProps
3665
4584
  });
3666
- Schema.Struct({
3667
- name: Schema.Literal("org_role_granted"),
3668
- props: OrgRoleGrantedProps
3669
- });
3670
- Schema.Struct({
3671
- name: Schema.Literal("org_member_active"),
3672
- props: OrgMemberActiveProps
3673
- });
3674
- Schema.Struct({
3675
- name: Schema.Literal("org_member_removed"),
3676
- props: OrgMemberRemovedProps
3677
- });
3678
4585
  Schema.Struct({
3679
4586
  name: Schema.Literal("org_invite_expired"),
3680
4587
  props: OrgInviteExpiredProps
3681
4588
  });
3682
4589
  Schema.Struct({
3683
- name: Schema.Literal("org_role_grant_failed"),
3684
- props: OrgRoleGrantFailedProps
3685
- });
3686
- Schema.Struct({
3687
- name: Schema.Literal("payment_requested"),
3688
- props: PaymentTargetTelemetryProps
3689
- });
3690
- Schema.Struct({
3691
- name: Schema.Literal("payment_resolved"),
3692
- props: PaymentTargetTelemetryProps
3693
- });
3694
- Schema.Struct({
3695
- name: Schema.Literal("payment_document_attached"),
3696
- props: PaymentTargetTelemetryProps
3697
- });
3698
- Schema.Struct({
3699
- name: Schema.Literal("payment_submitted"),
3700
- props: PaymentTargetTelemetryProps
4590
+ name: Schema.Literal("payment_initiated"),
4591
+ props: PaymentInitiatedProps
3701
4592
  });
3702
4593
  Schema.Struct({
3703
4594
  name: Schema.Literal("payment_settled"),
3704
- props: PaymentTargetTelemetryProps
3705
- });
3706
- Schema.Struct({
3707
- name: Schema.Literal("payment_claimed"),
3708
- props: PaymentTargetTelemetryProps
3709
- });
3710
- Schema.Struct({
3711
- name: Schema.Literal("payment_cancelled"),
3712
- props: PaymentTargetTelemetryProps
3713
- });
3714
- Schema.Struct({
3715
- name: Schema.Literal("payment_redirected"),
3716
- props: PaymentTargetTelemetryProps
4595
+ props: PaymentSettledL2Props
3717
4596
  });
3718
4597
  Schema.Struct({
3719
4598
  name: Schema.Literal("payment_failed"),
3720
- props: PaymentTargetTelemetryProps
4599
+ props: PaymentFailedL2Props
3721
4600
  });
3722
4601
  Schema.Struct({
3723
- name: Schema.Literal("stream_created"),
3724
- props: StreamTargetTelemetryProps
4602
+ name: Schema.Literal("deposit_initiated"),
4603
+ props: DepositInitiatedProps
3725
4604
  });
3726
4605
  Schema.Struct({
3727
- name: Schema.Literal("stream_claimed"),
3728
- props: StreamTargetTelemetryProps
4606
+ name: Schema.Literal("deposit_settled"),
4607
+ props: DepositSettledProps
3729
4608
  });
3730
4609
  Schema.Struct({
3731
- name: Schema.Literal("stream_cancelled"),
3732
- props: StreamTargetTelemetryProps
4610
+ name: Schema.Literal("permission_mirror_verification"),
4611
+ props: PermissionMirrorVerificationProps
3733
4612
  });
3734
4613
  Schema.Struct({
3735
- name: Schema.Literal("stream_completed"),
3736
- props: StreamTargetTelemetryProps
4614
+ name: Schema.Literal("movement_scan_window"),
4615
+ props: MovementScanWindowProps
3737
4616
  });
3738
4617
  Schema.Struct({
3739
- name: Schema.Literal("stream_failed"),
3740
- props: StreamTargetTelemetryProps
4618
+ name: Schema.Literal("movement_scan_checkpoint"),
4619
+ props: MovementScanCheckpointProps
3741
4620
  });
3742
4621
  Schema.Struct({
3743
- name: Schema.Literal("withdrawal_requested"),
3744
- props: WithdrawalTargetTelemetryProps
3745
- });
3746
- Schema.Struct({
3747
- name: Schema.Literal("withdrawal_submitted"),
3748
- props: WithdrawalTargetTelemetryProps
3749
- });
3750
- Schema.Struct({
3751
- name: Schema.Literal("withdrawal_settled"),
3752
- props: WithdrawalTargetTelemetryProps
3753
- });
3754
- Schema.Struct({
3755
- name: Schema.Literal("withdrawal_failed"),
3756
- props: WithdrawalTargetTelemetryProps
4622
+ name: Schema.Literal("movement_scan_incident"),
4623
+ props: MovementScanIncidentProps
3757
4624
  });
3758
4625
  function redactTelemetryEvent(event, options = {}) {
3759
4626
  const props = redactTelemetryProps(event.name, event.props, options);
@@ -3764,7 +4631,7 @@ function redactTelemetryEvent(event, options = {}) {
3764
4631
  }
3765
4632
  function redactTelemetryProps(name, props, options = {}) {
3766
4633
  if (props === void 0) return void 0;
3767
- const clone = cloneProps(props);
4634
+ const clone = cloneProps$1(props);
3768
4635
  if (options.rawMode === true) return clone;
3769
4636
  for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) redactProperty(clone, key);
3770
4637
  return clone;
@@ -3779,17 +4646,17 @@ function redactProperty(props, key) {
3779
4646
  const value = props[key];
3780
4647
  if (typeof value === "string") props[key] = sha256Hex(value).slice(0, 12);
3781
4648
  }
3782
- function cloneProps(props) {
4649
+ function cloneProps$1(props) {
3783
4650
  const cloned = {};
3784
- for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue(value);
4651
+ for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue$1(value);
3785
4652
  return cloned;
3786
4653
  }
3787
- function cloneTelemetryValue(value) {
3788
- if (Array.isArray(value)) return value.map(cloneTelemetryValue);
4654
+ function cloneTelemetryValue$1(value) {
4655
+ if (Array.isArray(value)) return value.map(cloneTelemetryValue$1);
3789
4656
  if (value === null || typeof value !== "object") return value;
3790
4657
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
3791
4658
  const cloned = {};
3792
- for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue(nested);
4659
+ for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue$1(nested);
3793
4660
  return cloned;
3794
4661
  }
3795
4662
  const SHA256_INITIAL_HASH = [
@@ -3947,6 +4814,90 @@ function rotr(value, bits) {
3947
4814
  //#region src/ports/telemetry.ts
3948
4815
  var TelemetryPortTag = class extends Context.Service()("@capxul/sdk/ports/TelemetryPort") {};
3949
4816
  //#endregion
4817
+ //#region src/adapters/telemetry/PostHogTelemetryAdapter.ts
4818
+ var PostHogTelemetryAdapter = class {
4819
+ #capture;
4820
+ #identify;
4821
+ #group;
4822
+ #reset;
4823
+ constructor(deps) {
4824
+ this.#capture = deps.capture;
4825
+ this.#identify = deps.identify ?? (() => void 0);
4826
+ this.#group = deps.group ?? (() => void 0);
4827
+ this.#reset = deps.reset ?? (() => void 0);
4828
+ }
4829
+ emit(event) {
4830
+ return this.#run(() => this.#capture(event.name, redactTelemetryProps(event.name, cloneProps(event.props)), event), "emit", event.name);
4831
+ }
4832
+ identify(input) {
4833
+ return this.#run(() => this.#identify(cloneIdentifyInput(input)), "identify");
4834
+ }
4835
+ group(input) {
4836
+ return this.#run(() => this.#group(cloneGroupInput(input)), "group");
4837
+ }
4838
+ reset() {
4839
+ return this.#run(() => this.#reset(), "reset");
4840
+ }
4841
+ #run(operation, operationName, eventName) {
4842
+ const diagnose = Effect.logWarning("product.telemetry.transport.dropped").pipe(Effect.annotateLogs({
4843
+ operation: operationName,
4844
+ ...eventName === void 0 ? {} : { product_event: eventName }
4845
+ }), Effect.catchCause(() => Effect.void));
4846
+ return Effect.suspend(() => {
4847
+ let pending;
4848
+ try {
4849
+ pending = operation();
4850
+ } catch {
4851
+ return diagnose;
4852
+ }
4853
+ if (pending === void 0) return Effect.void;
4854
+ const transport = Effect.tryPromise({
4855
+ try: () => pending,
4856
+ catch: () => void 0
4857
+ }).pipe(Effect.catch(() => diagnose));
4858
+ return Effect.forkDetach(transport, { startImmediately: true }).pipe(Effect.asVoid);
4859
+ });
4860
+ }
4861
+ };
4862
+ function PostHogTelemetryLayer(deps) {
4863
+ return Layer.succeed(TelemetryPortTag, new PostHogTelemetryAdapter(deps));
4864
+ }
4865
+ function cloneIdentifyInput(input) {
4866
+ const traits = input.traits === void 0 ? void 0 : cloneProps(input.traits);
4867
+ const properties = input.properties === void 0 ? void 0 : cloneProps(input.properties);
4868
+ return {
4869
+ distinctId: input.distinctId,
4870
+ ...input.anonDistinctId === void 0 ? {} : { anonDistinctId: input.anonDistinctId },
4871
+ ...traits === void 0 ? {} : { traits },
4872
+ ...properties === void 0 ? {} : { properties }
4873
+ };
4874
+ }
4875
+ function cloneGroupInput(input) {
4876
+ const properties = input.properties === void 0 ? void 0 : cloneProps(input.properties);
4877
+ return properties === void 0 ? {
4878
+ groupType: input.groupType,
4879
+ groupKey: input.groupKey
4880
+ } : {
4881
+ groupType: input.groupType,
4882
+ groupKey: input.groupKey,
4883
+ properties
4884
+ };
4885
+ }
4886
+ function cloneProps(props) {
4887
+ if (props === void 0) return void 0;
4888
+ const cloned = {};
4889
+ for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue(value);
4890
+ return cloned;
4891
+ }
4892
+ function cloneTelemetryValue(value) {
4893
+ if (Array.isArray(value)) return value.map(cloneTelemetryValue);
4894
+ if (value === null || typeof value !== "object") return value;
4895
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
4896
+ const cloned = {};
4897
+ for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue(nested);
4898
+ return cloned;
4899
+ }
4900
+ //#endregion
3950
4901
  //#region src/flows/identity.ts
3951
4902
  const IDENTITY_SLOT = {
3952
4903
  session: "identity:session",
@@ -4056,7 +5007,8 @@ const accountLane = (input, config, session, send) => Effect.gen(function* () {
4056
5007
  if (Result.isFailure(existing)) return yield* failAt("provision", existing.failure);
4057
5008
  const provisioned = yield* Effect.result(existing.success === null ? call("smart-account.provision", input.ports.smartAccount.provision({
4058
5009
  authUserId: toAuthUserId(session.authUserId),
4059
- chainId: toChainId(input.chainId)
5010
+ chainId: toChainId(input.chainId),
5011
+ email: toEmail(session.email)
4060
5012
  })) : Effect.succeed(existing.success));
4061
5013
  if (Result.isFailure(provisioned)) return yield* failAt("provision", provisioned.failure);
4062
5014
  const account = provisioned.success;
@@ -4288,7 +5240,7 @@ const identitySpec = (input, sessionStore = { current: null }) => {
4288
5240
  case "RequestOtp": return {
4289
5241
  slot: IDENTITY_SLOT.auth,
4290
5242
  port: "auth-client",
4291
- run: (send) => call("auth-client.send-otp", input.ports.authClient.sendOtp({ email: toEmail(event.email) })).pipe(Effect.andThen(call("clock.now", input.ports.clock.now)), Effect.flatMap((at) => send({
5243
+ run: (send, controls) => call("auth-client.send-otp", input.ports.authClient.sendOtp(copyInvocationObservation(controls, { email: toEmail(event.email) }))).pipe(Effect.andThen(call("clock.now", input.ports.clock.now)), Effect.flatMap((at) => send({
4292
5244
  _tag: "OtpSent",
4293
5245
  at
4294
5246
  })), Effect.catch((failure) => send({
@@ -4299,10 +5251,10 @@ const identitySpec = (input, sessionStore = { current: null }) => {
4299
5251
  case "VerifyOtp": return {
4300
5252
  slot: IDENTITY_SLOT.auth,
4301
5253
  port: "auth-client",
4302
- run: (send) => call("auth-client.verify-otp", input.ports.authClient.verifyOtp({
5254
+ run: (send, controls) => call("auth-client.verify-otp", input.ports.authClient.verifyOtp(copyInvocationObservation(controls, {
4303
5255
  email: toEmail(event.email),
4304
5256
  otp: event.otp
4305
- })).pipe(Effect.tap((session) => Effect.sync(() => {
5257
+ }))).pipe(Effect.tap((session) => Effect.sync(() => {
4306
5258
  sessionStore.current = session;
4307
5259
  })), Effect.flatMap((session) => sessionProfile(input, session).pipe(Effect.flatMap((loaded) => send({
4308
5260
  _tag: "Verified",
@@ -4316,7 +5268,7 @@ const identitySpec = (input, sessionStore = { current: null }) => {
4316
5268
  case "ReadSession": return {
4317
5269
  slot: IDENTITY_SLOT.session,
4318
5270
  port: "auth-client",
4319
- run: (send) => call("auth-client.get-session", input.ports.authClient.getSession()).pipe(Effect.tap((session) => Effect.sync(() => {
5271
+ run: (send, controls) => call("auth-client.get-session", input.ports.authClient.getSession(copyInvocationObservation(controls, {}))).pipe(Effect.tap((session) => Effect.sync(() => {
4320
5272
  sessionStore.current = session;
4321
5273
  })), Effect.flatMap((session) => sessionProfile(input, session)), Effect.flatMap((loaded) => send({
4322
5274
  _tag: "SessionRead",
@@ -4331,7 +5283,7 @@ const identitySpec = (input, sessionStore = { current: null }) => {
4331
5283
  case "SignOut": return {
4332
5284
  slot: IDENTITY_SLOT.auth,
4333
5285
  port: "auth-client",
4334
- run: (send) => call("auth-client.sign-out", input.ports.authClient.signOut()).pipe(Effect.andThen(send({ _tag: "SignedOut" })), Effect.catch((failure) => send({
5286
+ run: (send, controls) => call("auth-client.sign-out", input.ports.authClient.signOut(copyInvocationObservation(controls, {}))).pipe(Effect.andThen(send({ _tag: "SignedOut" })), Effect.catch((failure) => send({
4335
5287
  _tag: "SignOutFailed",
4336
5288
  failure
4337
5289
  }).pipe(Effect.andThen(Effect.fail(failure)))), Effect.ensuring(Effect.sync(() => {
@@ -4706,7 +5658,8 @@ function provisionSmartAccountProgram() {
4706
5658
  if (session === null) return yield* Effect.fail(Errors.notAuthenticated());
4707
5659
  const provisioned = yield* deps.smartAccountPort.provision({
4708
5660
  authUserId: session.authUserId,
4709
- chainId: deps.chainId
5661
+ chainId: deps.chainId,
5662
+ email: session.email
4710
5663
  }).pipe(Effect.mapError((failure) => failure.publicError));
4711
5664
  yield* Effect.promise(() => emitProvisioningTelemetry(deps.telemetry, provisioned));
4712
5665
  return provisioned;
@@ -4792,11 +5745,6 @@ function makeIdentityMethods(deps) {
4792
5745
  function moneyToWeiAmount(money) {
4793
5746
  return toWei(money);
4794
5747
  }
4795
- function transferDirection(from, to) {
4796
- if (from === "main") return "add";
4797
- if (to === "main") return "out";
4798
- return "between";
4799
- }
4800
5748
  /** Fire-and-forget emit through an optional port; never throws. */
4801
5749
  async function emitMoneyTelemetry(telemetry, event) {
4802
5750
  if (telemetry === void 0) return;
@@ -4830,52 +5778,18 @@ function emitAccountBalanceFailed(telemetry, reason) {
4830
5778
  props: { reason }
4831
5779
  });
4832
5780
  }
4833
- function emitTransferRequested(telemetry, input) {
4834
- let amount;
4835
- try {
4836
- amount = moneyToWeiAmount(input.amount);
4837
- } catch (cause) {
4838
- reportMoneyTelemetryFailure("defect", "transfer_requested", cause);
4839
- return Promise.resolve();
4840
- }
4841
- return emitMoneyTelemetry(telemetry, {
4842
- name: "transfer_requested",
4843
- props: {
4844
- amount,
4845
- direction: transferDirection(input.from, input.to)
4846
- }
4847
- });
4848
- }
4849
- function emitTransferFailed(telemetry, reason) {
4850
- return emitMoneyTelemetry(telemetry, {
4851
- name: "transfer_failed",
4852
- props: { reason }
4853
- });
4854
- }
4855
- function emitSubAccountCreated(telemetry, subAccountId) {
4856
- return emitMoneyTelemetry(telemetry, {
4857
- name: "subaccount_created",
4858
- props: { sub_account_id: subAccountId }
4859
- });
4860
- }
4861
- function emitSubAccountRenamed(telemetry, subAccountId) {
4862
- return emitMoneyTelemetry(telemetry, {
4863
- name: "subaccount_renamed",
4864
- props: { sub_account_id: subAccountId }
4865
- });
4866
- }
4867
- function emitSubAccountDeleted(telemetry, subAccountId) {
5781
+ function emitDepositInitiated(telemetry) {
4868
5782
  return emitMoneyTelemetry(telemetry, {
4869
- name: "subaccount_deleted",
4870
- props: { sub_account_id: subAccountId }
5783
+ name: "deposit_initiated",
5784
+ props: {}
4871
5785
  });
4872
5786
  }
4873
- function emitSubAccountOpFailed(telemetry, op, reason) {
5787
+ function emitPaymentInitiated(telemetry, input) {
4874
5788
  return emitMoneyTelemetry(telemetry, {
4875
- name: "subaccount_op_failed",
5789
+ name: "payment_initiated",
4876
5790
  props: {
4877
- op,
4878
- reason
5791
+ kind: input.kind,
5792
+ payment_id: input.paymentId
4879
5793
  }
4880
5794
  });
4881
5795
  }
@@ -5009,23 +5923,160 @@ const financialOpsContract = {
5009
5923
  addDestination: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].add),
5010
5924
  listDestinations: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].list),
5011
5925
  removeDestination: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].remove),
5012
- pay: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/mutations"].pay),
5013
- payout: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].payout),
5014
- withdraw: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/mutations"].withdraw),
5015
- markPaymentSettled: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].markPaymentSettled),
5016
- markWithdrawalSettled: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].markWithdrawalSettled),
5017
- recordOrgPayment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].recordOrgPayment),
5018
- markCommitmentCreated: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].markCommitmentCreated),
5019
- claimCommitment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].claimCommitment),
5020
- cancelCommitment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].cancelCommitment),
5021
- redirectCommitment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].redirectCommitment),
5022
5926
  listPayments: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].listPayments),
5023
5927
  getPayment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].getPayment),
5928
+ activityList: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].list),
5929
+ activityGet: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].get),
5930
+ activityAnnotate: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].annotate),
5024
5931
  verifyPaymentDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].verifyPaymentDocument),
5025
- renderStoredDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].renderStoredDocument),
5026
- getCommitmentRef: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].getCommitmentRef)
5932
+ renderStoredDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].renderStoredDocument)
5027
5933
  };
5028
5934
  //#endregion
5935
+ //#region src/contract/money-execution.ts
5936
+ const moneyExecutionContract = {
5937
+ preparePermissionExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].preparePermissionExecution),
5938
+ preparePaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].preparePaymentExecution),
5939
+ prepareOrganizationPaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/paymentCommandActions"].prepareOrganizationPaymentExecution),
5940
+ preparePaymentLifecycleExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/paymentCommandActions"].preparePaymentLifecycleExecution),
5941
+ submitPaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].submitPaymentExecution),
5942
+ submitPermissionExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].submitPermissionExecution),
5943
+ submitPaymentCommandExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/paymentCommandActions"].submitPaymentCommandExecution)
5944
+ };
5945
+ //#endregion
5946
+ //#region src/surface/payment-execution.ts
5947
+ function mismatch(field, message) {
5948
+ return {
5949
+ ok: false,
5950
+ error: Errors.invalidInput(field, message)
5951
+ };
5952
+ }
5953
+ function cancelled(operation) {
5954
+ return {
5955
+ ok: false,
5956
+ error: Errors.cancelled({ operation })
5957
+ };
5958
+ }
5959
+ function isAborted$2(signal) {
5960
+ return signal?.aborted === true;
5961
+ }
5962
+ async function signerCall(operation, run) {
5963
+ try {
5964
+ return {
5965
+ ok: true,
5966
+ value: await run()
5967
+ };
5968
+ } catch (cause) {
5969
+ return {
5970
+ ok: false,
5971
+ error: cause instanceof CapxulError ? cause : Errors.providerError("wallet-signer", operation, cause)
5972
+ };
5973
+ }
5974
+ }
5975
+ async function executePersonalPayment(deps, payment, signal, requestKey) {
5976
+ if (isAborted$2(signal)) return cancelled("payments.pay");
5977
+ if (deps.signer === void 0) return mismatch("signer", "payments.pay requires a configured CapxulSigner");
5978
+ const session = deps.actor.authSession();
5979
+ if (session === null) return {
5980
+ ok: false,
5981
+ error: Errors.notAuthenticated()
5982
+ };
5983
+ const signerAddress = await signerCall("getAddress", () => deps.signer.getAddress());
5984
+ if (!signerAddress.ok) return signerAddress;
5985
+ const expectedSafe = deriveCapxulSafeAddress({ email: session.email });
5986
+ const resolvedRequestKey = requestKey ?? `pay_${crypto.randomUUID()}`;
5987
+ const prepared = await runIfActive(signal, "payments.prepareExecution", () => deps.convexCall.action(deps.functions.preparePaymentExecution, { input: {
5988
+ requestKey: resolvedRequestKey,
5989
+ signerAddress: signerAddress.value,
5990
+ payment
5991
+ } }));
5992
+ if (!prepared.ok) return prepared;
5993
+ if (prepared.value.requestKey !== resolvedRequestKey || JSON.stringify(prepared.value.payment) !== JSON.stringify(payment)) return mismatch("payment", "prepared Payment execution uses another request");
5994
+ if (prepared.value.chainId !== deps.chainId) return mismatch("chainId", "prepared Payment execution uses another chain");
5995
+ if (prepared.value.signerAddress.toLowerCase() !== signerAddress.value.toLowerCase()) return mismatch("signerAddress", "prepared Payment execution uses another signer");
5996
+ if (prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return mismatch("userOpSenderSafe", "prepared Payment execution uses another Account Safe");
5997
+ if (prepared.value.emitPaymentInitiated) await emitPaymentInitiated(deps.telemetry, {
5998
+ kind: prepared.value.purposeKind,
5999
+ paymentId: prepared.value.paymentId
6000
+ });
6001
+ if (isAborted$2(signal)) return cancelled("payments.pay");
6002
+ const signature = await signerCall("signUserOpHash", () => deps.signer.signUserOpHash(prepared.value.digest));
6003
+ if (!signature.ok) return signature;
6004
+ if (isAborted$2(signal)) return cancelled("payments.pay");
6005
+ return runIfActive(void 0, "payments.submitExecution", () => deps.convexCall.action(deps.functions.submitPaymentExecution, { input: {
6006
+ executionId: prepared.value.executionId,
6007
+ signature: signature.value
6008
+ } }));
6009
+ }
6010
+ //#endregion
6011
+ //#region src/surface/payment-command-execution.ts
6012
+ function isAborted$1(signal) {
6013
+ return signal?.aborted === true;
6014
+ }
6015
+ function signerFailure(operation, cause) {
6016
+ return {
6017
+ ok: false,
6018
+ error: cause instanceof CapxulError ? cause : Errors.providerError("wallet-signer", operation, cause)
6019
+ };
6020
+ }
6021
+ async function executePrepared(deps, prepare, expectedRequest, signal) {
6022
+ if (isAborted$1(signal)) return {
6023
+ ok: false,
6024
+ error: Errors.cancelled({ operation: "payments" })
6025
+ };
6026
+ const session = deps.actor.authSession();
6027
+ if (session === null) return {
6028
+ ok: false,
6029
+ error: Errors.notAuthenticated()
6030
+ };
6031
+ let signerAddress;
6032
+ try {
6033
+ signerAddress = await deps.signer.getAddress();
6034
+ } catch (cause) {
6035
+ return signerFailure("getAddress", cause);
6036
+ }
6037
+ const prepared = await prepare(signerAddress);
6038
+ if (!prepared.ok) return prepared;
6039
+ if (JSON.stringify(prepared.value.request) !== JSON.stringify(expectedRequest)) return {
6040
+ ok: false,
6041
+ error: Errors.invalidInput("payment", "prepared command mismatch")
6042
+ };
6043
+ const expectedSafe = deriveCapxulSafeAddress({ email: session.email });
6044
+ if (prepared.value.chainId !== deps.chainId || prepared.value.signerAddress.toLowerCase() !== signerAddress.toLowerCase() || prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return {
6045
+ ok: false,
6046
+ error: Errors.invalidInput("payment", "prepared authority mismatch")
6047
+ };
6048
+ if (isAborted$1(signal)) return {
6049
+ ok: false,
6050
+ error: Errors.cancelled({ operation: "payments" })
6051
+ };
6052
+ let signature;
6053
+ try {
6054
+ signature = await deps.signer.signUserOpHash(prepared.value.digest);
6055
+ } catch (cause) {
6056
+ return signerFailure("signUserOpHash", cause);
6057
+ }
6058
+ if (isAborted$1(signal)) return {
6059
+ ok: false,
6060
+ error: Errors.cancelled({ operation: "payments" })
6061
+ };
6062
+ return runIfActive(void 0, "payments.submitCommandExecution", () => deps.convexCall.action(deps.functions.submitPaymentCommandExecution, { input: {
6063
+ executionId: prepared.value.executionId,
6064
+ signature
6065
+ } }));
6066
+ }
6067
+ function executePaymentLifecycle(deps, intent, signal) {
6068
+ return executePrepared(deps, (signerAddress) => runIfActive(signal, "payments.prepareLifecycleExecution", () => deps.convexCall.action(deps.functions.preparePaymentLifecycleExecution, { input: {
6069
+ signerAddress,
6070
+ intent
6071
+ } })), intent, signal);
6072
+ }
6073
+ function executeOrganizationPayment(deps, input, signal) {
6074
+ return executePrepared(deps, (signerAddress) => runIfActive(signal, "organizationPayments.prepareExecution", () => deps.convexCall.action(deps.functions.prepareOrganizationPaymentExecution, { input: {
6075
+ ...input,
6076
+ signerAddress
6077
+ } })), input, signal);
6078
+ }
6079
+ //#endregion
5029
6080
  //#region src/surface/money.ts
5030
6081
  function actorReferenceToBackend(actor) {
5031
6082
  if (actor === void 0) return void 0;
@@ -5039,12 +6090,74 @@ function actorReferenceToBackend(actor) {
5039
6090
  case "org": return actor;
5040
6091
  }
5041
6092
  }
6093
+ function paymentExecutionIntent(input) {
6094
+ if (actorReferenceToBackend(input.actor)?.kind === "org") return {
6095
+ ok: false,
6096
+ error: Errors.notImplemented("payments", "pay.organizationActor")
6097
+ };
6098
+ const to = normalizeTargetForBackend(input.to, "to");
6099
+ if (!to.ok) return to;
6100
+ return {
6101
+ ok: true,
6102
+ value: {
6103
+ to: to.value,
6104
+ amount: input.amount,
6105
+ ...input.paymentType === void 0 ? {} : { paymentType: input.paymentType },
6106
+ ...input.document === void 0 ? {} : { document: input.document },
6107
+ ...input.timing === void 0 ? {} : { timing: input.timing },
6108
+ ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
6109
+ }
6110
+ };
6111
+ }
5042
6112
  function makeFinancialOpsMethods(deps) {
5043
6113
  const fns = deps.functions ?? financialOpsContract;
6114
+ const executionFns = deps.moneyExecutionFunctions ?? moneyExecutionContract;
6115
+ const pay = async (input, options) => {
6116
+ if (options?.signal?.aborted === true) return {
6117
+ ok: false,
6118
+ error: Errors.cancelled({ operation: "payments.pay" })
6119
+ };
6120
+ const payment = paymentExecutionIntent(input);
6121
+ if (!payment.ok) return payment;
6122
+ if (deps.actor === void 0 || deps.chainId === void 0) return {
6123
+ ok: false,
6124
+ error: Errors.notImplemented("payments", "executionComposition")
6125
+ };
6126
+ return mapOk(await executePersonalPayment({
6127
+ actor: deps.actor,
6128
+ chainId: deps.chainId,
6129
+ convexCall: deps.convexCall,
6130
+ functions: executionFns,
6131
+ ...deps.signer === void 0 ? {} : { signer: deps.signer },
6132
+ ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
6133
+ }, payment.value, options?.signal, input.requestKey), (submitted) => normalizePaymentTiming(submitted.payment));
6134
+ };
6135
+ const lifecycleDependencies = () => deps.actor === void 0 || deps.chainId === void 0 || deps.signer === void 0 ? {
6136
+ ok: false,
6137
+ error: Errors.notImplemented("payments", "executionComposition")
6138
+ } : {
6139
+ ok: true,
6140
+ value: {
6141
+ actor: deps.actor,
6142
+ chainId: deps.chainId,
6143
+ convexCall: deps.convexCall,
6144
+ functions: executionFns,
6145
+ signer: deps.signer
6146
+ }
6147
+ };
6148
+ const runLifecycle = async (intent, signal) => {
6149
+ const execution = lifecycleDependencies();
6150
+ if (!execution.ok) return execution;
6151
+ return mapOk(await executePaymentLifecycle(execution.value, intent, signal), (submitted) => {
6152
+ const payment = submitted.payments[0];
6153
+ if (payment === void 0 || submitted.payments.length !== 1) throw Errors.unknown();
6154
+ return normalizePaymentTiming(payment);
6155
+ });
6156
+ };
5044
6157
  return {
5045
6158
  me: {
5046
6159
  get: (options) => runIfActive(options?.signal, "me.get", () => deps.convexCall.query(fns.me, {})),
5047
- depositInstructions: (options) => runIfActive(options?.signal, "me.depositInstructions", () => deps.convexCall.query(fns.depositInstructions, {}))
6160
+ depositInstructions: (options) => runIfActive(options?.signal, "me.depositInstructions", () => deps.convexCall.query(fns.depositInstructions, {}).pipe(Effect.tap(() => Effect.promise(() => emitDepositInitiated(deps.telemetry)))))
5048
6161
  },
5049
6162
  handles: { resolve: (handle, options) => runIfActive(options?.signal, "handles.resolve", () => deps.convexCall.query(fns.resolveHandle, { handle })) },
5050
6163
  payees: {
@@ -5058,8 +6171,8 @@ function makeFinancialOpsMethods(deps) {
5058
6171
  },
5059
6172
  targets: { resolve: async (reference, options) => {
5060
6173
  switch (reference.kind) {
5061
- case "handle": return mapOk$1(await runIfActive(options?.signal, "targets.resolve.handle", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle })), (target) => resolvedTargetFromResolution(reference, target));
5062
- case "email": return mapOk$1(await runIfActive(options?.signal, "targets.resolve.email", () => deps.convexCall.query(fns.resolvePayee, { recipient: reference.email })), (target) => resolvedTargetFromResolution(reference, target));
6174
+ case "handle": return mapOk(await runIfActive(options?.signal, "targets.resolve.handle", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle })), (target) => resolvedTargetFromResolution(reference, target));
6175
+ case "email": return mapOk(await runIfActive(options?.signal, "targets.resolve.email", () => deps.convexCall.query(fns.resolvePayee, { recipient: reference.email })), (target) => resolvedTargetFromResolution(reference, target));
5063
6176
  case "organization": {
5064
6177
  const resolved = await runIfActive(options?.signal, "targets.resolve.organization", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle }));
5065
6178
  if (!resolved.ok) return {
@@ -5109,7 +6222,7 @@ function makeFinancialOpsMethods(deps) {
5109
6222
  error: Errors.invalidInput("target", DESTINATION_SCOPE_MESSAGE)
5110
6223
  };
5111
6224
  const backendActor = actorReferenceToBackend(input.actor);
5112
- return mapOk$1(await runIfActive(options?.signal, "destinations.add", () => deps.convexCall.mutation(fns.addDestination, {
6225
+ return mapOk(await runIfActive(options?.signal, "destinations.add", () => deps.convexCall.mutation(fns.addDestination, {
5113
6226
  ...backendActor === void 0 ? {} : { actor: backendActor },
5114
6227
  ...isSelfTarget(scopeValue) ? { self: true } : { ref: scopeValue },
5115
6228
  kind: destinationKindToBackend(input.kind),
@@ -5124,7 +6237,7 @@ function makeFinancialOpsMethods(deps) {
5124
6237
  error: scope.error
5125
6238
  };
5126
6239
  const scopeValue = scope.value;
5127
- return mapOk$1(await runIfActive(options?.signal, "destinations.list", () => deps.convexCall.query(fns.listDestinations, {
6240
+ return mapOk(await runIfActive(options?.signal, "destinations.list", () => deps.convexCall.query(fns.listDestinations, {
5128
6241
  ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
5129
6242
  ...scopeValue !== void 0 && isSelfTarget(scopeValue) ? { self: true } : {},
5130
6243
  ...scopeValue !== void 0 && !isSelfTarget(scopeValue) ? { ref: scopeValue } : {}
@@ -5136,117 +6249,49 @@ function makeFinancialOpsMethods(deps) {
5136
6249
  }))
5137
6250
  },
5138
6251
  payments: {
5139
- pay: async (input, options) => {
5140
- if (actorReferenceToBackend(input.actor)?.kind === "org") return {
5141
- ok: false,
5142
- error: Errors.notImplemented("payments", "pay.organizationActor")
5143
- };
5144
- const to = normalizeTargetForBackend(input.to, "to");
5145
- if (!to.ok) return {
5146
- ok: false,
5147
- error: to.error
5148
- };
5149
- return mapOk$1(await runIfActive(options?.signal, "payments.pay", () => deps.convexCall.mutation(fns.pay, {
5150
- to: to.value,
5151
- amount: input.amount,
5152
- ...input.paymentType === void 0 ? {} : { paymentType: input.paymentType },
5153
- ...input.document === void 0 ? {} : { document: input.document },
5154
- ...input.timing === void 0 ? {} : { timing: input.timing },
5155
- ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
5156
- })), normalizePaymentTiming$1);
5157
- },
5158
- payout: async (input, options) => mapOk$1(await runIfActive(options?.signal, "payments.payout", () => deps.convexCall.mutation(fns.payout, {
5159
- ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
5160
- destinationId: input.destinationId,
5161
- amount: input.amount
5162
- })), normalizePaymentTiming$1),
5163
- withdraw: (input, options) => runIfActive(options?.signal, "payments.withdraw", () => deps.convexCall.mutation(fns.withdraw, {
5164
- to: input.to,
5165
- amount: input.amount,
5166
- document: input.document
5167
- })),
5168
- list: async (options) => mapOk$1(await runIfActive(options?.signal, "payments.list", () => deps.convexCall.query(fns.listPayments, {})), (payments) => payments.map(normalizePaymentTiming$1)),
5169
- get: async (paymentId, options) => mapOk$1(await runIfActive(options?.signal, "payments.get", () => deps.convexCall.query(fns.getPayment, { paymentId })), (payment) => payment === null ? null : normalizePaymentTiming$1(payment)),
5170
- cancel: (paymentId, options) => {
5171
- if (options?.signal?.aborted) return Promise.resolve({
5172
- ok: false,
5173
- error: Errors.cancelled({ operation: "payments.cancel" })
5174
- });
5175
- return Promise.resolve({
5176
- ok: false,
5177
- error: Errors.notImplemented("payments", "cancel")
5178
- });
5179
- },
5180
- _internal: {
5181
- markSettled: (input, options) => runIfActive(options?.signal, "payments.markSettled", () => deps.convexCall.action(fns.markPaymentSettled, {
5182
- paymentId: input.paymentId,
5183
- userOpHash: input.evidence.userOpHash,
5184
- txHash: input.evidence.txHash
5185
- })),
5186
- markWithdrawalSettled: (input, options) => runIfActive(options?.signal, "payments.markWithdrawalSettled", () => deps.convexCall.action(fns.markWithdrawalSettled, {
5187
- paymentId: input.paymentId,
5188
- userOpHash: input.evidence.userOpHash,
5189
- txHash: input.evidence.txHash
5190
- })),
5191
- recordOrgPayment: (input, options) => runIfActive(options?.signal, "payments.recordOrgPayment", () => deps.convexCall.action(fns.recordOrgPayment, {
5192
- orgId: input.orgId,
5193
- recipientLabel: input.recipientLabel,
5194
- ...input.recipientKind === void 0 ? {} : { recipientKind: input.recipientKind },
5195
- ...input.recipientRef === void 0 ? {} : { recipientRef: input.recipientRef },
5196
- ...input.recipientPayeeId === void 0 ? {} : { recipientPayeeId: input.recipientPayeeId },
5197
- recipientSafeAddress: input.recipientSafeAddress,
5198
- amount: input.amount,
5199
- paymentType: input.paymentType,
5200
- ...input.document === void 0 ? {} : { document: input.document },
5201
- orgSafeAddress: input.orgSafeAddress,
5202
- occurrenceIndex: input.occurrenceIndex,
5203
- userOpHash: input.evidence.userOpHash,
5204
- txHash: input.evidence.txHash
5205
- })),
5206
- markCommitmentCreated: (input, options) => runIfActive(options?.signal, "payments.markCommitmentCreated", () => deps.convexCall.action(fns.markCommitmentCreated, {
5207
- paymentId: input.paymentId,
5208
- onchainCommitmentId: input.onchainCommitmentId,
5209
- userOpHash: input.evidence.userOpHash,
5210
- txHash: input.evidence.txHash
5211
- })),
5212
- claim: (input, options) => runIfActive(options?.signal, "payments.claim", () => deps.convexCall.action(fns.claimCommitment, {
6252
+ pay,
6253
+ createCommitment: (input, options) => pay(input, options),
6254
+ claim: (paymentId, options) => runLifecycle({
6255
+ kind: "claim",
6256
+ paymentId
6257
+ }, options?.signal),
6258
+ list: async (options) => mapOk(await runIfActive(options?.signal, "payments.list", () => deps.convexCall.query(fns.listPayments, {})), (payments) => payments.map(normalizePaymentTiming)),
6259
+ get: async (paymentId, options) => mapOk(await runIfActive(options?.signal, "payments.get", () => deps.convexCall.query(fns.getPayment, { paymentId })), (payment) => payment === null ? null : normalizePaymentTiming(payment)),
6260
+ cancel: (paymentId, options) => runLifecycle({
6261
+ kind: "cancel",
6262
+ paymentId
6263
+ }, options?.signal),
6264
+ redirect: async (input, options) => {
6265
+ const recipient = normalizeTargetForBackend(input.to, "to");
6266
+ if (!recipient.ok) return recipient;
6267
+ return runLifecycle({
6268
+ kind: "redirect",
5213
6269
  paymentId: input.paymentId,
5214
- userOpHash: input.evidence.userOpHash,
5215
- txHash: input.evidence.txHash
5216
- })),
5217
- cancel: (input, options) => runIfActive(options?.signal, "payments.cancel", () => deps.convexCall.action(fns.cancelCommitment, {
5218
- paymentId: input.paymentId,
5219
- userOpHash: input.evidence.userOpHash,
5220
- txHash: input.evidence.txHash,
5221
- ...input.document === void 0 ? {} : { document: input.document }
5222
- })),
5223
- redirect: async (input, options) => {
5224
- const to = normalizeRefForBackend(input.to, "to");
5225
- if (!to.ok) return {
5226
- ok: false,
5227
- error: to.error
5228
- };
5229
- return mapOk$1(await runIfActive(options?.signal, "payments.redirect", () => deps.convexCall.action(fns.redirectCommitment, {
5230
- paymentId: input.paymentId,
5231
- to: to.value,
5232
- userOpHash: input.evidence.userOpHash,
5233
- txHash: input.evidence.txHash,
5234
- ...input.document === void 0 ? {} : { document: input.document }
5235
- })), normalizePaymentTiming$1);
5236
- },
5237
- commitmentRef: (paymentId, options) => runIfActive(options?.signal, "payments.commitmentRef", () => deps.convexCall.query(fns.getCommitmentRef, { paymentId }))
6270
+ recipient: recipient.value
6271
+ }, options?.signal);
5238
6272
  }
5239
6273
  },
5240
- activity: { list: (params, options) => {
5241
- if (options?.signal?.aborted) return Promise.resolve({
5242
- ok: false,
5243
- error: Errors.cancelled({ operation: "activity.list" })
5244
- });
5245
- return Promise.resolve({
5246
- ok: false,
5247
- error: Errors.notImplemented("activity", "list")
5248
- });
5249
- } },
6274
+ activity: {
6275
+ list: (params, options) => runIfActive(options?.signal, "activity.list", () => deps.convexCall.query(fns.activityList, { input: {
6276
+ ...params?.actor?.kind === "organization" ? { actor: {
6277
+ kind: "organization",
6278
+ orgId: params.actor.organizationId
6279
+ } } : {},
6280
+ ...params?.cursor === void 0 ? {} : { cursor: params.cursor },
6281
+ ...params?.limit === void 0 ? {} : { limit: params.limit }
6282
+ } })),
6283
+ get: (reference, options) => runIfActive(options?.signal, "activity.get", () => deps.convexCall.query(fns.activityGet, { input: reference })),
6284
+ annotate: (input, options) => runIfActive(options?.signal, "activity.annotate", () => deps.convexCall.mutation(fns.activityAnnotate, { input: {
6285
+ ...input.actor?.kind === "organization" ? { actor: {
6286
+ kind: "organization",
6287
+ orgId: input.actor.organizationId
6288
+ } } : {},
6289
+ movementId: input.movementId,
6290
+ ...input.counterpartyLabel === void 0 ? {} : { counterpartyLabel: input.counterpartyLabel },
6291
+ ...input.accountingCategory === void 0 ? {} : { accountingCategory: input.accountingCategory },
6292
+ ...input.memo === void 0 ? {} : { memo: input.memo }
6293
+ } }))
6294
+ },
5250
6295
  offramp: {
5251
6296
  quote: (input, options) => {
5252
6297
  if (options?.signal?.aborted) return Promise.resolve({
@@ -5275,18 +6320,6 @@ function makeFinancialOpsMethods(deps) {
5275
6320
  }
5276
6321
  };
5277
6322
  }
5278
- function refToRecipientString(ref) {
5279
- if (typeof ref === "string") throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
5280
- if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
5281
- switch (ref.kind) {
5282
- case "handle": return handleRefValue(ref.handle, "handle");
5283
- case "email": return nonEmptyRefValue(ref.email, "email");
5284
- case "orgHandle": return nonEmptyRefValue(ref.orgHandle, "orgHandle");
5285
- case "capxulUserId": return nonEmptyRefValue(ref.capxulUserId, "capxulUserId");
5286
- case "payeeId": return nonEmptyRefValue(ref.payeeId, "payeeId");
5287
- default: throw Errors.invalidInput("to", "recipient must be a known Ref variant");
5288
- }
5289
- }
5290
6323
  function nonEmptyRefValue(value, field) {
5291
6324
  const trimmed = value.trim();
5292
6325
  if (trimmed.length === 0) throw Errors.invalidInput(field, "Ref value must be non-empty");
@@ -5534,14 +6567,14 @@ function normalizeRefForBackend(ref, field) {
5534
6567
  };
5535
6568
  }
5536
6569
  }
5537
- function normalizePaymentTiming$1(payment) {
6570
+ function normalizePaymentTiming(payment) {
5538
6571
  const { release: _release, ...rest } = payment;
5539
6572
  return {
5540
6573
  ...rest,
5541
6574
  timing: payment.timing ?? payment.release ?? { kind: "instant" }
5542
6575
  };
5543
6576
  }
5544
- function mapOk$1(result, f) {
6577
+ function mapOk(result, f) {
5545
6578
  if (!result.ok) return result;
5546
6579
  try {
5547
6580
  return {
@@ -5614,120 +6647,157 @@ function makeSystemMethods(deps) {
5614
6647
  return { health: (nonce, options) => runIfActive(options?.signal, "system.health", () => deps.convexCall.query(healthQuery, { nonce })) };
5615
6648
  }
5616
6649
  //#endregion
5617
- //#region src/surface/sub-accounts-deps.ts
5618
- var SubAccountsDepsTag = class extends Context.Service()("@capxul/sdk/SubAccountsDeps") {};
5619
- function subAccountsDepsLayer(deps) {
5620
- return Layer.succeed(SubAccountsDepsTag, deps);
5621
- }
5622
- function createSubAccountProgram(accountId, name) {
5623
- return Effect.gen(function* () {
5624
- const deps = yield* SubAccountsDepsTag;
5625
- const created = yield* deps.subAccountPort.create({
5626
- accountId,
5627
- name
5628
- }).pipe(Effect.tapError((error) => Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, "create", error.publicCode))), Effect.mapError((error) => error.publicError));
5629
- yield* Effect.promise(() => emitSubAccountCreated(deps.telemetry, created.id));
5630
- return created;
5631
- });
5632
- }
5633
- function getSubAccountProgram(subAccountId) {
5634
- return Effect.gen(function* () {
5635
- return yield* (yield* SubAccountsDepsTag).subAccountPort.get({ subAccountId }).pipe(Effect.mapError((error) => error.publicError));
5636
- });
5637
- }
5638
- function listSubAccountsProgram(accountId) {
5639
- return Effect.gen(function* () {
5640
- return yield* (yield* SubAccountsDepsTag).subAccountPort.list({ accountId }).pipe(Effect.mapError((error) => error.publicError));
5641
- });
5642
- }
5643
- function renameSubAccountProgram(subAccountId, name) {
5644
- return Effect.gen(function* () {
5645
- const deps = yield* SubAccountsDepsTag;
5646
- const renamed = yield* deps.subAccountPort.rename({
5647
- subAccountId,
5648
- name
5649
- }).pipe(Effect.tapError((error) => Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, "rename", error.publicCode))), Effect.mapError((error) => error.publicError));
5650
- yield* Effect.promise(() => emitSubAccountRenamed(deps.telemetry, renamed.id));
5651
- return renamed;
5652
- });
6650
+ //#region src/contract/permission.ts
6651
+ const permissionContract = { read: makeFunctionReference(CAPXUL_FUNCTIONS["permission/queries"].read) };
6652
+ //#endregion
6653
+ //#region src/surface/permissions.ts
6654
+ function isAborted(signal) {
6655
+ return signal?.aborted === true;
5653
6656
  }
5654
- function deleteSubAccountProgram(subAccountId) {
5655
- return Effect.gen(function* () {
5656
- const deps = yield* SubAccountsDepsTag;
5657
- yield* deps.subAccountPort.delete({ subAccountId }).pipe(Effect.tapError((error) => Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, "delete", error.publicCode))), Effect.mapError((error) => error.publicError));
5658
- yield* Effect.promise(() => emitSubAccountDeleted(deps.telemetry, subAccountId));
5659
- });
6657
+ function fail$1(cause, operation) {
6658
+ return {
6659
+ ok: false,
6660
+ error: cause instanceof CapxulError ? cause : Errors.providerError("wallet-signer", operation, cause)
6661
+ };
5660
6662
  }
5661
- function transferSubAccountProgram(input) {
5662
- return Effect.gen(function* () {
5663
- const deps = yield* SubAccountsDepsTag;
5664
- yield* Effect.promise(() => emitTransferRequested(deps.telemetry, {
5665
- amount: input.amount,
5666
- from: input.from,
5667
- to: input.to
5668
- }));
5669
- return yield* deps.subAccountPort.transfer(input).pipe(Effect.tapError((error) => Effect.promise(() => emitTransferFailed(deps.telemetry, error.publicCode))), Effect.mapError((error) => error.publicError));
5670
- });
6663
+ async function execute(deps, orgId, command, signal) {
6664
+ if (isAborted(signal)) return {
6665
+ ok: false,
6666
+ error: Errors.cancelled({ operation: "permissions" })
6667
+ };
6668
+ if (deps.actor === void 0 || deps.chainId === void 0 || deps.signer === void 0) return {
6669
+ ok: false,
6670
+ error: Errors.notImplemented("permissions", "executionComposition")
6671
+ };
6672
+ const session = deps.actor.authSession();
6673
+ if (session === null) return {
6674
+ ok: false,
6675
+ error: Errors.notAuthenticated()
6676
+ };
6677
+ let signerAddress;
6678
+ try {
6679
+ signerAddress = await deps.signer.getAddress();
6680
+ } catch (cause) {
6681
+ return fail$1(cause, "getAddress");
6682
+ }
6683
+ const executionFns = deps.executionFunctions ?? moneyExecutionContract;
6684
+ const prepared = await runIfActive(signal, "permissions.prepareExecution", () => deps.convexCall.action(executionFns.preparePermissionExecution, { input: {
6685
+ orgId,
6686
+ signerAddress,
6687
+ command
6688
+ } }));
6689
+ if (!prepared.ok) return prepared;
6690
+ const expectedSafe = deriveCapxulSafeAddress({ email: session.email });
6691
+ if (prepared.value.chainId !== deps.chainId || prepared.value.signerAddress.toLowerCase() !== signerAddress.toLowerCase() || prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase() || prepared.value.operation !== command.operation || prepared.value.orgId !== orgId || JSON.stringify(prepared.value.command) !== JSON.stringify(command)) return {
6692
+ ok: false,
6693
+ error: Errors.invalidInput("permission", "prepared authority mismatch")
6694
+ };
6695
+ if (isAborted(signal)) return {
6696
+ ok: false,
6697
+ error: Errors.cancelled({ operation: "permissions" })
6698
+ };
6699
+ let signature;
6700
+ try {
6701
+ signature = await deps.signer.signUserOpHash(prepared.value.digest);
6702
+ } catch (cause) {
6703
+ return fail$1(cause, "signUserOpHash");
6704
+ }
6705
+ if (isAborted(signal)) return {
6706
+ ok: false,
6707
+ error: Errors.cancelled({ operation: "permissions" })
6708
+ };
6709
+ return runIfActive(void 0, "permissions.submitExecution", () => deps.convexCall.action(executionFns.submitPermissionExecution, { input: {
6710
+ executionId: prepared.value.executionId,
6711
+ signature
6712
+ } }));
5671
6713
  }
5672
- //#endregion
5673
- //#region src/surface/sub-accounts.ts
5674
- function makeSubAccountsMethods(deps) {
5675
- const layer = subAccountsDepsLayer(deps);
6714
+ function makePermissionMethods(deps, orgId) {
6715
+ const reads = deps.permissionFunctions ?? permissionContract;
5676
6716
  return {
5677
- async create(accountId, input, options) {
5678
- if (options?.signal?.aborted) return {
5679
- ok: false,
5680
- error: Errors.cancelled({ operation: "subAccounts.create" })
5681
- };
5682
- return toCapxulResult(createSubAccountProgram(accountId, input.name), layer);
5683
- },
5684
- async get(subAccountId, options) {
5685
- if (options?.signal?.aborted) return {
5686
- ok: false,
5687
- error: Errors.cancelled({ operation: "subAccounts.get" })
5688
- };
5689
- return toCapxulResult(getSubAccountProgram(subAccountId), layer);
5690
- },
5691
- async list(accountId, options) {
5692
- if (options?.signal?.aborted) return {
5693
- ok: false,
5694
- error: Errors.cancelled({ operation: "subAccounts.list" })
5695
- };
5696
- return toCapxulResult(listSubAccountsProgram(accountId), layer);
5697
- },
5698
- async rename(subAccountId, name, options) {
5699
- if (options?.signal?.aborted) return {
5700
- ok: false,
5701
- error: Errors.cancelled({ operation: "subAccounts.rename" })
6717
+ create: (input, options) => execute(deps, orgId, {
6718
+ operation: "create",
6719
+ ...input
6720
+ }, options?.signal),
6721
+ change: (input, options) => execute(deps, orgId, {
6722
+ operation: "change",
6723
+ ...input
6724
+ }, options?.signal),
6725
+ assign: (input, options) => execute(deps, orgId, {
6726
+ operation: "assign",
6727
+ ...input
6728
+ }, options?.signal),
6729
+ revoke: (input, options) => execute(deps, orgId, {
6730
+ operation: "revoke",
6731
+ ...input
6732
+ }, options?.signal),
6733
+ replace: (input, options) => execute(deps, orgId, {
6734
+ operation: "replace",
6735
+ ...input
6736
+ }, options?.signal),
6737
+ list: (options) => runIfActive(options?.signal, "permissions.list", () => deps.convexCall.query(reads.read, { orgId })),
6738
+ get: async (permissionId, options) => {
6739
+ const listed = await runIfActive(options?.signal, "permissions.get", () => deps.convexCall.query(reads.read, { orgId }));
6740
+ if (!listed.ok) return listed;
6741
+ return {
6742
+ ok: true,
6743
+ value: listed.value.permissions.find((row) => row.permissionId === permissionId) ?? null
5702
6744
  };
5703
- return toCapxulResult(renameSubAccountProgram(subAccountId, name), layer);
5704
- },
5705
- async delete(subAccountId, options) {
5706
- if (options?.signal?.aborted) return {
6745
+ }
6746
+ };
6747
+ }
6748
+ //#endregion
6749
+ //#region src/surface/organization-payments.ts
6750
+ function executionDependencies(input) {
6751
+ return input.actor === void 0 || input.chainId === void 0 || input.signer === void 0 ? null : {
6752
+ actor: input.actor,
6753
+ chainId: input.chainId,
6754
+ convexCall: input.convexCall,
6755
+ functions: moneyExecutionContract,
6756
+ signer: input.signer
6757
+ };
6758
+ }
6759
+ function makeOrganizationPaymentsMethods(deps, orgId) {
6760
+ const execute = async (input, signal) => {
6761
+ const execution = executionDependencies(deps);
6762
+ if (execution === null) return {
6763
+ ok: false,
6764
+ error: Errors.notImplemented("organizationPayments", "executionComposition")
6765
+ };
6766
+ const result = await executeOrganizationPayment(execution, {
6767
+ orgId,
6768
+ permissionId: input.permissionId,
6769
+ requestKey: input.requestKey,
6770
+ items: input.items,
6771
+ ...input.lineage === void 0 ? {} : { lineage: input.lineage }
6772
+ }, signal);
6773
+ return result.ok ? {
6774
+ ok: true,
6775
+ value: result.value.payments.map((payment) => normalizePaymentTiming(payment))
6776
+ } : result;
6777
+ };
6778
+ return {
6779
+ pay: async (input, options) => {
6780
+ const { permissionId, requestKey, lineage, ...item } = input;
6781
+ const result = await execute({
6782
+ permissionId,
6783
+ requestKey,
6784
+ items: [item],
6785
+ ...lineage === void 0 ? {} : { lineage }
6786
+ }, options?.signal);
6787
+ if (!result.ok) return result;
6788
+ const payment = result.value[0];
6789
+ return payment === void 0 ? {
5707
6790
  ok: false,
5708
- error: Errors.cancelled({ operation: "subAccounts.delete" })
6791
+ error: Errors.unknown()
6792
+ } : {
6793
+ ok: true,
6794
+ value: payment
5709
6795
  };
5710
- return toCapxulResult(deleteSubAccountProgram(subAccountId), layer);
5711
6796
  },
5712
- async transfer(input, options) {
5713
- if (options?.signal?.aborted) return {
5714
- ok: false,
5715
- error: Errors.cancelled({ operation: "subAccounts.transfer" })
5716
- };
5717
- return toCapxulResult(transferSubAccountProgram(input), layer);
5718
- }
6797
+ payBatch: (input, options) => execute(input, options?.signal)
5719
6798
  };
5720
6799
  }
5721
6800
  //#endregion
5722
- //#region src/contract/payroll.ts
5723
- const payrollContract = {
5724
- add: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].add),
5725
- list: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].list),
5726
- update: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].update),
5727
- remove: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].remove),
5728
- run: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].run)
5729
- };
5730
- //#endregion
5731
6801
  //#region src/surface/_shared/org-telemetry.ts
5732
6802
  /** Extract the domain from an email for telemetry (never the local part / PII). */
5733
6803
  function emailDomain$1(email) {
@@ -5823,59 +6893,11 @@ function isOrgTelemetryDebugEnabled() {
5823
6893
  return globalThis.process?.env?.CAPXUL_DEBUG_TELEMETRY === "1";
5824
6894
  }
5825
6895
  //#endregion
5826
- //#region src/domain/org/spend-gate.ts
5827
- function evaluateSpendGate(input) {
5828
- if (!input.activeMember) return reject("not_member", Errors.invalidInput("member", "you are not an active member"));
5829
- if (!recipientAllowed(input.recipients, input.recipient)) return reject("invalid_recipient", Errors.invalidRecipient("recipient is not allowed by this role"));
5830
- if (!subAccountAllowed(input.subAccounts, input.subAccountId)) return reject("wrong_envelope", Errors.invalidInput("subAccountId", "sub-account not in scope for this role"));
5831
- const amount = parseRaw(input.amountRaw, "amountRaw");
5832
- const balance = parseRaw(input.subAccountBalanceRaw, "subAccountBalanceRaw");
5833
- if (amount > balance) return reject("insufficient_subaccount_balance", Errors.insufficientBalance(input.currency, balance.toString(10), amount.toString(10)));
5834
- const perTxCap = parseOptionalRaw(input.perTxCapRaw, "perTxCapRaw");
5835
- if (perTxCap !== null && amount > perTxCap) return reject("over_cap", Errors.insufficientBalance("role per-transaction cap", perTxCap.toString(10), amount.toString(10)));
5836
- const perDayCap = parseOptionalRaw(input.perDayCapRaw, "perDayCapRaw");
5837
- if (perDayCap !== null) {
5838
- const remaining = perDayCap - (parseOptionalRaw(input.spentTodayRaw, "spentTodayRaw") ?? 0n);
5839
- if (remaining < amount) return reject("daily_cap_exhausted", Errors.insufficientBalance("role daily cap", remaining.toString(10), amount.toString(10)));
5840
- }
5841
- return { ok: true };
5842
- }
5843
- function reject(reason, error) {
5844
- return {
5845
- ok: false,
5846
- reason,
5847
- error
5848
- };
5849
- }
5850
- function recipientAllowed(recipients, recipient) {
5851
- if (recipients === "anyone") return true;
5852
- const normalized = String(recipient).toLowerCase();
5853
- return recipients.some((allowed) => String(allowed).toLowerCase() === normalized);
5854
- }
5855
- function subAccountAllowed(scope, subAccountId) {
5856
- if (scope.scope === "all") return true;
5857
- return scope.subAccountIds.includes(subAccountId);
5858
- }
5859
- function parseOptionalRaw(value, field) {
5860
- if (value === null || value === void 0) return null;
5861
- return parseRaw(value, field);
5862
- }
5863
- function parseRaw(value, field) {
5864
- if (!/^[0-9]+$/.test(value)) throw Errors.invalidInput(field, "must be a non-negative integer string");
5865
- return BigInt(value);
5866
- }
5867
- //#endregion
5868
6896
  //#region src/surface/org-deps.ts
5869
6897
  var OrgDepsTag = class extends Context.Service()("@capxul/sdk/OrgDeps") {};
5870
6898
  function orgDepsLayer(deps) {
5871
6899
  return Layer.succeed(OrgDepsTag, deps);
5872
6900
  }
5873
- function isHermeticOrgDeps(deps) {
5874
- return deps.orgPort === void 0 && deps.orgRolesDeploymentPort === void 0 && deps.orgSpendPort === void 0;
5875
- }
5876
- function missingLiveOrgDep(portName) {
5877
- return Errors.invalidInput("orgDeps", `${portName} is required in live org mode`);
5878
- }
5879
6901
  /** Zero `Money` in the USDX-backed display currency (a fresh Org's treasury). */
5880
6902
  function zeroMoney() {
5881
6903
  return fromWei("0", 6, "USD");
@@ -5932,14 +6954,8 @@ function recipientsFromConfig(toRecipients) {
5932
6954
  if (toRecipients === void 0 || toRecipients === "anyone") return toRecipients;
5933
6955
  return toRecipients.map((recipient) => toAddress(recipient));
5934
6956
  }
5935
- function subAccountsFromConfig(subAccounts) {
5936
- if (subAccounts === void 0) return void 0;
5937
- if (subAccounts.scope === "all") return { scope: "all" };
5938
- return { scope: subAccounts.scope.map((subAccountId) => toSubAccountId(subAccountId)) };
5939
- }
5940
6957
  function roleDefinitionFromConfig(definition) {
5941
6958
  const toRecipients = recipientsFromConfig(definition.spend?.toRecipients);
5942
- const subAccounts = subAccountsFromConfig(definition.subAccounts);
5943
6959
  return {
5944
6960
  label: definition.label,
5945
6961
  ...definition.spend === void 0 ? {} : { spend: {
@@ -5947,7 +6963,6 @@ function roleDefinitionFromConfig(definition) {
5947
6963
  ...definition.spend.perDay === void 0 ? {} : { perDay: moneyFromConfig(definition.spend.perDay) },
5948
6964
  ...toRecipients === void 0 ? {} : { toRecipients }
5949
6965
  } },
5950
- ...subAccounts === void 0 ? {} : { subAccounts },
5951
6966
  ...definition.canManageMembers === void 0 ? {} : { canManageMembers: definition.canManageMembers },
5952
6967
  ...definition.canManageRoles === void 0 ? {} : { canManageRoles: definition.canManageRoles }
5953
6968
  };
@@ -5973,36 +6988,6 @@ function hermeticMember(input) {
5973
6988
  revokeTxHash: input.revokeTxHash ?? null
5974
6989
  };
5975
6990
  }
5976
- function hermeticSpendAuthority(input) {
5977
- return {
5978
- activeMember: true,
5979
- subAccountBalanceRaw: "100000000000",
5980
- recipients: "anyone",
5981
- subAccounts: {
5982
- scope: "only",
5983
- subAccountIds: [input.from]
5984
- },
5985
- perTxCapRaw: "25000000000",
5986
- perDayCapRaw: "100000000000",
5987
- spentTodayRaw: "0",
5988
- role: "Finance Manager"
5989
- };
5990
- }
5991
- function spendGateInput(input) {
5992
- return {
5993
- activeMember: input.authority.activeMember,
5994
- subAccountId: input.spend.from,
5995
- subAccountBalanceRaw: input.authority.subAccountBalanceRaw,
5996
- amountRaw: input.amountRaw,
5997
- currency: input.currency,
5998
- recipient: input.spend.to,
5999
- recipients: input.authority.recipients,
6000
- subAccounts: input.authority.subAccounts,
6001
- ...input.authority.perTxCapRaw === void 0 ? {} : { perTxCapRaw: input.authority.perTxCapRaw },
6002
- ...input.authority.perDayCapRaw === void 0 ? {} : { perDayCapRaw: input.authority.perDayCapRaw },
6003
- ...input.authority.spentTodayRaw === void 0 ? {} : { spentTodayRaw: input.authority.spentTodayRaw }
6004
- };
6005
- }
6006
6991
  function createOrgProgram(input) {
6007
6992
  return Effect.gen(function* () {
6008
6993
  const deps = yield* OrgDepsTag;
@@ -6094,14 +7079,6 @@ function listRolesProgram(orgId) {
6094
7079
  return startupRoleViews(orgId);
6095
7080
  });
6096
7081
  }
6097
- function deployRolesProgram(orgId) {
6098
- return Effect.gen(function* () {
6099
- const deps = yield* OrgDepsTag;
6100
- if (deps.orgRolesDeploymentPort !== void 0) return (yield* deps.orgRolesDeploymentPort.deployRoles({ orgId }).pipe(Effect.mapError((error) => error.publicError))).roles;
6101
- if (!isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgRolesDeploymentPort"));
6102
- return startupRoleViews(orgId);
6103
- });
6104
- }
6105
7082
  function listMembersProgram(orgId) {
6106
7083
  return Effect.gen(function* () {
6107
7084
  const deps = yield* OrgDepsTag;
@@ -6137,188 +7114,6 @@ function detectAndAcceptPendingInvitationsProgram() {
6137
7114
  return { matched: [] };
6138
7115
  });
6139
7116
  }
6140
- function assignRoleProgram(orgId, input) {
6141
- return Effect.gen(function* () {
6142
- const deps = yield* OrgDepsTag;
6143
- if (deps.orgRolesDeploymentPort !== void 0) return yield* deps.orgRolesDeploymentPort.grantRole({
6144
- orgId,
6145
- input
6146
- }).pipe(Effect.mapError((error) => error.publicError));
6147
- if (!isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgRolesDeploymentPort"));
6148
- return hermeticMember({
6149
- orgId,
6150
- email: "member@example.com",
6151
- role: input.role,
6152
- status: "active",
6153
- personalSafeAddress: input.memberSafeAddress,
6154
- grantTxHash: `0x${"0".repeat(64)}`
6155
- });
6156
- });
6157
- }
6158
- function removeMemberProgram(orgId, input) {
6159
- return Effect.gen(function* () {
6160
- const deps = yield* OrgDepsTag;
6161
- if (deps.orgRolesDeploymentPort !== void 0) return yield* deps.orgRolesDeploymentPort.revokeRole({
6162
- orgId,
6163
- input
6164
- }).pipe(Effect.mapError((error) => error.publicError));
6165
- if (!isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgRolesDeploymentPort"));
6166
- });
6167
- }
6168
- /**
6169
- * Build a leak-safe settled `Payment` for an org spend (G4 · #547). NO `txHash`
6170
- * / userOp / Safe internals and NO raw recipient address ever reach this record
6171
- * — only the validated recipient ref label + the committed `documentHash`.
6172
- */
6173
- function leakSafeOrgPayment(input) {
6174
- const now = Date.now();
6175
- const id = `payment_${toHexSeed(`${input.orgId}:${input.to}:${input.amount.value}:${input.index}`)}`;
6176
- const money = {
6177
- currency: String(input.amount.currency),
6178
- value: input.amount.value,
6179
- decimals: input.amount.decimals
6180
- };
6181
- return {
6182
- id,
6183
- status: "settled",
6184
- amount: money,
6185
- paymentType: input.paymentType,
6186
- recipient: {
6187
- kind: "email",
6188
- label: input.to
6189
- },
6190
- documents: input.documentHash === void 0 ? [] : [{
6191
- documentHash: input.documentHash,
6192
- kind: input.paymentType === "payroll" ? "payslip" : "memo"
6193
- }],
6194
- timing: { kind: "instant" },
6195
- released: money,
6196
- availableToClaim: {
6197
- ...money,
6198
- value: "0"
6199
- },
6200
- createdAt: now,
6201
- updatedAt: now
6202
- };
6203
- }
6204
- /** Resolve authority + run the spend gate for one org spend run (G4 · #547). */
6205
- function gateOneRun(input) {
6206
- return Effect.gen(function* () {
6207
- const amountRaw = yield* Effect.try({
6208
- try: () => toWei(input.amount),
6209
- catch: (cause) => Errors.invalidInput("amount", cause instanceof Error ? cause.message : "invalid money")
6210
- });
6211
- const currency = String(input.amount.currency);
6212
- const spendShaped = {
6213
- from: input.from,
6214
- to: toAddress(`0x${"0".repeat(40)}`),
6215
- amount: input.amount
6216
- };
6217
- const authority = input.deps.orgSpendPort === void 0 ? hermeticSpendAuthority(spendShaped) : yield* input.deps.orgSpendPort.readSpendAuthority({
6218
- orgId: input.orgId,
6219
- input: spendShaped,
6220
- amountRaw
6221
- }).pipe(Effect.mapError((error) => error.publicError));
6222
- const accumulated = BigInt(input.accumulatedRaw ?? "0");
6223
- const baseGateInput = spendGateInput({
6224
- authority,
6225
- spend: spendShaped,
6226
- amountRaw,
6227
- currency
6228
- });
6229
- const decision = yield* Effect.try({
6230
- try: () => evaluateSpendGate({
6231
- ...baseGateInput,
6232
- recipient: input.to,
6233
- subAccountBalanceRaw: subtractNonNegative(baseGateInput.subAccountBalanceRaw, accumulated),
6234
- spentTodayRaw: (BigInt(authority.spentTodayRaw ?? "0") + accumulated).toString(10)
6235
- }),
6236
- catch: (cause) => isCapxulError(cause) ? cause : Errors.unknown(cause)
6237
- });
6238
- if (!decision.ok) return yield* Effect.fail(decision.error);
6239
- return {
6240
- authority,
6241
- amountRaw
6242
- };
6243
- });
6244
- }
6245
- /** Subtract `delta` from a raw amount, flooring at zero (never negative). */
6246
- function subtractNonNegative(raw, delta) {
6247
- const remaining = BigInt(raw) - delta;
6248
- return (remaining < 0n ? 0n : remaining).toString(10);
6249
- }
6250
- function spendViaPaymentsProgram(orgId, input) {
6251
- return Effect.gen(function* () {
6252
- const deps = yield* OrgDepsTag;
6253
- if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
6254
- const to = yield* Effect.try({
6255
- try: () => refToRecipientString(input.to),
6256
- catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
6257
- });
6258
- const gated = yield* gateOneRun({
6259
- deps,
6260
- orgId,
6261
- from: input.from,
6262
- to,
6263
- amount: input.amount
6264
- });
6265
- const paymentType = input.paymentType ?? "unspecified";
6266
- if (deps.orgSpendPort?.submitSpendViaPayments !== void 0) return yield* deps.orgSpendPort.submitSpendViaPayments({
6267
- orgId,
6268
- input,
6269
- amountRaw: gated.amountRaw,
6270
- authority: gated.authority
6271
- }).pipe(Effect.mapError((error) => error.publicError));
6272
- return leakSafeOrgPayment({
6273
- orgId,
6274
- to,
6275
- amount: input.amount,
6276
- paymentType,
6277
- index: 0
6278
- });
6279
- });
6280
- }
6281
- function batchPayrollProgram(orgId, input) {
6282
- return Effect.gen(function* () {
6283
- const deps = yield* OrgDepsTag;
6284
- if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
6285
- if (input.runs.length === 0) return yield* Effect.fail(Errors.invalidInput("runs", "payroll batch must include at least one run"));
6286
- const gated = [];
6287
- const recipients = yield* Effect.try({
6288
- try: () => input.runs.map((run) => refToRecipientString(run.to)),
6289
- catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
6290
- });
6291
- let accumulatedRaw = 0n;
6292
- for (const [index, run] of input.runs.entries()) {
6293
- const result = yield* gateOneRun({
6294
- deps,
6295
- orgId,
6296
- from: input.from,
6297
- to: recipients[index],
6298
- amount: run.amount,
6299
- accumulatedRaw: accumulatedRaw.toString(10)
6300
- });
6301
- accumulatedRaw += BigInt(result.amountRaw);
6302
- gated.push(result);
6303
- }
6304
- if (deps.orgSpendPort?.submitBatchPayroll !== void 0) return yield* deps.orgSpendPort.submitBatchPayroll({
6305
- orgId,
6306
- from: input.from,
6307
- runs: input.runs.map((run, index) => ({
6308
- run,
6309
- amountRaw: gated[index].amountRaw
6310
- })),
6311
- authorities: gated.map((g) => g.authority)
6312
- }).pipe(Effect.mapError((error) => error.publicError));
6313
- return input.runs.map((run, index) => leakSafeOrgPayment({
6314
- orgId,
6315
- to: recipients[index],
6316
- amount: run.amount,
6317
- paymentType: "payroll",
6318
- index
6319
- }));
6320
- });
6321
- }
6322
7117
  function listOrgsProgram() {
6323
7118
  return Effect.gen(function* () {
6324
7119
  const deps = yield* OrgDepsTag;
@@ -6405,18 +7200,13 @@ function isRetryableOrganizationSetupFailure(error) {
6405
7200
  //#endregion
6406
7201
  //#region src/surface/org.ts
6407
7202
  /**
6408
- * Org method surface (canon §C2/§C3, D13). S1 (#274) wires `createOrg` /
6409
- * `orgs` / `treasury` to their Effect programs (`org-deps.ts`); the S2→S4
6410
- * member/role/spend verbs stay `Errors.notImplemented("org", "<verb>")` until
6411
- * their slices land. The entity-scoped bundle is constructed per `org(orgId)`
6412
- * call (D13 — explicit scoping, no shared mutable "active org" state); the
6413
- * closed-over `orgId` is the only entity reference.
7203
+ * Org method surface (canon §C2/§C3, D13). The entity-scoped bundle is
7204
+ * constructed for each `org(orgId)` call. It has no shared mutable active-Org
7205
+ * state. The closed-over `orgId` is its only entity reference.
6414
7206
  */
6415
7207
  function makeOrgMethods(deps) {
6416
7208
  const layer = orgDepsLayer({
6417
7209
  ...deps.orgPort === void 0 ? {} : { orgPort: deps.orgPort },
6418
- ...deps.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: deps.orgRolesDeploymentPort },
6419
- ...deps.orgSpendPort === void 0 ? {} : { orgSpendPort: deps.orgSpendPort },
6420
7210
  ...deps.chainId === void 0 ? {} : { chainId: deps.chainId },
6421
7211
  ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
6422
7212
  });
@@ -6547,13 +7337,6 @@ function makeOrgMethods(deps) {
6547
7337
  });
6548
7338
  return toCapxulResult(listRolesProgram(orgId), layer);
6549
7339
  },
6550
- deployRoles(_options) {
6551
- if (_options?.signal?.aborted) return Promise.resolve({
6552
- ok: false,
6553
- error: Errors.cancelled({ operation: "org.deployRoles" })
6554
- });
6555
- return toCapxulResult(deployRolesProgram(orgId), layer);
6556
- },
6557
7340
  invite(_input, _options) {
6558
7341
  if (_options?.signal?.aborted) return Promise.resolve({
6559
7342
  ok: false,
@@ -6561,34 +7344,6 @@ function makeOrgMethods(deps) {
6561
7344
  });
6562
7345
  return toCapxulResult(inviteMemberProgram(orgId, _input), layer);
6563
7346
  },
6564
- removeMember(_input, _options) {
6565
- if (_options?.signal?.aborted) return Promise.resolve({
6566
- ok: false,
6567
- error: Errors.cancelled({ operation: "org.removeMember" })
6568
- });
6569
- return toCapxulResult(removeMemberProgram(orgId, _input), layer);
6570
- },
6571
- assignRole(_input, _options) {
6572
- if (_options?.signal?.aborted) return Promise.resolve({
6573
- ok: false,
6574
- error: Errors.cancelled({ operation: "org.assignRole" })
6575
- });
6576
- return toCapxulResult(assignRoleProgram(orgId, _input), layer);
6577
- },
6578
- spendViaPayments(_input, _options) {
6579
- if (_options?.signal?.aborted) return Promise.resolve({
6580
- ok: false,
6581
- error: Errors.cancelled({ operation: "org.spendViaPayments" })
6582
- });
6583
- return toCapxulResult(spendViaPaymentsProgram(orgId, _input), layer);
6584
- },
6585
- batchPayroll(_input, _options) {
6586
- if (_options?.signal?.aborted) return Promise.resolve({
6587
- ok: false,
6588
- error: Errors.cancelled({ operation: "org.batchPayroll" })
6589
- });
6590
- return toCapxulResult(batchPayrollProgram(orgId, _input), layer);
6591
- },
6592
7347
  auditLog(_options) {
6593
7348
  if (_options?.signal?.aborted) return Promise.resolve({
6594
7349
  ok: false,
@@ -6599,114 +7354,334 @@ function makeOrgMethods(deps) {
6599
7354
  error: Errors.notImplemented("organizationAuditLog", "list")
6600
7355
  });
6601
7356
  },
6602
- payroll: convexCall === void 0 ? makeNotImplementedPayrollMethods() : makePayrollMethods({
6603
- orgId: String(orgId),
6604
- convexCall
6605
- })
7357
+ permissions: convexCall === void 0 ? makeNotImplementedPermissionMethods() : makePermissionMethods({
7358
+ convexCall,
7359
+ ...deps.actor === void 0 ? {} : { actor: deps.actor },
7360
+ ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
7361
+ ...deps.signer === void 0 ? {} : { signer: deps.signer }
7362
+ }, String(orgId)),
7363
+ payments: convexCall === void 0 ? makeNotImplementedOrganizationPaymentsMethods() : makeOrganizationPaymentsMethods({
7364
+ convexCall,
7365
+ ...deps.actor === void 0 ? {} : { actor: deps.actor },
7366
+ ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
7367
+ ...deps.signer === void 0 ? {} : { signer: deps.signer }
7368
+ }, String(orgId))
6606
7369
  };
6607
7370
  }
6608
7371
  };
6609
7372
  }
6610
- function makePayrollMethods(deps) {
6611
- const fns = payrollContract;
7373
+ function makeNotImplementedPermissionMethods() {
6612
7374
  return {
6613
- roster: {
6614
- add: async (input, options) => {
6615
- const employee = normalizeRefForBackend$1(input.employee, "employee");
6616
- if (!employee.ok) return employee;
6617
- return mapOk(runIfActive(options?.signal, "payroll.roster.add", () => deps.convexCall.mutation(fns.add, {
6618
- orgId: deps.orgId,
6619
- employee: employee.value,
6620
- amount: input.amount,
6621
- timing: input.timing,
6622
- payslipTemplate: toPayrollTemplate(input.payslipTemplate)
6623
- })), mapPayrollRosterLine);
6624
- },
6625
- list: (options) => mapOk(runIfActive(options?.signal, "payroll.roster.list", () => deps.convexCall.query(fns.list, { orgId: deps.orgId })), (lines) => lines.map(mapPayrollRosterLine)),
6626
- update: async (rosterLineId, input, options) => {
6627
- const employee = input.employee === void 0 ? void 0 : normalizeRefForBackend$1(input.employee, "employee");
6628
- if (employee !== void 0 && !employee.ok) return employee;
6629
- return mapOk(runIfActive(options?.signal, "payroll.roster.update", () => deps.convexCall.mutation(fns.update, {
6630
- orgId: deps.orgId,
6631
- rosterLineId,
6632
- ...employee === void 0 ? {} : { employee: employee.value },
6633
- ...input.amount === void 0 ? {} : { amount: input.amount },
6634
- ...input.timing === void 0 ? {} : { timing: input.timing },
6635
- ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: toPayrollTemplate(input.payslipTemplate) }
6636
- })), mapPayrollRosterLine);
6637
- },
6638
- remove: (rosterLineId, options) => mapOk(runIfActive(options?.signal, "payroll.roster.remove", () => deps.convexCall.mutation(fns.remove, {
6639
- orgId: deps.orgId,
6640
- rosterLineId
6641
- })), mapPayrollRosterLine)
6642
- },
6643
- run: (input, options) => mapOk(runIfActive(options?.signal, "payroll.run", () => deps.convexCall.mutation(fns.run, {
6644
- orgId: deps.orgId,
6645
- period: input.period,
6646
- from: String(input.from)
6647
- })), (run) => run.payments.map(normalizePaymentTiming))
7375
+ create: permissionExecutionUnavailable,
7376
+ change: permissionExecutionUnavailable,
7377
+ assign: permissionExecutionUnavailable,
7378
+ revoke: permissionExecutionUnavailable,
7379
+ replace: permissionExecutionUnavailable,
7380
+ list: permissionExecutionUnavailable,
7381
+ get: permissionExecutionUnavailable
7382
+ };
7383
+ }
7384
+ function makeNotImplementedOrganizationPaymentsMethods() {
7385
+ return {
7386
+ pay: organizationPaymentExecutionUnavailable,
7387
+ payBatch: organizationPaymentExecutionUnavailable
6648
7388
  };
6649
7389
  }
6650
- function makeNotImplementedPayrollMethods() {
7390
+ const permissionExecutionUnavailable = () => Promise.resolve({
7391
+ ok: false,
7392
+ error: Errors.notImplemented("permissions", "executionComposition")
7393
+ });
7394
+ const organizationPaymentExecutionUnavailable = () => Promise.resolve({
7395
+ ok: false,
7396
+ error: Errors.notImplemented("organizationPayments", "executionComposition")
7397
+ });
7398
+ //#endregion
7399
+ //#region src/contract/holdings.ts
7400
+ const holdingsContract = { current: makeFunctionReference(CAPXUL_FUNCTIONS["holdings/actions"].current) };
7401
+ //#endregion
7402
+ //#region src/surface/holdings.ts
7403
+ function makeHoldingsMethods(deps) {
7404
+ const functions = deps.functions ?? holdingsContract;
7405
+ return { current: (input, options) => runIfActive(options?.signal, "holdings.current", () => deps.convexCall.action(functions.current, input?.actor?.kind === "organization" ? { actor: {
7406
+ kind: "organization",
7407
+ orgId: input.actor.organizationId
7408
+ } } : {})) };
7409
+ }
7410
+ //#endregion
7411
+ //#region src/surface/factory.ts
7412
+ function detectAuthCacheAdapter() {
7413
+ const globalAny = globalThis;
7414
+ if (globalAny.window?.localStorage !== void 0) return new BrowserAuthCacheAdapter(globalAny.window.localStorage);
7415
+ return new InMemoryAuthCacheAdapter();
7416
+ }
7417
+ //#endregion
7418
+ //#region src/observation.ts
7419
+ const SDK_VERSION = version;
7420
+ /** Stable PostHog event used for typed failures that are expected product outcomes. */
7421
+ const CAPXUL_SDK_EXPECTED_OUTCOME_EVENT = "capxul_sdk_expected_outcome";
7422
+ /**
7423
+ * Adapt the host's already-initialized PostHog-like client. This function does
7424
+ * not import, initialize, configure, or own PostHog.
7425
+ */
7426
+ function postHogFailureObservation(policy, fixedSnapshot) {
7427
+ const prepare = (failure) => {
7428
+ const callStartSnapshot = readFailureInvocationSnapshot(failure) ?? fixedSnapshot;
7429
+ const directSnapshot = callStartSnapshot === void 0 ? policy.snapshot() : void 0;
7430
+ if (!(callStartSnapshot?.active ?? directSnapshot?.active) || policy.client === null || policy.client === void 0) return;
7431
+ const safeFailure = sanitizeFailureObservation(failure);
7432
+ return [safeFailure, postHogProperties(safeFailure, callStartSnapshot?.context ?? directSnapshot?.context)];
7433
+ };
7434
+ const captureOperationFailure = (failure) => {
7435
+ const prepared = prepare(failure);
7436
+ if (prepared === void 0 || policy.client === null || policy.client === void 0) return;
7437
+ const [safeFailure, properties] = prepared;
7438
+ if (classifyOperationOutcome(safeFailure.errorKind) === "expected") {
7439
+ policy.deliver(() => policy.client.capture(CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, {
7440
+ ...properties,
7441
+ outcome_class: "expected"
7442
+ }));
7443
+ return;
7444
+ }
7445
+ policy.deliver(() => policy.client.capture("$exception", postHogExceptionProperties(safeFailure, properties)));
7446
+ };
7447
+ const captureException = (failure) => {
7448
+ const prepared = prepare(failure);
7449
+ if (prepared === void 0 || policy.client === null || policy.client === void 0) return;
7450
+ const [safeFailure, properties] = prepared;
7451
+ policy.deliver(() => policy.client.capture("$exception", postHogExceptionProperties(safeFailure, properties)));
7452
+ };
6651
7453
  return {
6652
- roster: {
6653
- add: () => missingConvexCall("payroll.roster.add"),
6654
- list: () => missingConvexCall("payroll.roster.list"),
6655
- update: () => missingConvexCall("payroll.roster.update"),
6656
- remove: () => missingConvexCall("payroll.roster.remove")
7454
+ resolveContext: () => {
7455
+ const snapshot = fixedSnapshot ?? policy.snapshot();
7456
+ if (!snapshot.active) return void 0;
7457
+ return snapshot.context ?? {};
6657
7458
  },
6658
- run: () => missingConvexCall("payroll.run")
7459
+ captureOperationFailure,
7460
+ captureException
6659
7461
  };
6660
7462
  }
6661
- function missingConvexCall(operation) {
6662
- return Promise.resolve({
6663
- ok: false,
6664
- error: Errors.providerError("convex", operation, "ConvexCallPort is required")
7463
+ function classifyOperationOutcome(kind) {
7464
+ return EXPECTED_OPERATION_OUTCOMES.has(kind) ? "expected" : "unexpected";
7465
+ }
7466
+ /** @internal Reports a factory-level typed failure without changing its identity. */
7467
+ function observeFailedResult(result, adapter, operation) {
7468
+ if (adapter !== void 0 && isFailedResult(result)) report(adapter, "operation", operation, result.error, resolveAdapterContext(adapter));
7469
+ return result;
7470
+ }
7471
+ function report(adapter, kind, operation, cause, invocationContext) {
7472
+ const operationName = normalizeOperation(operation);
7473
+ const kindName = normalizeErrorKind(errorKind(cause));
7474
+ const context = sanitizeObservationContext({
7475
+ ...invocationContext,
7476
+ ...isCapxulError(cause) && cause.correlationId !== void 0 ? { correlationId: cause.correlationId } : {}
7477
+ });
7478
+ const failure = markFailureInvocationSnapshot({
7479
+ exception: syntheticException(operationName, kindName),
7480
+ sdkVersion: SDK_VERSION,
7481
+ operation: operationName,
7482
+ errorKind: kindName,
7483
+ ...context === void 0 ? {} : { context }
7484
+ }, {
7485
+ active: invocationContext !== void 0,
7486
+ ...context === void 0 ? {} : { context }
6665
7487
  });
7488
+ try {
7489
+ ignoreDeliveryFailure(kind === "operation" ? adapter.captureOperationFailure(failure) : adapter.captureException(failure));
7490
+ } catch {}
6666
7491
  }
6667
- async function mapOk(resultOrPromise, f) {
6668
- const result = await resultOrPromise;
6669
- if (!result.ok) return result;
7492
+ function resolveAdapterContext(adapter) {
7493
+ try {
7494
+ return adapter.resolveContext?.();
7495
+ } catch {
7496
+ return;
7497
+ }
7498
+ }
7499
+ function ignoreDeliveryFailure(delivery) {
7500
+ if (!isPromiseLike(delivery)) return;
7501
+ try {
7502
+ Promise.resolve(delivery).catch(() => void 0);
7503
+ } catch {}
7504
+ }
7505
+ /**
7506
+ * Map an ALREADY-sanitized observation context to the snake_case PostHog
7507
+ * property keys. Shared by the failure boundary here and the host
7508
+ * success-telemetry seam (`telemetry/from-posthog.ts`) so both attach identical
7509
+ * correlation fields from one definition.
7510
+ */
7511
+ function observationContextProps(context) {
7512
+ const props = {};
7513
+ if (context?.application !== void 0) props.application = context.application;
7514
+ if (context?.release !== void 0) props.release = context.release;
7515
+ if (context?.sessionId !== void 0) props.session_id = context.sessionId;
7516
+ if (context?.organizationId !== void 0) props.organization_id = context.organizationId;
7517
+ if (context?.journeyId !== void 0) props.journey_id = context.journeyId;
7518
+ if (context?.correlationId !== void 0) props.correlation_id = context.correlationId;
7519
+ if (context?.anonymousId !== void 0) props.anonymous_id = context.anonymousId;
7520
+ return props;
7521
+ }
7522
+ function postHogProperties(failure, context) {
7523
+ const merged = sanitizeObservationContext({
7524
+ ...context,
7525
+ ...failure.context
7526
+ });
6670
7527
  return {
6671
- ok: true,
6672
- value: f(result.value)
7528
+ sdk_version: failure.sdkVersion,
7529
+ operation: failure.operation,
7530
+ error_kind: failure.errorKind,
7531
+ handled: true,
7532
+ ...observationContextProps(merged)
6673
7533
  };
6674
7534
  }
6675
- function mapPayrollRosterLine(line) {
7535
+ function postHogExceptionProperties(failure, properties) {
7536
+ const filename = `capxul-sdk-observation://boundary/${failure.operation}`;
6676
7537
  return {
6677
- id: line.id,
6678
- employee: line.employee,
6679
- amount: line.amount,
6680
- timing: line.timing,
6681
- status: line.status === "removed" ? "ended" : line.status
7538
+ ...properties,
7539
+ $exception_type: failure.errorKind,
7540
+ $exception_message: EXCEPTION_MESSAGE,
7541
+ $exception_level: "error",
7542
+ $exception_list: [{
7543
+ type: failure.errorKind,
7544
+ value: EXCEPTION_MESSAGE,
7545
+ mechanism: {
7546
+ type: "capxul_sdk_boundary",
7547
+ handled: true,
7548
+ synthetic: true
7549
+ },
7550
+ stacktrace: {
7551
+ type: "raw",
7552
+ frames: [{
7553
+ platform: "javascript",
7554
+ filename,
7555
+ function: `CapxulSdkBoundary.${failure.operation}`,
7556
+ lineno: 1,
7557
+ colno: 1,
7558
+ in_app: true
7559
+ }]
7560
+ }
7561
+ }]
6682
7562
  };
6683
7563
  }
6684
- function toPayrollTemplate(document) {
6685
- if (document === void 0) return { title: "Payroll" };
6686
- if ("title" in document) return {
6687
- title: document.title,
6688
- ...typeof document.memo === "string" ? { memo: document.memo } : {}
6689
- };
6690
- if (document.primaryType === "Payslip") return { title: `Payslip ${document.message.period}` };
6691
- if ("reference" in document.message) return {
6692
- title: document.primaryType,
6693
- memo: document.message.reference
6694
- };
6695
- return { title: document.primaryType };
7564
+ function errorKind(cause) {
7565
+ try {
7566
+ if (isCapxulError(cause)) return normalizeErrorKind(cause.code);
7567
+ if (cause instanceof Error) return normalizeErrorKind(cause.name);
7568
+ return "UnknownFailure";
7569
+ } catch {
7570
+ return "Error";
7571
+ }
6696
7572
  }
6697
- function normalizePaymentTiming(payment) {
6698
- const { release: _release, ...rest } = payment;
7573
+ function sanitizeFailureObservation(failure) {
7574
+ const operation = normalizeOperation(failure.operation);
7575
+ const kind = normalizeErrorKind(failure.errorKind);
7576
+ const context = sanitizeObservationContext(failure.context);
6699
7577
  return {
6700
- ...rest,
6701
- timing: payment.timing ?? payment.release ?? { kind: "instant" }
7578
+ exception: syntheticException(operation, kind),
7579
+ sdkVersion: normalizeSdkVersion(failure.sdkVersion),
7580
+ operation,
7581
+ errorKind: kind,
7582
+ ...context === void 0 ? {} : { context }
6702
7583
  };
6703
7584
  }
7585
+ function normalizeSdkVersion(value) {
7586
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/u.test(value) ? value : "unknown";
7587
+ }
7588
+ function normalizeOperation(value) {
7589
+ return typeof value === "string" && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,255}$/u.test(value) ? value : "unknown";
7590
+ }
7591
+ function normalizeErrorKind(value) {
7592
+ return typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u.test(value) ? value : "Error";
7593
+ }
7594
+ function syntheticException(operation, kind) {
7595
+ const error = /* @__PURE__ */ new Error(EXCEPTION_MESSAGE);
7596
+ error.name = kind;
7597
+ error.stack = `${kind}: ${error.message}\n at CapxulSdkBoundary.${operation} (capxul-sdk-observation://boundary/${operation}:1:1)`;
7598
+ return error;
7599
+ }
7600
+ function isPromiseLike(value) {
7601
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
7602
+ }
7603
+ function isPlainObject(value) {
7604
+ if (typeof value !== "object" || value === null) return false;
7605
+ const prototype = Object.getPrototypeOf(value);
7606
+ return prototype === Object.prototype || prototype === null;
7607
+ }
7608
+ function isCapxulResult(value) {
7609
+ return isPlainObject(value) && typeof value.ok === "boolean";
7610
+ }
7611
+ function isFailedResult(value) {
7612
+ return isCapxulResult(value) && value.ok === false && "error" in value;
7613
+ }
6704
7614
  //#endregion
6705
- //#region src/surface/factory.ts
6706
- function detectAuthCacheAdapter() {
6707
- const globalAny = globalThis;
6708
- if (globalAny.window?.localStorage !== void 0) return new BrowserAuthCacheAdapter(globalAny.window.localStorage);
6709
- return new InMemoryAuthCacheAdapter();
7615
+ //#region src/telemetry/from-posthog.ts
7616
+ const PRODUCT_INVOCATION = Symbol("capxul.product-telemetry-invocation");
7617
+ /** @internal Bind paired emit/identify/reset work to one call-start snapshot. */
7618
+ function bindProductTelemetryInvocation(telemetry, source) {
7619
+ return telemetry[PRODUCT_INVOCATION]?.(source) ?? telemetry;
7620
+ }
7621
+ /**
7622
+ * Drop props that must never cross to a host-owned external sink. Today that is
7623
+ * the `$exception` `details` blob: `captureException` serializes
7624
+ * `CapxulError.details` (e.g. `{ asset, available, required }`, `{ name }`,
7625
+ * `{ accountId }` — errors.ts) into it, and the shared redactor has no
7626
+ * `$exception` rule, so it is stripped here at the boundary (infra#1037). The
7627
+ * safe fields (error code, operation, failure_mode, the fixed leak-safe message,
7628
+ * stack frames) are preserved.
7629
+ */
7630
+ function stripHostUnsafeProps(props) {
7631
+ if (props === void 0) return void 0;
7632
+ const { details: _details, ...safe } = props;
7633
+ return safe;
7634
+ }
7635
+ /**
7636
+ * The subset of a posthog-js client the seam calls. `identify` / `group` /
7637
+ * `reset` are optional — a host that only wants event capture can omit them.
7638
+ */
7639
+ /**
7640
+ * Adapt the host's already-initialized posthog-like client into a
7641
+ * `TelemetryPort` for the `telemetry` prop / input. This port SUPPLANTS the
7642
+ * SDK's no-op default telemetry sink (`production.ts` binds it via
7643
+ * `Layer.succeed`, not `compose` — there is no client-side success relay to
7644
+ * compose with); it is additive to Capxul's backend first-party record and
7645
+ * never owns the client.
7646
+ */
7647
+ function postHogProductTelemetry(policy, fixedSnapshot) {
7648
+ const telemetry = new PostHogTelemetryAdapter({
7649
+ capture: (name, props, source) => {
7650
+ const snapshot = readInvocationObservation(source) ?? fixedSnapshot ?? policy.snapshot();
7651
+ if (!snapshot.active || policy.client === null || policy.client === void 0) return;
7652
+ const event = stampTelemetryEnvelope({
7653
+ name,
7654
+ props
7655
+ }, {
7656
+ capxul_env: policy.capxulEnv,
7657
+ producer: "sdk"
7658
+ });
7659
+ policy.deliver(() => policy.client.capture(name, {
7660
+ ...stripHostUnsafeProps(event.props),
7661
+ ...observationContextProps(snapshot.context)
7662
+ }));
7663
+ },
7664
+ identify: (input) => {
7665
+ if (!(fixedSnapshot ?? policy.snapshot()).active || policy.client?.identify === void 0) return;
7666
+ policy.deliver(() => policy.client.identify(input.distinctId, {
7667
+ ...input.traits,
7668
+ ...input.properties
7669
+ }));
7670
+ },
7671
+ group: (input) => {
7672
+ if (!(fixedSnapshot ?? policy.snapshot()).active || policy.client?.group === void 0) return;
7673
+ policy.deliver(() => policy.client.group(input.groupType, input.groupKey, input.properties === void 0 ? void 0 : { ...input.properties }));
7674
+ },
7675
+ reset: () => {
7676
+ if (!(fixedSnapshot ?? policy.snapshot()).active || policy.client?.reset === void 0) return;
7677
+ policy.deliver(() => policy.client.reset());
7678
+ }
7679
+ });
7680
+ Object.defineProperty(telemetry, PRODUCT_INVOCATION, {
7681
+ enumerable: false,
7682
+ value: (source) => postHogProductTelemetry(policy, readInvocationObservation(source) ?? fixedSnapshot ?? policy.snapshot())
7683
+ });
7684
+ return telemetry;
6710
7685
  }
6711
7686
  //#endregion
6712
7687
  //#region src/telemetry/identity-product.ts
@@ -6791,13 +7766,15 @@ const ignoreTransportFailure = (operation, operationName, eventName) => Effect.s
6791
7766
  product_event: eventName
6792
7767
  }), Effect.catchCause(() => Effect.void))));
6793
7768
  function executeIdentityProductObservation(telemetry, record, state) {
6794
- const observation = mapIdentityProductObservation(record, state);
6795
- if (observation === null) return Effect.void;
6796
- const after = () => observation.name === "auth_verified" && state.phase === "authenticated" ? telemetry.identify({
7769
+ const mapped = mapIdentityProductObservation(record, state);
7770
+ if (mapped === null) return Effect.void;
7771
+ copyInvocationObservation(record, mapped);
7772
+ const invocationTelemetry = bindProductTelemetryInvocation(telemetry, mapped);
7773
+ const after = () => mapped.name === "auth_verified" && state.phase === "authenticated" ? invocationTelemetry.identify({
6797
7774
  distinctId: state.session.authUserId,
6798
7775
  traits: { email_domain: emailDomain(state.session.email) }
6799
- }) : observation.name === "auth_signed_out" ? telemetry.reset() : Effect.void;
6800
- return ignoreTransportFailure(() => telemetry.emit(observation), "emit", observation.name).pipe(Effect.andThen(ignoreTransportFailure(after, observation.name === "auth_signed_out" ? "reset" : "identify", observation.name)));
7776
+ }) : mapped.name === "auth_signed_out" ? invocationTelemetry.reset() : Effect.void;
7777
+ return ignoreTransportFailure(() => invocationTelemetry.emit(mapped), "emit", mapped.name).pipe(Effect.andThen(ignoreTransportFailure(after, mapped.name === "auth_signed_out" ? "reset" : "identify", mapped.name)));
6801
7778
  }
6802
7779
  //#endregion
6803
7780
  //#region src/surface/create-capxul-client.ts
@@ -6808,14 +7785,14 @@ function assembleCapxulClient(input) {
6808
7785
  runPromise: Effect.runPromise
6809
7786
  };
6810
7787
  const scope = effectRunner.runSync(Scope.make());
6811
- const actor = effectRunner.runSync(Scope.provide(bootIdentityFlow({
7788
+ const actor = withHostObservation(effectRunner.runSync(Scope.provide(bootIdentityFlow({
6812
7789
  ports: input.ports,
6813
7790
  chainId: input.bootstrap.chainId,
6814
7791
  requirement: input.requirement,
6815
7792
  ...input.signer === void 0 ? {} : { signer: input.signer },
6816
7793
  ...input.organizationSetup === void 0 ? {} : { organizationSetup: input.organizationSetup },
6817
7794
  ...input.otpTtlMs === void 0 ? {} : { otpTtlMs: input.otpTtlMs }
6818
- }), scope));
7795
+ }), scope)), input.hostObservationSnapshot);
6819
7796
  const unsubscribeProductTelemetry = actor.subscribeTransitions((record) => {
6820
7797
  effectRunner.runPromise(executeIdentityProductObservation(input.ports.telemetry, record, actor.snapshot())).catch(() => {});
6821
7798
  });
@@ -6831,7 +7808,13 @@ function assembleCapxulClient(input) {
6831
7808
  const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;
6832
7809
  let detectPendingOrgInvitations;
6833
7810
  let kickProvisioning;
6834
- const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });
7811
+ const financialOps = makeFinancialOpsMethods({
7812
+ actor,
7813
+ chainId: input.bootstrap.chainId,
7814
+ convexCall: input.ports.convexCall,
7815
+ ...input.signer === void 0 ? {} : { signer: input.signer },
7816
+ telemetry: input.ports.telemetry
7817
+ });
6835
7818
  const accountBundle = makeAccountMethods({
6836
7819
  actor,
6837
7820
  authCache,
@@ -6876,22 +7859,19 @@ function assembleCapxulClient(input) {
6876
7859
  });
6877
7860
  const system = makeSystemMethods({ convexCall: input.ports.convexCall });
6878
7861
  const media = makeMediaMethods({ convexCall: input.ports.convexCall });
7862
+ const holdings = makeHoldingsMethods({ convexCall: input.ports.convexCall });
6879
7863
  const accounts = makeAccountsMethods({
6880
7864
  accountReadPort: input.ports.accountRead,
6881
7865
  chainId: input.bootstrap.chainId,
6882
7866
  telemetry: input.ports.telemetry
6883
7867
  });
6884
- const subAccounts = makeSubAccountsMethods({
6885
- subAccountPort: input.ports.subAccount,
6886
- telemetry: input.ports.telemetry
6887
- });
6888
7868
  const orgMethods = makeOrgMethods({
7869
+ actor,
6889
7870
  chainId: input.bootstrap.chainId,
6890
7871
  telemetry: input.ports.telemetry,
6891
7872
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
6892
- ...input.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: input.orgRolesDeploymentPort },
6893
- ...input.orgSpendPort === void 0 ? {} : { orgSpendPort: input.orgSpendPort },
6894
7873
  convexCall: input.ports.convexCall,
7874
+ ...input.signer === void 0 ? {} : { signer: input.signer },
6895
7875
  ...input.organizationSetup === void 0 ? {} : { organizationSetup: input.organizationSetup }
6896
7876
  });
6897
7877
  if (selectedOrgPort !== void 0) detectPendingOrgInvitations = async () => {
@@ -6980,10 +7960,10 @@ function assembleCapxulClient(input) {
6980
7960
  destinations: financialOps.destinations,
6981
7961
  payments: financialOps.payments,
6982
7962
  activity: financialOps.activity,
7963
+ holdings,
6983
7964
  offramp: financialOps.offramp,
6984
7965
  paymentDocuments: financialOps.paymentDocuments,
6985
7966
  media,
6986
- subAccounts,
6987
7967
  createOrg: orgMethods.createOrg,
6988
7968
  orgs: orgMethods.orgs,
6989
7969
  org: orgMethods.org,
@@ -6997,7 +7977,19 @@ function assembleCapxulClient(input) {
6997
7977
  }
6998
7978
  };
6999
7979
  }
7980
+ function withHostObservation(actor, snapshot) {
7981
+ if (snapshot === void 0) return actor;
7982
+ const controls = (input) => {
7983
+ const captured = snapshot();
7984
+ const copied = { ...input };
7985
+ return captured === void 0 ? copied : attachInvocationObservation(copied, captured);
7986
+ };
7987
+ return {
7988
+ ...actor,
7989
+ ask: (event, input) => actor.ask(event, controls(input)),
7990
+ tell: (event, input) => actor.tell(event, controls(input)),
7991
+ restoreAuthSession: (session, input) => actor.restoreAuthSession(session, controls(input))
7992
+ };
7993
+ }
7000
7994
  //#endregion
7001
- export { OBSERVATION_CONTEXT_HEADER as A, normalizeBindingEmail as B, convexCallErrorFromCapxul as C, bootstrapErrorFromCapxul as D, BootstrapPortTag as E, isSettingUpLifecycle as F, deriveCapxulSafeAddress as H, formatTraceparent as I, EXCEPTION_MESSAGE as L, sanitizeObservationContext as M, CAPXUL_FUNCTIONS as N, authClientPortFromPromiseAdapter as O, BootstrapEnvelope as P, captureException as R, ConvexCallPortTag as S, ClockPortTag as T, destination as U, BASE_SEPOLIA_CHAIN_ID as V, identityErrorFromCapxul as _, redactTelemetryProps as a, markFailureInvocationSnapshot as b, smartAccountErrorFromCapxul as c, fromWei as d, AccountReadPortTag as f, IdentityPortTag as g, wireChainId as h, redactTelemetryEvent as i, encodeObservationContextHeader as j, AuthClientPortTag as k, SubAccountPortTag as l, toWei as m, detectAuthCacheAdapter as n, stampTelemetryEnvelope as o, accountReadErrorFromCapxul as p, TelemetryPortTag as r, SmartAccountPortTag as s, assembleCapxulClient as t, subAccountErrorFromCapxul as u, copyInvocationObservation as v, ClockError as w, readInvocationObservation as x, hasFailureInvocationSnapshot as y, captureExceptionSync as z };
7002
-
7003
- //# sourceMappingURL=create-capxul-client-DVzm78RU.mjs.map
7995
+ export { encodeObservationContextHeader as A, captureExceptionSync as B, ClockPortTag as C, AuthClientPortTag as D, authClientPortFromPromiseAdapter as E, isSettingUpLifecycle as F, destination as G, normalizeBindingEmail as H, formatTraceparent as I, copyInvocationObservation as L, CAPXUL_FUNCTIONS as M, BootstrapEnvelope as N, version as O, EngineeringTelemetryBootstrapPolicy as P, readInvocationObservation as R, ClockError as S, bootstrapErrorFromCapxul as T, BASE_SEPOLIA_CHAIN_ID as U, CAPXUL_PAYMENTS_V2_ADDRESS as V, deriveCapxulSafeAddress as W, wireChainId as _, observeFailedResult as a, ConvexCallPortTag as b, PostHogTelemetryLayer as c, SmartAccountPortTag as d, smartAccountErrorFromCapxul as f, toWei as g, accountReadErrorFromCapxul as h, observationContextProps as i, sanitizeObservationContext as j, OBSERVATION_CONTEXT_HEADER as k, TelemetryPortTag as l, AccountReadPortTag as m, postHogProductTelemetry as n, postHogFailureObservation as o, fromWei as p, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT as r, detectAuthCacheAdapter as s, assembleCapxulClient as t, redactTelemetryEvent as u, IdentityPortTag as v, BootstrapPortTag as w, convexCallErrorFromCapxul as x, identityErrorFromCapxul as y, captureException as z };