@capxul/sdk 1.2.3 → 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.
@@ -1608,6 +1607,24 @@ function mapAccountLifecycle(input) {
1608
1607
  }
1609
1608
  //#endregion
1610
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" }));
1611
1628
  /**
1612
1629
  * `AppId` schema. Mirrors `toAppId` from `@capxul/types`:
1613
1630
  * `app_` + Crockford-base32 ULID (26 chars, first char in `[0-7]`).
@@ -1627,13 +1644,15 @@ const DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;
1627
1644
  * `DocumentHash` schema. Mirrors `toDocumentHash`: bare or 0x-prefixed bytes32,
1628
1645
  * normalized to lowercase 0x-prefixed form.
1629
1646
  */
1630
- const DocumentHashSchema$1 = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1647
+ const DocumentHashSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1631
1648
  decode: SchemaGetter.transform((s) => {
1632
1649
  const stripped = s.startsWith("0x") || s.startsWith("0X") ? s.slice(2) : s;
1633
1650
  return DOCUMENT_HASH_HEX_RE.test(stripped) ? `0x${stripped.toLowerCase()}` : s;
1634
1651
  }),
1635
1652
  encode: SchemaGetter.transform((s) => s)
1636
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" }));
1637
1656
  /**
1638
1657
  * `SessionToken` schema. Mirrors `toSessionToken`: non-empty string.
1639
1658
  * Issuance source distinguishes SDK-handshake tokens from auth-session
@@ -1710,15 +1729,6 @@ const CAPXUL_FUNCTIONS = {
1710
1729
  faucetMint: "account/actions:faucetMint",
1711
1730
  readBalance: "account/actions:readBalance"
1712
1731
  },
1713
- "financialOps/actions": {
1714
- cancelCommitment: "financialOps/actions:cancelCommitment",
1715
- claimCommitment: "financialOps/actions:claimCommitment",
1716
- markCommitmentCreated: "financialOps/actions:markCommitmentCreated",
1717
- markPaymentSettled: "financialOps/actions:markPaymentSettled",
1718
- markWithdrawalSettled: "financialOps/actions:markWithdrawalSettled",
1719
- recordOrgPayment: "financialOps/actions:recordOrgPayment",
1720
- redirectCommitment: "financialOps/actions:redirectCommitment"
1721
- },
1722
1732
  "financialOps/addressBook": {
1723
1733
  add: "financialOps/addressBook:add",
1724
1734
  get: "financialOps/addressBook:get",
@@ -1730,28 +1740,11 @@ const CAPXUL_FUNCTIONS = {
1730
1740
  "financialOps/destinations": {
1731
1741
  add: "financialOps/destinations:add",
1732
1742
  list: "financialOps/destinations:list",
1733
- payout: "financialOps/destinations:payout",
1734
1743
  remove: "financialOps/destinations:remove"
1735
1744
  },
1736
- "financialOps/insights": {
1737
- history: "financialOps/insights:history",
1738
- summary: "financialOps/insights:summary"
1739
- },
1740
- "financialOps/mutations": {
1741
- createPayee: "financialOps/mutations:createPayee",
1742
- pay: "financialOps/mutations:pay",
1743
- withdraw: "financialOps/mutations:withdraw"
1744
- },
1745
- "financialOps/payrollRoster": {
1746
- add: "financialOps/payrollRoster:add",
1747
- list: "financialOps/payrollRoster:list",
1748
- remove: "financialOps/payrollRoster:remove",
1749
- run: "financialOps/payrollRoster:run",
1750
- update: "financialOps/payrollRoster:update"
1751
- },
1745
+ "financialOps/mutations": { createPayee: "financialOps/mutations:createPayee" },
1752
1746
  "financialOps/queries": {
1753
1747
  depositInstructions: "financialOps/queries:depositInstructions",
1754
- getCommitmentRef: "financialOps/queries:getCommitmentRef",
1755
1748
  getPayee: "financialOps/queries:getPayee",
1756
1749
  getPayment: "financialOps/queries:getPayment",
1757
1750
  listPayments: "financialOps/queries:listPayments",
@@ -1768,8 +1761,7 @@ const CAPXUL_FUNCTIONS = {
1768
1761
  get: "financialOps/requestsInbox:get",
1769
1762
  inboxList: "financialOps/requestsInbox:inboxList",
1770
1763
  issue: "financialOps/requestsInbox:issue",
1771
- list: "financialOps/requestsInbox:list",
1772
- reconcile: "financialOps/requestsInbox:reconcile"
1764
+ list: "financialOps/requestsInbox:list"
1773
1765
  },
1774
1766
  "identity/mutations": {
1775
1767
  completeOnboarding: "identity/mutations:completeOnboarding",
@@ -1780,24 +1772,44 @@ const CAPXUL_FUNCTIONS = {
1780
1772
  loadByAuthUserId: "identity/queries:loadByAuthUserId",
1781
1773
  usernameAvailable: "identity/queries:usernameAvailable"
1782
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
+ },
1783
1792
  media: {
1784
1793
  generateUploadUrl: "media:generateUploadUrl",
1785
1794
  setOrgLogo: "media:setOrgLogo",
1786
1795
  setProfileImage: "media:setProfileImage"
1787
1796
  },
1788
1797
  "org/actions": {
1789
- assignRole: "org/actions:assignRole",
1790
1798
  confirmBootstrap: "org/actions:confirmBootstrap",
1791
- deployOrgRoles: "org/actions:deployOrgRoles",
1792
1799
  detectAndAcceptPendingInvitations: "org/actions:detectAndAcceptPendingInvitations",
1793
1800
  inviteMember: "org/actions:inviteMember",
1794
1801
  prepareBootstrap: "org/actions:prepareBootstrap",
1795
1802
  prepareFounderAccount: "org/actions:prepareFounderAccount",
1796
1803
  readTreasury: "org/actions:readTreasury",
1797
- removeMember: "org/actions:removeMember",
1798
1804
  resumeBootstrapSubmission: "org/actions:resumeBootstrapSubmission",
1799
1805
  submitBootstrap: "org/actions:submitBootstrap"
1800
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
+ },
1801
1813
  "org/lifecycle": {
1802
1814
  getProofReceipt: "org/lifecycle:getProofReceipt",
1803
1815
  load: "org/lifecycle:load",
@@ -1825,31 +1837,19 @@ const CAPXUL_FUNCTIONS = {
1825
1837
  loadByAuthUserId: "smartAccount/queries:loadByAuthUserId",
1826
1838
  loadBySmartAccountAddress: "smartAccount/queries:loadBySmartAccountAddress"
1827
1839
  },
1828
- "subAccount/actions": { transfer: "subAccount/actions:transfer" },
1829
- "subAccount/mutations": {
1830
- create: "subAccount/mutations:create",
1831
- remove: "subAccount/mutations:remove",
1832
- rename: "subAccount/mutations:rename"
1833
- },
1834
- "subAccount/queries": {
1835
- get: "subAccount/queries:get",
1836
- list: "subAccount/queries:list"
1837
- },
1838
1840
  system: { health: "system:health" }
1839
1841
  };
1840
1842
  //#endregion
1841
1843
  //#region ../wire/src/status.ts
1842
- /** Payment lifecycle states carried on the wire (ADR-0018 P1). */
1843
- const PAYMENT_STATUSES = [
1844
+ /** The closed L2 Payment status authority. */
1845
+ const L2_PAYMENT_STATUSES = [
1844
1846
  "pending",
1845
- "submitted",
1846
- "pending_claim",
1847
+ "settling",
1847
1848
  "scheduled",
1848
1849
  "streaming",
1850
+ "pending_claim",
1849
1851
  "settled",
1850
1852
  "cancelled",
1851
- "redirected",
1852
- "expired",
1853
1853
  "failed"
1854
1854
  ];
1855
1855
  /** What a payment is FOR. Pairs with `PAYMENT_DOCUMENT_KINDS`. */
@@ -1888,7 +1888,7 @@ const HANDLE_RE = /^@?[a-z0-9][a-z0-9-]{2,31}$/;
1888
1888
  const ORG_HANDLE_RE = /^[a-z0-9][a-z0-9-]{2,31}$/;
1889
1889
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1890
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" })));
1891
- 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" })));
1892
1892
  const PayeeIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PAYEE_ID_RE.test(value), { message: "must be payee_ plus an alphanumeric id" })));
1893
1893
  const OrgIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => ORG_ID_RE.test(value), { message: "must be org_ plus an alphanumeric id" })));
1894
1894
  const UserIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => USER_ID_RE.test(value), { message: "must be user_ plus an alphanumeric id" })));
@@ -1896,7 +1896,7 @@ const DecimalStringSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((v
1896
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" })));
1897
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" })));
1898
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" })));
1899
- 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" })));
1900
1900
  const Uint64Schema = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" })));
1901
1901
  const PaymentDocumentDomain = Schema.Struct({
1902
1902
  name: Schema.Literal("CapxulPayments"),
@@ -1917,10 +1917,10 @@ const InvoiceDocument = Schema.Struct({
1917
1917
  payeeRef: Schema.String,
1918
1918
  amount: MinorUnitStringSchema,
1919
1919
  currency: CurrencyCodeSchema$1,
1920
- decimals: Uint8Schema,
1920
+ decimals: Uint8Schema$1,
1921
1921
  issuedAt: Uint64Schema,
1922
1922
  dueAt: Uint64Schema,
1923
- lineItemsHash: DocumentHashSchema$1
1923
+ lineItemsHash: DocumentHashSchema
1924
1924
  });
1925
1925
  const PayslipDocument = Schema.Struct({
1926
1926
  kind: Schema.Literal(2),
@@ -1930,7 +1930,7 @@ const PayslipDocument = Schema.Struct({
1930
1930
  gross: MinorUnitStringSchema,
1931
1931
  net: MinorUnitStringSchema,
1932
1932
  currency: CurrencyCodeSchema$1,
1933
- decimals: Uint8Schema,
1933
+ decimals: Uint8Schema$1,
1934
1934
  issuedAt: Uint64Schema
1935
1935
  });
1936
1936
  const ReceiptDocument = Schema.Struct({
@@ -1938,7 +1938,7 @@ const ReceiptDocument = Schema.Struct({
1938
1938
  reference: Schema.String,
1939
1939
  amount: MinorUnitStringSchema,
1940
1940
  currency: CurrencyCodeSchema$1,
1941
- decimals: Uint8Schema,
1941
+ decimals: Uint8Schema$1,
1942
1942
  paidAt: Uint64Schema,
1943
1943
  note: Schema.String
1944
1944
  });
@@ -1948,7 +1948,7 @@ const WithdrawalDocument = Schema.Struct({
1948
1948
  reference: Schema.String,
1949
1949
  amount: MinorUnitStringSchema,
1950
1950
  currency: CurrencyCodeSchema$1,
1951
- decimals: Uint8Schema,
1951
+ decimals: Uint8Schema$1,
1952
1952
  destChain: ChainIdSchema$1,
1953
1953
  destAddress: WithdrawalDestAddressSchema,
1954
1954
  settledAt: Uint64Schema,
@@ -1961,7 +1961,7 @@ const FinancialOpsMoney = Schema.Struct({
1961
1961
  decimals: Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" })))
1962
1962
  });
1963
1963
  const PaymentDocument = Schema.Struct({
1964
- documentHash: DocumentHashSchema$1,
1964
+ documentHash: DocumentHashSchema,
1965
1965
  kind: Schema.Literals(PAYMENT_DOCUMENT_KINDS),
1966
1966
  title: Schema.optional(Schema.String),
1967
1967
  uri: Schema.optional(Schema.String),
@@ -2087,8 +2087,8 @@ const PaymentRef = Schema.Union([
2087
2087
  })
2088
2088
  ]);
2089
2089
  const Payment = Schema.Struct({
2090
- id: PaymentIdSchema,
2091
- status: Schema.Literals(PAYMENT_STATUSES),
2090
+ id: PaymentIdSchema$1,
2091
+ status: Schema.Literals(L2_PAYMENT_STATUSES),
2092
2092
  amount: FinancialOpsMoney,
2093
2093
  paymentType: PaymentType,
2094
2094
  recipient: PaymentRecipient,
@@ -2152,6 +2152,1032 @@ Schema.Struct({
2152
2152
  version: Schema.Literal(1),
2153
2153
  payments: Schema.Array(Payment)
2154
2154
  });
2155
+ //#endregion
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
2179
+ };
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
+ });
2155
3181
  `
2156
3182
  .capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;
2157
3183
  font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;
@@ -2295,12 +3321,9 @@ const actorScopeContract = {
2295
3321
  requestsList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].list),
2296
3322
  requestsGet: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].get),
2297
3323
  requestsCancel: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].cancel),
2298
- requestsReconcile: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].reconcile),
2299
3324
  inboxList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].inboxList),
2300
3325
  inboxApprove: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].approve),
2301
- inboxDecline: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].decline),
2302
- insightsSummary: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/insights"].summary),
2303
- insightsHistory: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/insights"].history)
3326
+ inboxDecline: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].decline)
2304
3327
  };
2305
3328
  //#endregion
2306
3329
  //#region src/surface/contacts.ts
@@ -2312,11 +3335,11 @@ function makeActorRelationshipMethods(deps) {
2312
3335
  const fns = actorScopeContract;
2313
3336
  return {
2314
3337
  addressBook: {
2315
- list: (options) => mapOk$2(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
3338
+ list: (options) => mapOk$1(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
2316
3339
  get: async (entryId, options) => {
2317
3340
  const ref = refFromEntryId(entryId);
2318
3341
  if (!ref.ok) return ref;
2319
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
3342
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
2320
3343
  actor,
2321
3344
  ref: ref.value
2322
3345
  })), (entry) => entry === null ? null : mapAddressBookEntry(entry));
@@ -2324,7 +3347,7 @@ function makeActorRelationshipMethods(deps) {
2324
3347
  add: async (input, options) => {
2325
3348
  const ref = normalizeRefForBackend$1(input.ref, "ref");
2326
3349
  if (!ref.ok) return ref;
2327
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
3350
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
2328
3351
  actor,
2329
3352
  ref: ref.value,
2330
3353
  ...input.label === void 0 ? {} : { label: input.label }
@@ -2333,7 +3356,7 @@ function makeActorRelationshipMethods(deps) {
2333
3356
  hide: async (entryId, options) => {
2334
3357
  const ref = refFromEntryId(entryId);
2335
3358
  if (!ref.ok) return ref;
2336
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
3359
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
2337
3360
  actor,
2338
3361
  ref: ref.value
2339
3362
  })), mapAddressBookEntry);
@@ -2341,7 +3364,7 @@ function makeActorRelationshipMethods(deps) {
2341
3364
  unhide: async (entryId, options) => {
2342
3365
  const ref = refFromEntryId(entryId);
2343
3366
  if (!ref.ok) return ref;
2344
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
3367
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
2345
3368
  actor,
2346
3369
  ref: ref.value
2347
3370
  })), mapAddressBookEntry);
@@ -2349,7 +3372,7 @@ function makeActorRelationshipMethods(deps) {
2349
3372
  label: async (input, options) => {
2350
3373
  const ref = refFromEntryId(input.entryId);
2351
3374
  if (!ref.ok) return ref;
2352
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
3375
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
2353
3376
  actor,
2354
3377
  ref: ref.value,
2355
3378
  label: input.label
@@ -2360,7 +3383,7 @@ function makeActorRelationshipMethods(deps) {
2360
3383
  issue: async (input, options) => {
2361
3384
  const payer = normalizeRefForBackend$1(input.payer, "payer");
2362
3385
  if (!payer.ok) return payer;
2363
- return mapOk$2(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
3386
+ return mapOk$1(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
2364
3387
  actor,
2365
3388
  payer: payer.value,
2366
3389
  amount: input.amount,
@@ -2369,43 +3392,36 @@ function makeActorRelationshipMethods(deps) {
2369
3392
  ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
2370
3393
  })), (request) => mapActorRequest(request, input.payer));
2371
3394
  },
2372
- list: (options) => mapOk$2(awaitableConvex(options?.signal, "requests.list", () => convexCall.query(fns.requestsList, { actor })), (requests) => requests.map((request) => mapActorRequest(request))),
2373
- 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, {
2374
3397
  actor,
2375
3398
  paymentRequestId: requestId
2376
3399
  })), (request) => request === null ? null : mapActorRequest(request)),
2377
- 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, {
2378
3401
  actor,
2379
3402
  paymentRequestId: requestId
2380
- })), (request) => mapActorRequest(request)),
2381
- reconcile: async (options) => {
2382
- return mapOk$2(awaitableConvex(options?.signal, "requests.reconcile", () => convexCall.query(fns.requestsReconcile, { actor })), (entries) => entries.map(mapReconciliationEntry));
2383
- }
3403
+ })), (request) => mapActorRequest(request))
2384
3404
  },
2385
3405
  inbox: {
2386
- list: (options) => mapOk$2(awaitableConvex(options?.signal, "inbox.list", () => convexCall.query(fns.inboxList, { actor })), (items) => items.map(mapInboxItem)),
2387
- 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, {
2388
3408
  actor,
2389
3409
  paymentRequestId: input.requestId,
2390
3410
  ...input.timing === void 0 ? {} : { timing: input.timing }
2391
3411
  })), mapApprovedInboxPayment),
2392
- 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, {
2393
3413
  actor,
2394
3414
  paymentRequestId: requestId
2395
3415
  })), mapInboxItem)
2396
3416
  },
2397
- insights: {
2398
- summary: (options) => awaitableConvex(options?.signal, "insights.summary", () => convexCall.query(fns.insightsSummary, { actor })),
2399
- history: (options) => mapOk$2(awaitableConvex(options?.signal, "insights.history", () => convexCall.query(fns.insightsHistory, { actor })), (history) => history.transactions.map(normalizePaymentTiming$2))
2400
- },
2401
3417
  profile: {
2402
3418
  get: (options) => {
2403
3419
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
2404
- return missingConvexCall$1(`${domain}.profile.get`);
3420
+ return missingConvexCall(`${domain}.profile.get`);
2405
3421
  },
2406
3422
  depositInstructions: (options) => {
2407
3423
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
2408
- return missingConvexCall$1(`${domain}.profile.depositInstructions`);
3424
+ return missingConvexCall(`${domain}.profile.depositInstructions`);
2409
3425
  }
2410
3426
  }
2411
3427
  };
@@ -2413,37 +3429,32 @@ function makeActorRelationshipMethods(deps) {
2413
3429
  function makeNotImplementedActorRelationshipMethods(deps, domain) {
2414
3430
  return {
2415
3431
  addressBook: {
2416
- list: () => missingConvexCall$1("addressBook.list"),
2417
- get: () => missingConvexCall$1("addressBook.get"),
2418
- add: () => missingConvexCall$1("addressBook.add"),
2419
- hide: () => missingConvexCall$1("addressBook.hide"),
2420
- unhide: () => missingConvexCall$1("addressBook.unhide"),
2421
- 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")
2422
3438
  },
2423
3439
  requests: {
2424
- issue: () => missingConvexCall$1("requests.issue"),
2425
- list: () => missingConvexCall$1("requests.list"),
2426
- get: () => missingConvexCall$1("requests.get"),
2427
- cancel: () => missingConvexCall$1("requests.cancel"),
2428
- 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")
2429
3444
  },
2430
3445
  inbox: {
2431
- list: () => missingConvexCall$1("inbox.list"),
2432
- approve: () => missingConvexCall$1("inbox.approve"),
2433
- decline: () => missingConvexCall$1("inbox.decline")
2434
- },
2435
- insights: {
2436
- summary: () => missingConvexCall$1("insights.summary"),
2437
- history: () => missingConvexCall$1("insights.history")
3446
+ list: () => missingConvexCall("inbox.list"),
3447
+ approve: () => missingConvexCall("inbox.approve"),
3448
+ decline: () => missingConvexCall("inbox.decline")
2438
3449
  },
2439
3450
  profile: {
2440
3451
  get: (options) => {
2441
3452
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
2442
- return missingConvexCall$1(`${domain}.profile.get`);
3453
+ return missingConvexCall(`${domain}.profile.get`);
2443
3454
  },
2444
3455
  depositInstructions: (options) => {
2445
3456
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
2446
- return missingConvexCall$1(`${domain}.profile.depositInstructions`);
3457
+ return missingConvexCall(`${domain}.profile.depositInstructions`);
2447
3458
  }
2448
3459
  }
2449
3460
  };
@@ -2460,13 +3471,13 @@ async function mapAccountProfile(resultPromise) {
2460
3471
  }
2461
3472
  };
2462
3473
  }
2463
- function missingConvexCall$1(operation) {
3474
+ function missingConvexCall(operation) {
2464
3475
  return Promise.resolve({
2465
3476
  ok: false,
2466
3477
  error: Errors.providerError("convex", operation, "ConvexCallPort is required")
2467
3478
  });
2468
3479
  }
2469
- async function mapOk$2(resultOrPromise, f) {
3480
+ async function mapOk$1(resultOrPromise, f) {
2470
3481
  const result = await resultOrPromise;
2471
3482
  if (!result.ok) return result;
2472
3483
  return {
@@ -2512,17 +3523,8 @@ function mapInboxItem(item) {
2512
3523
  status: mapInboxStatus(item.status)
2513
3524
  };
2514
3525
  }
2515
- function mapReconciliationEntry(entry) {
2516
- return {
2517
- paymentRequestId: entry.paymentRequestId,
2518
- reference: entry.reference,
2519
- status: entry.status,
2520
- settledPaymentId: entry.settledPaymentId ?? null,
2521
- receiptDocumentHash: entry.receiptDocumentHash ?? null
2522
- };
2523
- }
2524
3526
  function mapApprovedInboxPayment(item) {
2525
- if (item.settledPayment !== void 0) return normalizePaymentTiming$2(item.settledPayment);
3527
+ if (item.settledPayment !== void 0) return normalizePaymentTiming$1(item.settledPayment);
2526
3528
  const zero = {
2527
3529
  ...item.amount,
2528
3530
  value: "0"
@@ -2592,7 +3594,7 @@ function mapInboxStatus(status) {
2592
3594
  default: return "open";
2593
3595
  }
2594
3596
  }
2595
- function normalizePaymentTiming$2(payment) {
3597
+ function normalizePaymentTiming$1(payment) {
2596
3598
  const { release: _release, ...rest } = payment;
2597
3599
  return {
2598
3600
  ...rest,
@@ -2944,7 +3946,7 @@ function makeAccountMethods(deps) {
2944
3946
  }
2945
3947
  //#endregion
2946
3948
  //#region package.json
2947
- var version = "1.2.3";
3949
+ var version = "2.0.0";
2948
3950
  //#endregion
2949
3951
  //#region src/ports/auth-client.ts
2950
3952
  var AuthClientError = class extends Data.TaggedError("AuthClientError") {};
@@ -3089,19 +4091,6 @@ function fromWei(rawBalance, decimals, currency) {
3089
4091
  };
3090
4092
  }
3091
4093
  //#endregion
3092
- //#region src/ports/sub-account.ts
3093
- var SubAccountError = class extends Data.TaggedError("SubAccountError") {};
3094
- function subAccountErrorFromCapxul(operation, error, cause = error) {
3095
- return new SubAccountError({
3096
- operation,
3097
- publicCode: error.code,
3098
- publicError: error,
3099
- cause,
3100
- ...error.details === void 0 ? {} : { details: error.details }
3101
- });
3102
- }
3103
- var SubAccountPortTag = class extends Context.Service()("@capxul/sdk/ports/SubAccountPort") {};
3104
- //#endregion
3105
4094
  //#region src/ports/smart-account.ts
3106
4095
  var SmartAccountError = class extends Data.TaggedError("SmartAccountError") {};
3107
4096
  function smartAccountErrorFromCapxul(operation, error, cause = error) {
@@ -3130,31 +4119,15 @@ const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeI
3130
4119
  const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
3131
4120
  const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
3132
4121
  const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
3133
- const SUBACCOUNT_ID_TELEMETRY_RE = /^subaccount_[0-9A-Za-z]+$/;
3134
4122
  const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
3135
4123
  const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
3136
- const SubAccountIdSchema = Schema.String.pipe(Schema.refine((value) => SUBACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be subaccount_ plus an alphanumeric id" }));
3137
4124
  const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
3138
4125
  const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
3139
4126
  const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
3140
- const TransferDirectionSchema = Schema.Literals([
3141
- "add",
3142
- "out",
3143
- "between"
3144
- ]);
3145
- const SubAccountOpSchema = Schema.Literals([
3146
- "create",
3147
- "rename",
3148
- "delete"
3149
- ]);
3150
4127
  const OptionalAccountId = Schema.optional(AccountIdSchema);
3151
- const OptionalSubAccountId = Schema.optional(SubAccountIdSchema);
3152
4128
  const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
3153
4129
  const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
3154
4130
  const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
3155
- const OptionalTransferDirection = Schema.optional(TransferDirectionSchema);
3156
- const OptionalSubAccountOp = Schema.optional(SubAccountOpSchema);
3157
- const OptionalTrue = Schema.optional(Schema.Literal(true));
3158
4131
  const OptionalAddress = Schema.optional(AddressSchema);
3159
4132
  const OptionalAppId = Schema.optional(AppIdSchema);
3160
4133
  const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
@@ -3163,11 +4136,6 @@ const OptionalDurationMs = Schema.optional(DurationMsSchema);
3163
4136
  const OptionalEpochMs = Schema.optional(EpochMsSchema);
3164
4137
  const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
3165
4138
  const OptionalTxHash = Schema.optional(TxHashSchema);
3166
- const PAYMENT_ID_TELEMETRY_RE = /^payment_[0-9A-Za-z]+$/;
3167
- const PAYEE_ID_TELEMETRY_RE = /^payee_[0-9A-Za-z]+$/;
3168
- const PaymentIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => PAYMENT_ID_TELEMETRY_RE.test(value), { message: "must be payment_ plus an alphanumeric id" }));
3169
- const PayeeIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => PAYEE_ID_TELEMETRY_RE.test(value), { message: "must be payee_ plus an alphanumeric id" }));
3170
- const DocumentHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
3171
4139
  /**
3172
4140
  * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
3173
4141
  * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
@@ -3293,45 +4261,6 @@ const FaucetFailedProps = Schema.Struct({
3293
4261
  ...TelemetryEnvelopeProps,
3294
4262
  reason: OptionalString
3295
4263
  });
3296
- const SubaccountCreatedProps = Schema.Struct({
3297
- ...TelemetryEnvelopeProps,
3298
- sub_account_id: OptionalSubAccountId,
3299
- durationMs: OptionalDurationMs
3300
- });
3301
- const SubaccountRenamedProps = Schema.Struct({
3302
- ...TelemetryEnvelopeProps,
3303
- sub_account_id: OptionalSubAccountId
3304
- });
3305
- const SubaccountDeletedProps = Schema.Struct({
3306
- ...TelemetryEnvelopeProps,
3307
- sub_account_id: OptionalSubAccountId
3308
- });
3309
- const SubaccountOpFailedProps = Schema.Struct({
3310
- ...TelemetryEnvelopeProps,
3311
- op: OptionalSubAccountOp,
3312
- reason: OptionalString
3313
- });
3314
- const TransferRequestedProps = Schema.Struct({
3315
- ...TelemetryEnvelopeProps,
3316
- amount: OptionalWeiAmount,
3317
- direction: OptionalTransferDirection
3318
- });
3319
- const TransferBackendReceivedProps = Schema.Struct({
3320
- ...TelemetryEnvelopeProps,
3321
- direction: OptionalTransferDirection
3322
- });
3323
- const TransferConfirmedProps = Schema.Struct({
3324
- ...TelemetryEnvelopeProps,
3325
- amount: OptionalWeiAmount,
3326
- direction: OptionalTransferDirection,
3327
- available_bucket: OptionalBalanceBucket,
3328
- txless: OptionalTrue,
3329
- durationMs: OptionalDurationMs
3330
- });
3331
- const TransferFailedProps = Schema.Struct({
3332
- ...TelemetryEnvelopeProps,
3333
- reason: OptionalString
3334
- });
3335
4264
  const ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;
3336
4265
  const OrgIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => ORG_ID_TELEMETRY_RE.test(value), { message: "must be org_ plus an alphanumeric id" }));
3337
4266
  const OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);
@@ -3456,75 +4385,70 @@ const OrgInviteAcceptedProps = Schema.Struct({
3456
4385
  role: OptionalString,
3457
4386
  status: OptionalString
3458
4387
  });
3459
- const OrgRoleGrantedProps = Schema.Struct({
4388
+ const OrgInviteExpiredProps = Schema.Struct({
3460
4389
  ...TelemetryEnvelopeProps,
3461
4390
  org_id: OptionalOrgId,
4391
+ email_domain: OptionalString,
4392
+ reason: OptionalString,
3462
4393
  role: OptionalString,
3463
- status: OptionalString,
3464
- txHash: OptionalTxHash
4394
+ status: OptionalString
3465
4395
  });
3466
- const OrgMemberActiveProps = Schema.Struct({
4396
+ const PaymentInitiatedProps = Schema.Struct({
3467
4397
  ...TelemetryEnvelopeProps,
3468
- org_id: OptionalOrgId,
3469
- role: OptionalString,
3470
- status: OptionalString,
3471
- durationMs: OptionalDurationMs
4398
+ kind: Schema.String,
4399
+ payment_id: Schema.String
3472
4400
  });
3473
- const OrgMemberRemovedProps = Schema.Struct({
4401
+ const PaymentSettledL2Props = Schema.Struct({
3474
4402
  ...TelemetryEnvelopeProps,
3475
- org_id: OptionalOrgId,
3476
- role: OptionalString,
3477
- status: OptionalString,
3478
- txHash: OptionalTxHash
4403
+ kind: Schema.String,
4404
+ chain_id: Schema.Number,
4405
+ settlement_id: Schema.String
3479
4406
  });
3480
- const OrgInviteExpiredProps = Schema.Struct({
4407
+ const PaymentFailedL2Props = Schema.Struct({
3481
4408
  ...TelemetryEnvelopeProps,
3482
- org_id: OptionalOrgId,
3483
- email_domain: OptionalString,
3484
- reason: OptionalString,
3485
- role: OptionalString,
3486
- status: OptionalString
4409
+ kind: Schema.String,
4410
+ payment_id: Schema.String,
4411
+ reason_code: Schema.String
3487
4412
  });
3488
- const OrgRoleGrantFailedProps = Schema.Struct({
4413
+ const DepositInitiatedProps = Schema.Struct({ ...TelemetryEnvelopeProps });
4414
+ const DepositSettledProps = Schema.Struct({
3489
4415
  ...TelemetryEnvelopeProps,
3490
- org_id: OptionalOrgId,
3491
- reason: OptionalString,
3492
- role: OptionalString
4416
+ chain_id: Schema.Number,
4417
+ tx_hash: Schema.String,
4418
+ log_index: Schema.Number
3493
4419
  });
3494
- const OptionalPaymentId = Schema.optional(PaymentIdTelemetrySchema);
3495
- const OptionalPayeeId = Schema.optional(PayeeIdTelemetrySchema);
3496
- const OptionalDocumentHash = Schema.optional(DocumentHashSchema);
3497
- const PaymentTargetTelemetryProps = Schema.Struct({
4420
+ const PermissionMirrorVerificationProps = Schema.Struct({
3498
4421
  ...TelemetryEnvelopeProps,
3499
- payment_id: OptionalPaymentId,
3500
- payee_id: OptionalPayeeId,
3501
- document_hash: OptionalDocumentHash,
3502
- amount: OptionalWeiAmount,
3503
- currency: OptionalCurrencyCode,
3504
- status: OptionalString,
3505
- reason: OptionalString,
3506
- durationMs: OptionalDurationMs
3507
- });
3508
- 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({
3509
4430
  ...TelemetryEnvelopeProps,
3510
- payment_id: OptionalPaymentId,
3511
- document_hash: OptionalDocumentHash,
3512
- amount: OptionalWeiAmount,
3513
- currency: OptionalCurrencyCode,
3514
- status: OptionalString,
3515
- available_bucket: OptionalBalanceBucket,
3516
- reason: OptionalString,
3517
- 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
3518
4445
  });
3519
- const WithdrawalTargetTelemetryProps = Schema.Struct({
4446
+ const MovementScanIncidentProps = Schema.Struct({
3520
4447
  ...TelemetryEnvelopeProps,
3521
- payment_id: OptionalPaymentId,
3522
- document_hash: OptionalDocumentHash,
3523
- amount: OptionalWeiAmount,
3524
- currency: OptionalCurrencyCode,
3525
- status: OptionalString,
3526
- reason: OptionalString,
3527
- durationMs: OptionalDurationMs
4448
+ chain_id: Schema.Number,
4449
+ token_address: Schema.String,
4450
+ incident_kind: Schema.String,
4451
+ anchor_block_number: Schema.Number
3528
4452
  });
3529
4453
  Schema.Struct({
3530
4454
  name: Schema.Literal("auth_otp_requested"),
@@ -3626,38 +4550,6 @@ Schema.Struct({
3626
4550
  name: Schema.Literal("faucet_failed"),
3627
4551
  props: FaucetFailedProps
3628
4552
  });
3629
- Schema.Struct({
3630
- name: Schema.Literal("subaccount_created"),
3631
- props: SubaccountCreatedProps
3632
- });
3633
- Schema.Struct({
3634
- name: Schema.Literal("subaccount_renamed"),
3635
- props: SubaccountRenamedProps
3636
- });
3637
- Schema.Struct({
3638
- name: Schema.Literal("subaccount_deleted"),
3639
- props: SubaccountDeletedProps
3640
- });
3641
- Schema.Struct({
3642
- name: Schema.Literal("subaccount_op_failed"),
3643
- props: SubaccountOpFailedProps
3644
- });
3645
- Schema.Struct({
3646
- name: Schema.Literal("transfer_requested"),
3647
- props: TransferRequestedProps
3648
- });
3649
- Schema.Struct({
3650
- name: Schema.Literal("transfer_backend_received"),
3651
- props: TransferBackendReceivedProps
3652
- });
3653
- Schema.Struct({
3654
- name: Schema.Literal("transfer_confirmed"),
3655
- props: TransferConfirmedProps
3656
- });
3657
- Schema.Struct({
3658
- name: Schema.Literal("transfer_failed"),
3659
- props: TransferFailedProps
3660
- });
3661
4553
  Schema.Struct({
3662
4554
  name: Schema.Literal("org_create_started"),
3663
4555
  props: OrgCreateStartedProps
@@ -3690,97 +4582,45 @@ Schema.Struct({
3690
4582
  name: Schema.Literal("org_invite_accepted"),
3691
4583
  props: OrgInviteAcceptedProps
3692
4584
  });
3693
- Schema.Struct({
3694
- name: Schema.Literal("org_role_granted"),
3695
- props: OrgRoleGrantedProps
3696
- });
3697
- Schema.Struct({
3698
- name: Schema.Literal("org_member_active"),
3699
- props: OrgMemberActiveProps
3700
- });
3701
- Schema.Struct({
3702
- name: Schema.Literal("org_member_removed"),
3703
- props: OrgMemberRemovedProps
3704
- });
3705
4585
  Schema.Struct({
3706
4586
  name: Schema.Literal("org_invite_expired"),
3707
4587
  props: OrgInviteExpiredProps
3708
4588
  });
3709
4589
  Schema.Struct({
3710
- name: Schema.Literal("org_role_grant_failed"),
3711
- props: OrgRoleGrantFailedProps
3712
- });
3713
- Schema.Struct({
3714
- name: Schema.Literal("payment_requested"),
3715
- props: PaymentTargetTelemetryProps
3716
- });
3717
- Schema.Struct({
3718
- name: Schema.Literal("payment_resolved"),
3719
- props: PaymentTargetTelemetryProps
3720
- });
3721
- Schema.Struct({
3722
- name: Schema.Literal("payment_document_attached"),
3723
- props: PaymentTargetTelemetryProps
3724
- });
3725
- Schema.Struct({
3726
- name: Schema.Literal("payment_submitted"),
3727
- props: PaymentTargetTelemetryProps
4590
+ name: Schema.Literal("payment_initiated"),
4591
+ props: PaymentInitiatedProps
3728
4592
  });
3729
4593
  Schema.Struct({
3730
4594
  name: Schema.Literal("payment_settled"),
3731
- props: PaymentTargetTelemetryProps
3732
- });
3733
- Schema.Struct({
3734
- name: Schema.Literal("payment_claimed"),
3735
- props: PaymentTargetTelemetryProps
3736
- });
3737
- Schema.Struct({
3738
- name: Schema.Literal("payment_cancelled"),
3739
- props: PaymentTargetTelemetryProps
3740
- });
3741
- Schema.Struct({
3742
- name: Schema.Literal("payment_redirected"),
3743
- props: PaymentTargetTelemetryProps
4595
+ props: PaymentSettledL2Props
3744
4596
  });
3745
4597
  Schema.Struct({
3746
4598
  name: Schema.Literal("payment_failed"),
3747
- props: PaymentTargetTelemetryProps
3748
- });
3749
- Schema.Struct({
3750
- name: Schema.Literal("stream_created"),
3751
- props: StreamTargetTelemetryProps
3752
- });
3753
- Schema.Struct({
3754
- name: Schema.Literal("stream_claimed"),
3755
- props: StreamTargetTelemetryProps
3756
- });
3757
- Schema.Struct({
3758
- name: Schema.Literal("stream_cancelled"),
3759
- props: StreamTargetTelemetryProps
4599
+ props: PaymentFailedL2Props
3760
4600
  });
3761
4601
  Schema.Struct({
3762
- name: Schema.Literal("stream_completed"),
3763
- props: StreamTargetTelemetryProps
4602
+ name: Schema.Literal("deposit_initiated"),
4603
+ props: DepositInitiatedProps
3764
4604
  });
3765
4605
  Schema.Struct({
3766
- name: Schema.Literal("stream_failed"),
3767
- props: StreamTargetTelemetryProps
4606
+ name: Schema.Literal("deposit_settled"),
4607
+ props: DepositSettledProps
3768
4608
  });
3769
4609
  Schema.Struct({
3770
- name: Schema.Literal("withdrawal_requested"),
3771
- props: WithdrawalTargetTelemetryProps
4610
+ name: Schema.Literal("permission_mirror_verification"),
4611
+ props: PermissionMirrorVerificationProps
3772
4612
  });
3773
4613
  Schema.Struct({
3774
- name: Schema.Literal("withdrawal_submitted"),
3775
- props: WithdrawalTargetTelemetryProps
4614
+ name: Schema.Literal("movement_scan_window"),
4615
+ props: MovementScanWindowProps
3776
4616
  });
3777
4617
  Schema.Struct({
3778
- name: Schema.Literal("withdrawal_settled"),
3779
- props: WithdrawalTargetTelemetryProps
4618
+ name: Schema.Literal("movement_scan_checkpoint"),
4619
+ props: MovementScanCheckpointProps
3780
4620
  });
3781
4621
  Schema.Struct({
3782
- name: Schema.Literal("withdrawal_failed"),
3783
- props: WithdrawalTargetTelemetryProps
4622
+ name: Schema.Literal("movement_scan_incident"),
4623
+ props: MovementScanIncidentProps
3784
4624
  });
3785
4625
  function redactTelemetryEvent(event, options = {}) {
3786
4626
  const props = redactTelemetryProps(event.name, event.props, options);
@@ -4167,7 +5007,8 @@ const accountLane = (input, config, session, send) => Effect.gen(function* () {
4167
5007
  if (Result.isFailure(existing)) return yield* failAt("provision", existing.failure);
4168
5008
  const provisioned = yield* Effect.result(existing.success === null ? call("smart-account.provision", input.ports.smartAccount.provision({
4169
5009
  authUserId: toAuthUserId(session.authUserId),
4170
- chainId: toChainId(input.chainId)
5010
+ chainId: toChainId(input.chainId),
5011
+ email: toEmail(session.email)
4171
5012
  })) : Effect.succeed(existing.success));
4172
5013
  if (Result.isFailure(provisioned)) return yield* failAt("provision", provisioned.failure);
4173
5014
  const account = provisioned.success;
@@ -4817,7 +5658,8 @@ function provisionSmartAccountProgram() {
4817
5658
  if (session === null) return yield* Effect.fail(Errors.notAuthenticated());
4818
5659
  const provisioned = yield* deps.smartAccountPort.provision({
4819
5660
  authUserId: session.authUserId,
4820
- chainId: deps.chainId
5661
+ chainId: deps.chainId,
5662
+ email: session.email
4821
5663
  }).pipe(Effect.mapError((failure) => failure.publicError));
4822
5664
  yield* Effect.promise(() => emitProvisioningTelemetry(deps.telemetry, provisioned));
4823
5665
  return provisioned;
@@ -4903,11 +5745,6 @@ function makeIdentityMethods(deps) {
4903
5745
  function moneyToWeiAmount(money) {
4904
5746
  return toWei(money);
4905
5747
  }
4906
- function transferDirection(from, to) {
4907
- if (from === "main") return "add";
4908
- if (to === "main") return "out";
4909
- return "between";
4910
- }
4911
5748
  /** Fire-and-forget emit through an optional port; never throws. */
4912
5749
  async function emitMoneyTelemetry(telemetry, event) {
4913
5750
  if (telemetry === void 0) return;
@@ -4941,52 +5778,18 @@ function emitAccountBalanceFailed(telemetry, reason) {
4941
5778
  props: { reason }
4942
5779
  });
4943
5780
  }
4944
- function emitTransferRequested(telemetry, input) {
4945
- let amount;
4946
- try {
4947
- amount = moneyToWeiAmount(input.amount);
4948
- } catch (cause) {
4949
- reportMoneyTelemetryFailure("defect", "transfer_requested", cause);
4950
- return Promise.resolve();
4951
- }
4952
- return emitMoneyTelemetry(telemetry, {
4953
- name: "transfer_requested",
4954
- props: {
4955
- amount,
4956
- direction: transferDirection(input.from, input.to)
4957
- }
4958
- });
4959
- }
4960
- function emitTransferFailed(telemetry, reason) {
4961
- return emitMoneyTelemetry(telemetry, {
4962
- name: "transfer_failed",
4963
- props: { reason }
4964
- });
4965
- }
4966
- function emitSubAccountCreated(telemetry, subAccountId) {
4967
- return emitMoneyTelemetry(telemetry, {
4968
- name: "subaccount_created",
4969
- props: { sub_account_id: subAccountId }
4970
- });
4971
- }
4972
- function emitSubAccountRenamed(telemetry, subAccountId) {
4973
- return emitMoneyTelemetry(telemetry, {
4974
- name: "subaccount_renamed",
4975
- props: { sub_account_id: subAccountId }
4976
- });
4977
- }
4978
- function emitSubAccountDeleted(telemetry, subAccountId) {
5781
+ function emitDepositInitiated(telemetry) {
4979
5782
  return emitMoneyTelemetry(telemetry, {
4980
- name: "subaccount_deleted",
4981
- props: { sub_account_id: subAccountId }
5783
+ name: "deposit_initiated",
5784
+ props: {}
4982
5785
  });
4983
5786
  }
4984
- function emitSubAccountOpFailed(telemetry, op, reason) {
5787
+ function emitPaymentInitiated(telemetry, input) {
4985
5788
  return emitMoneyTelemetry(telemetry, {
4986
- name: "subaccount_op_failed",
5789
+ name: "payment_initiated",
4987
5790
  props: {
4988
- op,
4989
- reason
5791
+ kind: input.kind,
5792
+ payment_id: input.paymentId
4990
5793
  }
4991
5794
  });
4992
5795
  }
@@ -5120,23 +5923,160 @@ const financialOpsContract = {
5120
5923
  addDestination: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].add),
5121
5924
  listDestinations: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].list),
5122
5925
  removeDestination: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].remove),
5123
- pay: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/mutations"].pay),
5124
- payout: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].payout),
5125
- withdraw: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/mutations"].withdraw),
5126
- markPaymentSettled: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].markPaymentSettled),
5127
- markWithdrawalSettled: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].markWithdrawalSettled),
5128
- recordOrgPayment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].recordOrgPayment),
5129
- markCommitmentCreated: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].markCommitmentCreated),
5130
- claimCommitment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].claimCommitment),
5131
- cancelCommitment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].cancelCommitment),
5132
- redirectCommitment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/actions"].redirectCommitment),
5133
5926
  listPayments: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].listPayments),
5134
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),
5135
5931
  verifyPaymentDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].verifyPaymentDocument),
5136
- renderStoredDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].renderStoredDocument),
5137
- getCommitmentRef: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].getCommitmentRef)
5932
+ renderStoredDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].renderStoredDocument)
5138
5933
  };
5139
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
5140
6080
  //#region src/surface/money.ts
5141
6081
  function actorReferenceToBackend(actor) {
5142
6082
  if (actor === void 0) return void 0;
@@ -5150,12 +6090,74 @@ function actorReferenceToBackend(actor) {
5150
6090
  case "org": return actor;
5151
6091
  }
5152
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
+ }
5153
6112
  function makeFinancialOpsMethods(deps) {
5154
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
+ };
5155
6157
  return {
5156
6158
  me: {
5157
6159
  get: (options) => runIfActive(options?.signal, "me.get", () => deps.convexCall.query(fns.me, {})),
5158
- 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)))))
5159
6161
  },
5160
6162
  handles: { resolve: (handle, options) => runIfActive(options?.signal, "handles.resolve", () => deps.convexCall.query(fns.resolveHandle, { handle })) },
5161
6163
  payees: {
@@ -5169,8 +6171,8 @@ function makeFinancialOpsMethods(deps) {
5169
6171
  },
5170
6172
  targets: { resolve: async (reference, options) => {
5171
6173
  switch (reference.kind) {
5172
- case "handle": return mapOk$1(await runIfActive(options?.signal, "targets.resolve.handle", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle })), (target) => resolvedTargetFromResolution(reference, target));
5173
- 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));
5174
6176
  case "organization": {
5175
6177
  const resolved = await runIfActive(options?.signal, "targets.resolve.organization", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle }));
5176
6178
  if (!resolved.ok) return {
@@ -5220,7 +6222,7 @@ function makeFinancialOpsMethods(deps) {
5220
6222
  error: Errors.invalidInput("target", DESTINATION_SCOPE_MESSAGE)
5221
6223
  };
5222
6224
  const backendActor = actorReferenceToBackend(input.actor);
5223
- 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, {
5224
6226
  ...backendActor === void 0 ? {} : { actor: backendActor },
5225
6227
  ...isSelfTarget(scopeValue) ? { self: true } : { ref: scopeValue },
5226
6228
  kind: destinationKindToBackend(input.kind),
@@ -5235,7 +6237,7 @@ function makeFinancialOpsMethods(deps) {
5235
6237
  error: scope.error
5236
6238
  };
5237
6239
  const scopeValue = scope.value;
5238
- 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, {
5239
6241
  ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
5240
6242
  ...scopeValue !== void 0 && isSelfTarget(scopeValue) ? { self: true } : {},
5241
6243
  ...scopeValue !== void 0 && !isSelfTarget(scopeValue) ? { ref: scopeValue } : {}
@@ -5247,117 +6249,49 @@ function makeFinancialOpsMethods(deps) {
5247
6249
  }))
5248
6250
  },
5249
6251
  payments: {
5250
- pay: async (input, options) => {
5251
- if (actorReferenceToBackend(input.actor)?.kind === "org") return {
5252
- ok: false,
5253
- error: Errors.notImplemented("payments", "pay.organizationActor")
5254
- };
5255
- const to = normalizeTargetForBackend(input.to, "to");
5256
- if (!to.ok) return {
5257
- ok: false,
5258
- error: to.error
5259
- };
5260
- return mapOk$1(await runIfActive(options?.signal, "payments.pay", () => deps.convexCall.mutation(fns.pay, {
5261
- to: to.value,
5262
- amount: input.amount,
5263
- ...input.paymentType === void 0 ? {} : { paymentType: input.paymentType },
5264
- ...input.document === void 0 ? {} : { document: input.document },
5265
- ...input.timing === void 0 ? {} : { timing: input.timing },
5266
- ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
5267
- })), normalizePaymentTiming$1);
5268
- },
5269
- payout: async (input, options) => mapOk$1(await runIfActive(options?.signal, "payments.payout", () => deps.convexCall.mutation(fns.payout, {
5270
- ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
5271
- destinationId: input.destinationId,
5272
- amount: input.amount
5273
- })), normalizePaymentTiming$1),
5274
- withdraw: (input, options) => runIfActive(options?.signal, "payments.withdraw", () => deps.convexCall.mutation(fns.withdraw, {
5275
- to: input.to,
5276
- amount: input.amount,
5277
- document: input.document
5278
- })),
5279
- list: async (options) => mapOk$1(await runIfActive(options?.signal, "payments.list", () => deps.convexCall.query(fns.listPayments, {})), (payments) => payments.map(normalizePaymentTiming$1)),
5280
- 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)),
5281
- cancel: (paymentId, options) => {
5282
- if (options?.signal?.aborted) return Promise.resolve({
5283
- ok: false,
5284
- error: Errors.cancelled({ operation: "payments.cancel" })
5285
- });
5286
- return Promise.resolve({
5287
- ok: false,
5288
- error: Errors.notImplemented("payments", "cancel")
5289
- });
5290
- },
5291
- _internal: {
5292
- markSettled: (input, options) => runIfActive(options?.signal, "payments.markSettled", () => deps.convexCall.action(fns.markPaymentSettled, {
5293
- paymentId: input.paymentId,
5294
- userOpHash: input.evidence.userOpHash,
5295
- txHash: input.evidence.txHash
5296
- })),
5297
- markWithdrawalSettled: (input, options) => runIfActive(options?.signal, "payments.markWithdrawalSettled", () => deps.convexCall.action(fns.markWithdrawalSettled, {
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",
5298
6269
  paymentId: input.paymentId,
5299
- userOpHash: input.evidence.userOpHash,
5300
- txHash: input.evidence.txHash
5301
- })),
5302
- recordOrgPayment: (input, options) => runIfActive(options?.signal, "payments.recordOrgPayment", () => deps.convexCall.action(fns.recordOrgPayment, {
5303
- orgId: input.orgId,
5304
- recipientLabel: input.recipientLabel,
5305
- ...input.recipientKind === void 0 ? {} : { recipientKind: input.recipientKind },
5306
- ...input.recipientRef === void 0 ? {} : { recipientRef: input.recipientRef },
5307
- ...input.recipientPayeeId === void 0 ? {} : { recipientPayeeId: input.recipientPayeeId },
5308
- recipientSafeAddress: input.recipientSafeAddress,
5309
- amount: input.amount,
5310
- paymentType: input.paymentType,
5311
- ...input.document === void 0 ? {} : { document: input.document },
5312
- orgSafeAddress: input.orgSafeAddress,
5313
- occurrenceIndex: input.occurrenceIndex,
5314
- userOpHash: input.evidence.userOpHash,
5315
- txHash: input.evidence.txHash
5316
- })),
5317
- markCommitmentCreated: (input, options) => runIfActive(options?.signal, "payments.markCommitmentCreated", () => deps.convexCall.action(fns.markCommitmentCreated, {
5318
- paymentId: input.paymentId,
5319
- onchainCommitmentId: input.onchainCommitmentId,
5320
- userOpHash: input.evidence.userOpHash,
5321
- txHash: input.evidence.txHash
5322
- })),
5323
- claim: (input, options) => runIfActive(options?.signal, "payments.claim", () => deps.convexCall.action(fns.claimCommitment, {
5324
- paymentId: input.paymentId,
5325
- userOpHash: input.evidence.userOpHash,
5326
- txHash: input.evidence.txHash
5327
- })),
5328
- cancel: (input, options) => runIfActive(options?.signal, "payments.cancel", () => deps.convexCall.action(fns.cancelCommitment, {
5329
- paymentId: input.paymentId,
5330
- userOpHash: input.evidence.userOpHash,
5331
- txHash: input.evidence.txHash,
5332
- ...input.document === void 0 ? {} : { document: input.document }
5333
- })),
5334
- redirect: async (input, options) => {
5335
- const to = normalizeRefForBackend(input.to, "to");
5336
- if (!to.ok) return {
5337
- ok: false,
5338
- error: to.error
5339
- };
5340
- return mapOk$1(await runIfActive(options?.signal, "payments.redirect", () => deps.convexCall.action(fns.redirectCommitment, {
5341
- paymentId: input.paymentId,
5342
- to: to.value,
5343
- userOpHash: input.evidence.userOpHash,
5344
- txHash: input.evidence.txHash,
5345
- ...input.document === void 0 ? {} : { document: input.document }
5346
- })), normalizePaymentTiming$1);
5347
- },
5348
- commitmentRef: (paymentId, options) => runIfActive(options?.signal, "payments.commitmentRef", () => deps.convexCall.query(fns.getCommitmentRef, { paymentId }))
6270
+ recipient: recipient.value
6271
+ }, options?.signal);
5349
6272
  }
5350
6273
  },
5351
- activity: { list: (params, options) => {
5352
- if (options?.signal?.aborted) return Promise.resolve({
5353
- ok: false,
5354
- error: Errors.cancelled({ operation: "activity.list" })
5355
- });
5356
- return Promise.resolve({
5357
- ok: false,
5358
- error: Errors.notImplemented("activity", "list")
5359
- });
5360
- } },
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
+ },
5361
6295
  offramp: {
5362
6296
  quote: (input, options) => {
5363
6297
  if (options?.signal?.aborted) return Promise.resolve({
@@ -5386,18 +6320,6 @@ function makeFinancialOpsMethods(deps) {
5386
6320
  }
5387
6321
  };
5388
6322
  }
5389
- function refToRecipientString(ref) {
5390
- if (typeof ref === "string") throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
5391
- if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
5392
- switch (ref.kind) {
5393
- case "handle": return handleRefValue(ref.handle, "handle");
5394
- case "email": return nonEmptyRefValue(ref.email, "email");
5395
- case "orgHandle": return nonEmptyRefValue(ref.orgHandle, "orgHandle");
5396
- case "capxulUserId": return nonEmptyRefValue(ref.capxulUserId, "capxulUserId");
5397
- case "payeeId": return nonEmptyRefValue(ref.payeeId, "payeeId");
5398
- default: throw Errors.invalidInput("to", "recipient must be a known Ref variant");
5399
- }
5400
- }
5401
6323
  function nonEmptyRefValue(value, field) {
5402
6324
  const trimmed = value.trim();
5403
6325
  if (trimmed.length === 0) throw Errors.invalidInput(field, "Ref value must be non-empty");
@@ -5645,14 +6567,14 @@ function normalizeRefForBackend(ref, field) {
5645
6567
  };
5646
6568
  }
5647
6569
  }
5648
- function normalizePaymentTiming$1(payment) {
6570
+ function normalizePaymentTiming(payment) {
5649
6571
  const { release: _release, ...rest } = payment;
5650
6572
  return {
5651
6573
  ...rest,
5652
6574
  timing: payment.timing ?? payment.release ?? { kind: "instant" }
5653
6575
  };
5654
6576
  }
5655
- function mapOk$1(result, f) {
6577
+ function mapOk(result, f) {
5656
6578
  if (!result.ok) return result;
5657
6579
  try {
5658
6580
  return {
@@ -5725,120 +6647,157 @@ function makeSystemMethods(deps) {
5725
6647
  return { health: (nonce, options) => runIfActive(options?.signal, "system.health", () => deps.convexCall.query(healthQuery, { nonce })) };
5726
6648
  }
5727
6649
  //#endregion
5728
- //#region src/surface/sub-accounts-deps.ts
5729
- var SubAccountsDepsTag = class extends Context.Service()("@capxul/sdk/SubAccountsDeps") {};
5730
- function subAccountsDepsLayer(deps) {
5731
- return Layer.succeed(SubAccountsDepsTag, deps);
5732
- }
5733
- function createSubAccountProgram(accountId, name) {
5734
- return Effect.gen(function* () {
5735
- const deps = yield* SubAccountsDepsTag;
5736
- const created = yield* deps.subAccountPort.create({
5737
- accountId,
5738
- name
5739
- }).pipe(Effect.tapError((error) => Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, "create", error.publicCode))), Effect.mapError((error) => error.publicError));
5740
- yield* Effect.promise(() => emitSubAccountCreated(deps.telemetry, created.id));
5741
- return created;
5742
- });
5743
- }
5744
- function getSubAccountProgram(subAccountId) {
5745
- return Effect.gen(function* () {
5746
- return yield* (yield* SubAccountsDepsTag).subAccountPort.get({ subAccountId }).pipe(Effect.mapError((error) => error.publicError));
5747
- });
5748
- }
5749
- function listSubAccountsProgram(accountId) {
5750
- return Effect.gen(function* () {
5751
- return yield* (yield* SubAccountsDepsTag).subAccountPort.list({ accountId }).pipe(Effect.mapError((error) => error.publicError));
5752
- });
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;
5753
6656
  }
5754
- function renameSubAccountProgram(subAccountId, name) {
5755
- return Effect.gen(function* () {
5756
- const deps = yield* SubAccountsDepsTag;
5757
- const renamed = yield* deps.subAccountPort.rename({
5758
- subAccountId,
5759
- name
5760
- }).pipe(Effect.tapError((error) => Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, "rename", error.publicCode))), Effect.mapError((error) => error.publicError));
5761
- yield* Effect.promise(() => emitSubAccountRenamed(deps.telemetry, renamed.id));
5762
- return renamed;
5763
- });
6657
+ function fail$1(cause, operation) {
6658
+ return {
6659
+ ok: false,
6660
+ error: cause instanceof CapxulError ? cause : Errors.providerError("wallet-signer", operation, cause)
6661
+ };
5764
6662
  }
5765
- function deleteSubAccountProgram(subAccountId) {
5766
- return Effect.gen(function* () {
5767
- const deps = yield* SubAccountsDepsTag;
5768
- yield* deps.subAccountPort.delete({ subAccountId }).pipe(Effect.tapError((error) => Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, "delete", error.publicCode))), Effect.mapError((error) => error.publicError));
5769
- yield* Effect.promise(() => emitSubAccountDeleted(deps.telemetry, subAccountId));
5770
- });
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
+ } }));
5771
6713
  }
5772
- function transferSubAccountProgram(input) {
5773
- return Effect.gen(function* () {
5774
- const deps = yield* SubAccountsDepsTag;
5775
- yield* Effect.promise(() => emitTransferRequested(deps.telemetry, {
5776
- amount: input.amount,
5777
- from: input.from,
5778
- to: input.to
5779
- }));
5780
- return yield* deps.subAccountPort.transfer(input).pipe(Effect.tapError((error) => Effect.promise(() => emitTransferFailed(deps.telemetry, error.publicCode))), Effect.mapError((error) => error.publicError));
5781
- });
6714
+ function makePermissionMethods(deps, orgId) {
6715
+ const reads = deps.permissionFunctions ?? permissionContract;
6716
+ return {
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
6744
+ };
6745
+ }
6746
+ };
5782
6747
  }
5783
6748
  //#endregion
5784
- //#region src/surface/sub-accounts.ts
5785
- function makeSubAccountsMethods(deps) {
5786
- const layer = subAccountsDepsLayer(deps);
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
+ };
5787
6778
  return {
5788
- async create(accountId, input, options) {
5789
- if (options?.signal?.aborted) return {
5790
- ok: false,
5791
- error: Errors.cancelled({ operation: "subAccounts.create" })
5792
- };
5793
- return toCapxulResult(createSubAccountProgram(accountId, input.name), layer);
5794
- },
5795
- async get(subAccountId, options) {
5796
- if (options?.signal?.aborted) return {
5797
- ok: false,
5798
- error: Errors.cancelled({ operation: "subAccounts.get" })
5799
- };
5800
- return toCapxulResult(getSubAccountProgram(subAccountId), layer);
5801
- },
5802
- async list(accountId, options) {
5803
- if (options?.signal?.aborted) return {
5804
- ok: false,
5805
- error: Errors.cancelled({ operation: "subAccounts.list" })
5806
- };
5807
- return toCapxulResult(listSubAccountsProgram(accountId), layer);
5808
- },
5809
- async rename(subAccountId, name, options) {
5810
- if (options?.signal?.aborted) return {
5811
- ok: false,
5812
- error: Errors.cancelled({ operation: "subAccounts.rename" })
5813
- };
5814
- return toCapxulResult(renameSubAccountProgram(subAccountId, name), layer);
5815
- },
5816
- async delete(subAccountId, options) {
5817
- if (options?.signal?.aborted) 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 ? {
5818
6790
  ok: false,
5819
- error: Errors.cancelled({ operation: "subAccounts.delete" })
6791
+ error: Errors.unknown()
6792
+ } : {
6793
+ ok: true,
6794
+ value: payment
5820
6795
  };
5821
- return toCapxulResult(deleteSubAccountProgram(subAccountId), layer);
5822
6796
  },
5823
- async transfer(input, options) {
5824
- if (options?.signal?.aborted) return {
5825
- ok: false,
5826
- error: Errors.cancelled({ operation: "subAccounts.transfer" })
5827
- };
5828
- return toCapxulResult(transferSubAccountProgram(input), layer);
5829
- }
6797
+ payBatch: (input, options) => execute(input, options?.signal)
5830
6798
  };
5831
6799
  }
5832
6800
  //#endregion
5833
- //#region src/contract/payroll.ts
5834
- const payrollContract = {
5835
- add: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].add),
5836
- list: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].list),
5837
- update: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].update),
5838
- remove: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].remove),
5839
- run: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/payrollRoster"].run)
5840
- };
5841
- //#endregion
5842
6801
  //#region src/surface/_shared/org-telemetry.ts
5843
6802
  /** Extract the domain from an email for telemetry (never the local part / PII). */
5844
6803
  function emailDomain$1(email) {
@@ -5934,59 +6893,11 @@ function isOrgTelemetryDebugEnabled() {
5934
6893
  return globalThis.process?.env?.CAPXUL_DEBUG_TELEMETRY === "1";
5935
6894
  }
5936
6895
  //#endregion
5937
- //#region src/domain/org/spend-gate.ts
5938
- function evaluateSpendGate(input) {
5939
- if (!input.activeMember) return reject("not_member", Errors.invalidInput("member", "you are not an active member"));
5940
- if (!recipientAllowed(input.recipients, input.recipient)) return reject("invalid_recipient", Errors.invalidRecipient("recipient is not allowed by this role"));
5941
- if (!subAccountAllowed(input.subAccounts, input.subAccountId)) return reject("wrong_envelope", Errors.invalidInput("subAccountId", "sub-account not in scope for this role"));
5942
- const amount = parseRaw(input.amountRaw, "amountRaw");
5943
- const balance = parseRaw(input.subAccountBalanceRaw, "subAccountBalanceRaw");
5944
- if (amount > balance) return reject("insufficient_subaccount_balance", Errors.insufficientBalance(input.currency, balance.toString(10), amount.toString(10)));
5945
- const perTxCap = parseOptionalRaw(input.perTxCapRaw, "perTxCapRaw");
5946
- if (perTxCap !== null && amount > perTxCap) return reject("over_cap", Errors.insufficientBalance("role per-transaction cap", perTxCap.toString(10), amount.toString(10)));
5947
- const perDayCap = parseOptionalRaw(input.perDayCapRaw, "perDayCapRaw");
5948
- if (perDayCap !== null) {
5949
- const remaining = perDayCap - (parseOptionalRaw(input.spentTodayRaw, "spentTodayRaw") ?? 0n);
5950
- if (remaining < amount) return reject("daily_cap_exhausted", Errors.insufficientBalance("role daily cap", remaining.toString(10), amount.toString(10)));
5951
- }
5952
- return { ok: true };
5953
- }
5954
- function reject(reason, error) {
5955
- return {
5956
- ok: false,
5957
- reason,
5958
- error
5959
- };
5960
- }
5961
- function recipientAllowed(recipients, recipient) {
5962
- if (recipients === "anyone") return true;
5963
- const normalized = String(recipient).toLowerCase();
5964
- return recipients.some((allowed) => String(allowed).toLowerCase() === normalized);
5965
- }
5966
- function subAccountAllowed(scope, subAccountId) {
5967
- if (scope.scope === "all") return true;
5968
- return scope.subAccountIds.includes(subAccountId);
5969
- }
5970
- function parseOptionalRaw(value, field) {
5971
- if (value === null || value === void 0) return null;
5972
- return parseRaw(value, field);
5973
- }
5974
- function parseRaw(value, field) {
5975
- if (!/^[0-9]+$/.test(value)) throw Errors.invalidInput(field, "must be a non-negative integer string");
5976
- return BigInt(value);
5977
- }
5978
- //#endregion
5979
6896
  //#region src/surface/org-deps.ts
5980
6897
  var OrgDepsTag = class extends Context.Service()("@capxul/sdk/OrgDeps") {};
5981
6898
  function orgDepsLayer(deps) {
5982
6899
  return Layer.succeed(OrgDepsTag, deps);
5983
6900
  }
5984
- function isHermeticOrgDeps(deps) {
5985
- return deps.orgPort === void 0 && deps.orgRolesDeploymentPort === void 0 && deps.orgSpendPort === void 0;
5986
- }
5987
- function missingLiveOrgDep(portName) {
5988
- return Errors.invalidInput("orgDeps", `${portName} is required in live org mode`);
5989
- }
5990
6901
  /** Zero `Money` in the USDX-backed display currency (a fresh Org's treasury). */
5991
6902
  function zeroMoney() {
5992
6903
  return fromWei("0", 6, "USD");
@@ -6043,14 +6954,8 @@ function recipientsFromConfig(toRecipients) {
6043
6954
  if (toRecipients === void 0 || toRecipients === "anyone") return toRecipients;
6044
6955
  return toRecipients.map((recipient) => toAddress(recipient));
6045
6956
  }
6046
- function subAccountsFromConfig(subAccounts) {
6047
- if (subAccounts === void 0) return void 0;
6048
- if (subAccounts.scope === "all") return { scope: "all" };
6049
- return { scope: subAccounts.scope.map((subAccountId) => toSubAccountId(subAccountId)) };
6050
- }
6051
6957
  function roleDefinitionFromConfig(definition) {
6052
6958
  const toRecipients = recipientsFromConfig(definition.spend?.toRecipients);
6053
- const subAccounts = subAccountsFromConfig(definition.subAccounts);
6054
6959
  return {
6055
6960
  label: definition.label,
6056
6961
  ...definition.spend === void 0 ? {} : { spend: {
@@ -6058,7 +6963,6 @@ function roleDefinitionFromConfig(definition) {
6058
6963
  ...definition.spend.perDay === void 0 ? {} : { perDay: moneyFromConfig(definition.spend.perDay) },
6059
6964
  ...toRecipients === void 0 ? {} : { toRecipients }
6060
6965
  } },
6061
- ...subAccounts === void 0 ? {} : { subAccounts },
6062
6966
  ...definition.canManageMembers === void 0 ? {} : { canManageMembers: definition.canManageMembers },
6063
6967
  ...definition.canManageRoles === void 0 ? {} : { canManageRoles: definition.canManageRoles }
6064
6968
  };
@@ -6084,36 +6988,6 @@ function hermeticMember(input) {
6084
6988
  revokeTxHash: input.revokeTxHash ?? null
6085
6989
  };
6086
6990
  }
6087
- function hermeticSpendAuthority(input) {
6088
- return {
6089
- activeMember: true,
6090
- subAccountBalanceRaw: "100000000000",
6091
- recipients: "anyone",
6092
- subAccounts: {
6093
- scope: "only",
6094
- subAccountIds: [input.from]
6095
- },
6096
- perTxCapRaw: "25000000000",
6097
- perDayCapRaw: "100000000000",
6098
- spentTodayRaw: "0",
6099
- role: "Finance Manager"
6100
- };
6101
- }
6102
- function spendGateInput(input) {
6103
- return {
6104
- activeMember: input.authority.activeMember,
6105
- subAccountId: input.spend.from,
6106
- subAccountBalanceRaw: input.authority.subAccountBalanceRaw,
6107
- amountRaw: input.amountRaw,
6108
- currency: input.currency,
6109
- recipient: input.spend.to,
6110
- recipients: input.authority.recipients,
6111
- subAccounts: input.authority.subAccounts,
6112
- ...input.authority.perTxCapRaw === void 0 ? {} : { perTxCapRaw: input.authority.perTxCapRaw },
6113
- ...input.authority.perDayCapRaw === void 0 ? {} : { perDayCapRaw: input.authority.perDayCapRaw },
6114
- ...input.authority.spentTodayRaw === void 0 ? {} : { spentTodayRaw: input.authority.spentTodayRaw }
6115
- };
6116
- }
6117
6991
  function createOrgProgram(input) {
6118
6992
  return Effect.gen(function* () {
6119
6993
  const deps = yield* OrgDepsTag;
@@ -6205,14 +7079,6 @@ function listRolesProgram(orgId) {
6205
7079
  return startupRoleViews(orgId);
6206
7080
  });
6207
7081
  }
6208
- function deployRolesProgram(orgId) {
6209
- return Effect.gen(function* () {
6210
- const deps = yield* OrgDepsTag;
6211
- if (deps.orgRolesDeploymentPort !== void 0) return (yield* deps.orgRolesDeploymentPort.deployRoles({ orgId }).pipe(Effect.mapError((error) => error.publicError))).roles;
6212
- if (!isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgRolesDeploymentPort"));
6213
- return startupRoleViews(orgId);
6214
- });
6215
- }
6216
7082
  function listMembersProgram(orgId) {
6217
7083
  return Effect.gen(function* () {
6218
7084
  const deps = yield* OrgDepsTag;
@@ -6248,188 +7114,6 @@ function detectAndAcceptPendingInvitationsProgram() {
6248
7114
  return { matched: [] };
6249
7115
  });
6250
7116
  }
6251
- function assignRoleProgram(orgId, input) {
6252
- return Effect.gen(function* () {
6253
- const deps = yield* OrgDepsTag;
6254
- if (deps.orgRolesDeploymentPort !== void 0) return yield* deps.orgRolesDeploymentPort.grantRole({
6255
- orgId,
6256
- input
6257
- }).pipe(Effect.mapError((error) => error.publicError));
6258
- if (!isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgRolesDeploymentPort"));
6259
- return hermeticMember({
6260
- orgId,
6261
- email: "member@example.com",
6262
- role: input.role,
6263
- status: "active",
6264
- personalSafeAddress: input.memberSafeAddress,
6265
- grantTxHash: `0x${"0".repeat(64)}`
6266
- });
6267
- });
6268
- }
6269
- function removeMemberProgram(orgId, input) {
6270
- return Effect.gen(function* () {
6271
- const deps = yield* OrgDepsTag;
6272
- if (deps.orgRolesDeploymentPort !== void 0) return yield* deps.orgRolesDeploymentPort.revokeRole({
6273
- orgId,
6274
- input
6275
- }).pipe(Effect.mapError((error) => error.publicError));
6276
- if (!isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgRolesDeploymentPort"));
6277
- });
6278
- }
6279
- /**
6280
- * Build a leak-safe settled `Payment` for an org spend (G4 · #547). NO `txHash`
6281
- * / userOp / Safe internals and NO raw recipient address ever reach this record
6282
- * — only the validated recipient ref label + the committed `documentHash`.
6283
- */
6284
- function leakSafeOrgPayment(input) {
6285
- const now = Date.now();
6286
- const id = `payment_${toHexSeed(`${input.orgId}:${input.to}:${input.amount.value}:${input.index}`)}`;
6287
- const money = {
6288
- currency: String(input.amount.currency),
6289
- value: input.amount.value,
6290
- decimals: input.amount.decimals
6291
- };
6292
- return {
6293
- id,
6294
- status: "settled",
6295
- amount: money,
6296
- paymentType: input.paymentType,
6297
- recipient: {
6298
- kind: "email",
6299
- label: input.to
6300
- },
6301
- documents: input.documentHash === void 0 ? [] : [{
6302
- documentHash: input.documentHash,
6303
- kind: input.paymentType === "payroll" ? "payslip" : "memo"
6304
- }],
6305
- timing: { kind: "instant" },
6306
- released: money,
6307
- availableToClaim: {
6308
- ...money,
6309
- value: "0"
6310
- },
6311
- createdAt: now,
6312
- updatedAt: now
6313
- };
6314
- }
6315
- /** Resolve authority + run the spend gate for one org spend run (G4 · #547). */
6316
- function gateOneRun(input) {
6317
- return Effect.gen(function* () {
6318
- const amountRaw = yield* Effect.try({
6319
- try: () => toWei(input.amount),
6320
- catch: (cause) => Errors.invalidInput("amount", cause instanceof Error ? cause.message : "invalid money")
6321
- });
6322
- const currency = String(input.amount.currency);
6323
- const spendShaped = {
6324
- from: input.from,
6325
- to: toAddress(`0x${"0".repeat(40)}`),
6326
- amount: input.amount
6327
- };
6328
- const authority = input.deps.orgSpendPort === void 0 ? hermeticSpendAuthority(spendShaped) : yield* input.deps.orgSpendPort.readSpendAuthority({
6329
- orgId: input.orgId,
6330
- input: spendShaped,
6331
- amountRaw
6332
- }).pipe(Effect.mapError((error) => error.publicError));
6333
- const accumulated = BigInt(input.accumulatedRaw ?? "0");
6334
- const baseGateInput = spendGateInput({
6335
- authority,
6336
- spend: spendShaped,
6337
- amountRaw,
6338
- currency
6339
- });
6340
- const decision = yield* Effect.try({
6341
- try: () => evaluateSpendGate({
6342
- ...baseGateInput,
6343
- recipient: input.to,
6344
- subAccountBalanceRaw: subtractNonNegative(baseGateInput.subAccountBalanceRaw, accumulated),
6345
- spentTodayRaw: (BigInt(authority.spentTodayRaw ?? "0") + accumulated).toString(10)
6346
- }),
6347
- catch: (cause) => isCapxulError(cause) ? cause : Errors.unknown(cause)
6348
- });
6349
- if (!decision.ok) return yield* Effect.fail(decision.error);
6350
- return {
6351
- authority,
6352
- amountRaw
6353
- };
6354
- });
6355
- }
6356
- /** Subtract `delta` from a raw amount, flooring at zero (never negative). */
6357
- function subtractNonNegative(raw, delta) {
6358
- const remaining = BigInt(raw) - delta;
6359
- return (remaining < 0n ? 0n : remaining).toString(10);
6360
- }
6361
- function spendViaPaymentsProgram(orgId, input) {
6362
- return Effect.gen(function* () {
6363
- const deps = yield* OrgDepsTag;
6364
- if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
6365
- const to = yield* Effect.try({
6366
- try: () => refToRecipientString(input.to),
6367
- catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
6368
- });
6369
- const gated = yield* gateOneRun({
6370
- deps,
6371
- orgId,
6372
- from: input.from,
6373
- to,
6374
- amount: input.amount
6375
- });
6376
- const paymentType = input.paymentType ?? "unspecified";
6377
- if (deps.orgSpendPort?.submitSpendViaPayments !== void 0) return yield* deps.orgSpendPort.submitSpendViaPayments({
6378
- orgId,
6379
- input,
6380
- amountRaw: gated.amountRaw,
6381
- authority: gated.authority
6382
- }).pipe(Effect.mapError((error) => error.publicError));
6383
- return leakSafeOrgPayment({
6384
- orgId,
6385
- to,
6386
- amount: input.amount,
6387
- paymentType,
6388
- index: 0
6389
- });
6390
- });
6391
- }
6392
- function batchPayrollProgram(orgId, input) {
6393
- return Effect.gen(function* () {
6394
- const deps = yield* OrgDepsTag;
6395
- if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
6396
- if (input.runs.length === 0) return yield* Effect.fail(Errors.invalidInput("runs", "payroll batch must include at least one run"));
6397
- const gated = [];
6398
- const recipients = yield* Effect.try({
6399
- try: () => input.runs.map((run) => refToRecipientString(run.to)),
6400
- catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
6401
- });
6402
- let accumulatedRaw = 0n;
6403
- for (const [index, run] of input.runs.entries()) {
6404
- const result = yield* gateOneRun({
6405
- deps,
6406
- orgId,
6407
- from: input.from,
6408
- to: recipients[index],
6409
- amount: run.amount,
6410
- accumulatedRaw: accumulatedRaw.toString(10)
6411
- });
6412
- accumulatedRaw += BigInt(result.amountRaw);
6413
- gated.push(result);
6414
- }
6415
- if (deps.orgSpendPort?.submitBatchPayroll !== void 0) return yield* deps.orgSpendPort.submitBatchPayroll({
6416
- orgId,
6417
- from: input.from,
6418
- runs: input.runs.map((run, index) => ({
6419
- run,
6420
- amountRaw: gated[index].amountRaw
6421
- })),
6422
- authorities: gated.map((g) => g.authority)
6423
- }).pipe(Effect.mapError((error) => error.publicError));
6424
- return input.runs.map((run, index) => leakSafeOrgPayment({
6425
- orgId,
6426
- to: recipients[index],
6427
- amount: run.amount,
6428
- paymentType: "payroll",
6429
- index
6430
- }));
6431
- });
6432
- }
6433
7117
  function listOrgsProgram() {
6434
7118
  return Effect.gen(function* () {
6435
7119
  const deps = yield* OrgDepsTag;
@@ -6516,18 +7200,13 @@ function isRetryableOrganizationSetupFailure(error) {
6516
7200
  //#endregion
6517
7201
  //#region src/surface/org.ts
6518
7202
  /**
6519
- * Org method surface (canon §C2/§C3, D13). S1 (#274) wires `createOrg` /
6520
- * `orgs` / `treasury` to their Effect programs (`org-deps.ts`); the S2→S4
6521
- * member/role/spend verbs stay `Errors.notImplemented("org", "<verb>")` until
6522
- * their slices land. The entity-scoped bundle is constructed per `org(orgId)`
6523
- * call (D13 — explicit scoping, no shared mutable "active org" state); the
6524
- * 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.
6525
7206
  */
6526
7207
  function makeOrgMethods(deps) {
6527
7208
  const layer = orgDepsLayer({
6528
7209
  ...deps.orgPort === void 0 ? {} : { orgPort: deps.orgPort },
6529
- ...deps.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: deps.orgRolesDeploymentPort },
6530
- ...deps.orgSpendPort === void 0 ? {} : { orgSpendPort: deps.orgSpendPort },
6531
7210
  ...deps.chainId === void 0 ? {} : { chainId: deps.chainId },
6532
7211
  ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
6533
7212
  });
@@ -6658,13 +7337,6 @@ function makeOrgMethods(deps) {
6658
7337
  });
6659
7338
  return toCapxulResult(listRolesProgram(orgId), layer);
6660
7339
  },
6661
- deployRoles(_options) {
6662
- if (_options?.signal?.aborted) return Promise.resolve({
6663
- ok: false,
6664
- error: Errors.cancelled({ operation: "org.deployRoles" })
6665
- });
6666
- return toCapxulResult(deployRolesProgram(orgId), layer);
6667
- },
6668
7340
  invite(_input, _options) {
6669
7341
  if (_options?.signal?.aborted) return Promise.resolve({
6670
7342
  ok: false,
@@ -6672,34 +7344,6 @@ function makeOrgMethods(deps) {
6672
7344
  });
6673
7345
  return toCapxulResult(inviteMemberProgram(orgId, _input), layer);
6674
7346
  },
6675
- removeMember(_input, _options) {
6676
- if (_options?.signal?.aborted) return Promise.resolve({
6677
- ok: false,
6678
- error: Errors.cancelled({ operation: "org.removeMember" })
6679
- });
6680
- return toCapxulResult(removeMemberProgram(orgId, _input), layer);
6681
- },
6682
- assignRole(_input, _options) {
6683
- if (_options?.signal?.aborted) return Promise.resolve({
6684
- ok: false,
6685
- error: Errors.cancelled({ operation: "org.assignRole" })
6686
- });
6687
- return toCapxulResult(assignRoleProgram(orgId, _input), layer);
6688
- },
6689
- spendViaPayments(_input, _options) {
6690
- if (_options?.signal?.aborted) return Promise.resolve({
6691
- ok: false,
6692
- error: Errors.cancelled({ operation: "org.spendViaPayments" })
6693
- });
6694
- return toCapxulResult(spendViaPaymentsProgram(orgId, _input), layer);
6695
- },
6696
- batchPayroll(_input, _options) {
6697
- if (_options?.signal?.aborted) return Promise.resolve({
6698
- ok: false,
6699
- error: Errors.cancelled({ operation: "org.batchPayroll" })
6700
- });
6701
- return toCapxulResult(batchPayrollProgram(orgId, _input), layer);
6702
- },
6703
7347
  auditLog(_options) {
6704
7348
  if (_options?.signal?.aborted) return Promise.resolve({
6705
7349
  ok: false,
@@ -6710,107 +7354,58 @@ function makeOrgMethods(deps) {
6710
7354
  error: Errors.notImplemented("organizationAuditLog", "list")
6711
7355
  });
6712
7356
  },
6713
- payroll: convexCall === void 0 ? makeNotImplementedPayrollMethods() : makePayrollMethods({
6714
- orgId: String(orgId),
6715
- convexCall
6716
- })
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))
6717
7369
  };
6718
7370
  }
6719
7371
  };
6720
7372
  }
6721
- function makePayrollMethods(deps) {
6722
- const fns = payrollContract;
7373
+ function makeNotImplementedPermissionMethods() {
6723
7374
  return {
6724
- roster: {
6725
- add: async (input, options) => {
6726
- const employee = normalizeRefForBackend$1(input.employee, "employee");
6727
- if (!employee.ok) return employee;
6728
- return mapOk(runIfActive(options?.signal, "payroll.roster.add", () => deps.convexCall.mutation(fns.add, {
6729
- orgId: deps.orgId,
6730
- employee: employee.value,
6731
- amount: input.amount,
6732
- timing: input.timing,
6733
- payslipTemplate: toPayrollTemplate(input.payslipTemplate)
6734
- })), mapPayrollRosterLine);
6735
- },
6736
- list: (options) => mapOk(runIfActive(options?.signal, "payroll.roster.list", () => deps.convexCall.query(fns.list, { orgId: deps.orgId })), (lines) => lines.map(mapPayrollRosterLine)),
6737
- update: async (rosterLineId, input, options) => {
6738
- const employee = input.employee === void 0 ? void 0 : normalizeRefForBackend$1(input.employee, "employee");
6739
- if (employee !== void 0 && !employee.ok) return employee;
6740
- return mapOk(runIfActive(options?.signal, "payroll.roster.update", () => deps.convexCall.mutation(fns.update, {
6741
- orgId: deps.orgId,
6742
- rosterLineId,
6743
- ...employee === void 0 ? {} : { employee: employee.value },
6744
- ...input.amount === void 0 ? {} : { amount: input.amount },
6745
- ...input.timing === void 0 ? {} : { timing: input.timing },
6746
- ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: toPayrollTemplate(input.payslipTemplate) }
6747
- })), mapPayrollRosterLine);
6748
- },
6749
- remove: (rosterLineId, options) => mapOk(runIfActive(options?.signal, "payroll.roster.remove", () => deps.convexCall.mutation(fns.remove, {
6750
- orgId: deps.orgId,
6751
- rosterLineId
6752
- })), mapPayrollRosterLine)
6753
- },
6754
- run: (input, options) => mapOk(runIfActive(options?.signal, "payroll.run", () => deps.convexCall.mutation(fns.run, {
6755
- orgId: deps.orgId,
6756
- period: input.period,
6757
- from: String(input.from)
6758
- })), (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
6759
7382
  };
6760
7383
  }
6761
- function makeNotImplementedPayrollMethods() {
7384
+ function makeNotImplementedOrganizationPaymentsMethods() {
6762
7385
  return {
6763
- roster: {
6764
- add: () => missingConvexCall("payroll.roster.add"),
6765
- list: () => missingConvexCall("payroll.roster.list"),
6766
- update: () => missingConvexCall("payroll.roster.update"),
6767
- remove: () => missingConvexCall("payroll.roster.remove")
6768
- },
6769
- run: () => missingConvexCall("payroll.run")
7386
+ pay: organizationPaymentExecutionUnavailable,
7387
+ payBatch: organizationPaymentExecutionUnavailable
6770
7388
  };
6771
7389
  }
6772
- function missingConvexCall(operation) {
6773
- return Promise.resolve({
6774
- ok: false,
6775
- error: Errors.providerError("convex", operation, "ConvexCallPort is required")
6776
- });
6777
- }
6778
- async function mapOk(resultOrPromise, f) {
6779
- const result = await resultOrPromise;
6780
- if (!result.ok) return result;
6781
- return {
6782
- ok: true,
6783
- value: f(result.value)
6784
- };
6785
- }
6786
- function mapPayrollRosterLine(line) {
6787
- return {
6788
- id: line.id,
6789
- employee: line.employee,
6790
- amount: line.amount,
6791
- timing: line.timing,
6792
- status: line.status === "removed" ? "ended" : line.status
6793
- };
6794
- }
6795
- function toPayrollTemplate(document) {
6796
- if (document === void 0) return { title: "Payroll" };
6797
- if ("title" in document) return {
6798
- title: document.title,
6799
- ...typeof document.memo === "string" ? { memo: document.memo } : {}
6800
- };
6801
- if (document.primaryType === "Payslip") return { title: `Payslip ${document.message.period}` };
6802
- if ("reference" in document.message) return {
6803
- title: document.primaryType,
6804
- memo: document.message.reference
6805
- };
6806
- return { title: document.primaryType };
6807
- }
6808
- function normalizePaymentTiming(payment) {
6809
- const { release: _release, ...rest } = payment;
6810
- return {
6811
- ...rest,
6812
- timing: payment.timing ?? payment.release ?? { kind: "instant" }
6813
- };
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
+ } } : {})) };
6814
7409
  }
6815
7410
  //#endregion
6816
7411
  //#region src/surface/factory.ts
@@ -7213,7 +7808,13 @@ function assembleCapxulClient(input) {
7213
7808
  const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;
7214
7809
  let detectPendingOrgInvitations;
7215
7810
  let kickProvisioning;
7216
- 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
+ });
7217
7818
  const accountBundle = makeAccountMethods({
7218
7819
  actor,
7219
7820
  authCache,
@@ -7258,22 +7859,19 @@ function assembleCapxulClient(input) {
7258
7859
  });
7259
7860
  const system = makeSystemMethods({ convexCall: input.ports.convexCall });
7260
7861
  const media = makeMediaMethods({ convexCall: input.ports.convexCall });
7862
+ const holdings = makeHoldingsMethods({ convexCall: input.ports.convexCall });
7261
7863
  const accounts = makeAccountsMethods({
7262
7864
  accountReadPort: input.ports.accountRead,
7263
7865
  chainId: input.bootstrap.chainId,
7264
7866
  telemetry: input.ports.telemetry
7265
7867
  });
7266
- const subAccounts = makeSubAccountsMethods({
7267
- subAccountPort: input.ports.subAccount,
7268
- telemetry: input.ports.telemetry
7269
- });
7270
7868
  const orgMethods = makeOrgMethods({
7869
+ actor,
7271
7870
  chainId: input.bootstrap.chainId,
7272
7871
  telemetry: input.ports.telemetry,
7273
7872
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
7274
- ...input.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: input.orgRolesDeploymentPort },
7275
- ...input.orgSpendPort === void 0 ? {} : { orgSpendPort: input.orgSpendPort },
7276
7873
  convexCall: input.ports.convexCall,
7874
+ ...input.signer === void 0 ? {} : { signer: input.signer },
7277
7875
  ...input.organizationSetup === void 0 ? {} : { organizationSetup: input.organizationSetup }
7278
7876
  });
7279
7877
  if (selectedOrgPort !== void 0) detectPendingOrgInvitations = async () => {
@@ -7362,10 +7960,10 @@ function assembleCapxulClient(input) {
7362
7960
  destinations: financialOps.destinations,
7363
7961
  payments: financialOps.payments,
7364
7962
  activity: financialOps.activity,
7963
+ holdings,
7365
7964
  offramp: financialOps.offramp,
7366
7965
  paymentDocuments: financialOps.paymentDocuments,
7367
7966
  media,
7368
- subAccounts,
7369
7967
  createOrg: orgMethods.createOrg,
7370
7968
  orgs: orgMethods.orgs,
7371
7969
  org: orgMethods.org,
@@ -7394,6 +7992,4 @@ function withHostObservation(actor, snapshot) {
7394
7992
  };
7395
7993
  }
7396
7994
  //#endregion
7397
- export { version as A, readInvocationObservation as B, convexCallErrorFromCapxul as C, bootstrapErrorFromCapxul as D, BootstrapPortTag as E, BootstrapEnvelope as F, deriveCapxulSafeAddress as G, captureExceptionSync as H, EngineeringTelemetryBootstrapPolicy as I, destination as K, isSettingUpLifecycle as L, encodeObservationContextHeader as M, sanitizeObservationContext as N, authClientPortFromPromiseAdapter as O, CAPXUL_FUNCTIONS as P, formatTraceparent as R, ConvexCallPortTag as S, ClockPortTag as T, normalizeBindingEmail as U, captureException as V, BASE_SEPOLIA_CHAIN_ID as W, accountReadErrorFromCapxul as _, observeFailedResult as a, IdentityPortTag as b, PostHogTelemetryLayer as c, SmartAccountPortTag as d, smartAccountErrorFromCapxul as f, AccountReadPortTag as g, fromWei as h, observationContextProps as i, OBSERVATION_CONTEXT_HEADER as j, AuthClientPortTag as k, TelemetryPortTag as l, subAccountErrorFromCapxul as m, postHogProductTelemetry as n, postHogFailureObservation as o, SubAccountPortTag as p, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT as r, detectAuthCacheAdapter as s, assembleCapxulClient as t, redactTelemetryEvent as u, toWei as v, ClockError as w, identityErrorFromCapxul as x, wireChainId as y, copyInvocationObservation as z };
7398
-
7399
- //# sourceMappingURL=create-capxul-client-BTnlLLag.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 };