@capxul/sdk 1.2.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
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";
2
- import { concat, encodeAbiParameters, encodeFunctionData, encodePacked, formatUnits, getContractAddress, keccak256, padHex, parseUnits, stringToHex, toBytes, toEventSelector, toFunctionSelector } from "viem";
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
+ import { concat, encodeAbiParameters, encodeFunctionData, encodePacked, formatUnits, getContractAddress, keccak256, padHex, parseUnits, stringToHex, toBytes, toEventSelector, toFunctionSelector, toFunctionSignature } 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";
5
5
  //#region src/domain/identity/model.ts
@@ -591,8 +591,12 @@ 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";
594
+ const FOUNDER_BUDGET_ROLE_LABEL = "Founder Budget";
595
+ const FOUNDER_BUDGET_LIMIT = {
596
+ currency: "USD",
597
+ value: "1000000000000",
598
+ decimals: 6
599
+ };
596
600
  function usd(value) {
597
601
  return {
598
602
  currency: "USD",
@@ -630,9 +634,15 @@ function orgRoleKeyForLabel(label) {
630
634
  function soloOrgRoleTemplate() {
631
635
  return [{
632
636
  label: "Owner",
633
- subAccounts: { scope: "all" },
634
637
  canManageMembers: true,
635
638
  canManageRoles: true
639
+ }, {
640
+ label: FOUNDER_BUDGET_ROLE_LABEL,
641
+ spend: {
642
+ perTx: FOUNDER_BUDGET_LIMIT,
643
+ perDay: FOUNDER_BUDGET_LIMIT,
644
+ toRecipients: "anyone"
645
+ }
636
646
  }];
637
647
  }
638
648
  function startupOrgRoleTemplate() {
@@ -644,8 +654,7 @@ function startupOrgRoleTemplate() {
644
654
  perTx: usd("25000"),
645
655
  perDay: usd("100000"),
646
656
  toRecipients: "anyone"
647
- },
648
- subAccounts: { scope: [MARKETING_SUB_ACCOUNT_ID] }
657
+ }
649
658
  },
650
659
  {
651
660
  label: "Team Lead",
@@ -653,8 +662,7 @@ function startupOrgRoleTemplate() {
653
662
  perTx: usd("5000"),
654
663
  perDay: usd("15000"),
655
664
  toRecipients: "anyone"
656
- },
657
- subAccounts: { scope: [PAYROLL_SUB_ACCOUNT_ID] }
665
+ }
658
666
  }
659
667
  ];
660
668
  }
@@ -701,6 +709,634 @@ function compileOrgRoleDefinitions(definitions) {
701
709
  }
702
710
  };
703
711
  }
712
+ //#endregion
713
+ //#region ../config/src/capxul-payments-v2.ts
714
+ /** The exact compiled CapxulPaymentsV2 ABI. */
715
+ const CAPXUL_PAYMENTS_V2_ABI = [
716
+ {
717
+ type: "function",
718
+ name: "cancel",
719
+ inputs: [{
720
+ name: "commitmentId",
721
+ type: "uint256",
722
+ internalType: "uint256"
723
+ }, {
724
+ name: "documentHash",
725
+ type: "bytes32",
726
+ internalType: "bytes32"
727
+ }],
728
+ outputs: [],
729
+ stateMutability: "nonpayable"
730
+ },
731
+ {
732
+ type: "function",
733
+ name: "claim",
734
+ inputs: [{
735
+ name: "commitmentId",
736
+ type: "uint256",
737
+ internalType: "uint256"
738
+ }],
739
+ outputs: [],
740
+ stateMutability: "nonpayable"
741
+ },
742
+ {
743
+ type: "function",
744
+ name: "claimableAmount",
745
+ inputs: [{
746
+ name: "commitmentId",
747
+ type: "uint256",
748
+ internalType: "uint256"
749
+ }],
750
+ outputs: [{
751
+ name: "",
752
+ type: "uint256",
753
+ internalType: "uint256"
754
+ }],
755
+ stateMutability: "view"
756
+ },
757
+ {
758
+ type: "function",
759
+ name: "commitments",
760
+ inputs: [{
761
+ name: "",
762
+ type: "uint256",
763
+ internalType: "uint256"
764
+ }],
765
+ outputs: [
766
+ {
767
+ name: "settlementId",
768
+ type: "bytes32",
769
+ internalType: "bytes32"
770
+ },
771
+ {
772
+ name: "creator",
773
+ type: "address",
774
+ internalType: "address"
775
+ },
776
+ {
777
+ name: "recipient",
778
+ type: "address",
779
+ internalType: "address"
780
+ },
781
+ {
782
+ name: "token",
783
+ type: "address",
784
+ internalType: "address"
785
+ },
786
+ {
787
+ name: "totalAmount",
788
+ type: "uint256",
789
+ internalType: "uint256"
790
+ },
791
+ {
792
+ name: "claimed",
793
+ type: "uint256",
794
+ internalType: "uint256"
795
+ },
796
+ {
797
+ name: "startTime",
798
+ type: "uint48",
799
+ internalType: "uint48"
800
+ },
801
+ {
802
+ name: "cliffTime",
803
+ type: "uint48",
804
+ internalType: "uint48"
805
+ },
806
+ {
807
+ name: "endTime",
808
+ type: "uint48",
809
+ internalType: "uint48"
810
+ },
811
+ {
812
+ name: "kind",
813
+ type: "uint16",
814
+ internalType: "uint16"
815
+ },
816
+ {
817
+ name: "documentHash",
818
+ type: "bytes32",
819
+ internalType: "bytes32"
820
+ },
821
+ {
822
+ name: "cancelled",
823
+ type: "bool",
824
+ internalType: "bool"
825
+ }
826
+ ],
827
+ stateMutability: "view"
828
+ },
829
+ {
830
+ type: "function",
831
+ name: "createCommitment",
832
+ inputs: [{
833
+ name: "input",
834
+ type: "tuple",
835
+ internalType: "struct CapxulPaymentsV2.CommitmentInput",
836
+ components: [
837
+ {
838
+ name: "settlementId",
839
+ type: "bytes32",
840
+ internalType: "bytes32"
841
+ },
842
+ {
843
+ name: "recipient",
844
+ type: "address",
845
+ internalType: "address"
846
+ },
847
+ {
848
+ name: "token",
849
+ type: "address",
850
+ internalType: "address"
851
+ },
852
+ {
853
+ name: "totalAmount",
854
+ type: "uint256",
855
+ internalType: "uint256"
856
+ },
857
+ {
858
+ name: "startTime",
859
+ type: "uint48",
860
+ internalType: "uint48"
861
+ },
862
+ {
863
+ name: "cliffTime",
864
+ type: "uint48",
865
+ internalType: "uint48"
866
+ },
867
+ {
868
+ name: "endTime",
869
+ type: "uint48",
870
+ internalType: "uint48"
871
+ },
872
+ {
873
+ name: "kind",
874
+ type: "uint16",
875
+ internalType: "uint16"
876
+ },
877
+ {
878
+ name: "documentHash",
879
+ type: "bytes32",
880
+ internalType: "bytes32"
881
+ }
882
+ ]
883
+ }],
884
+ outputs: [{
885
+ name: "commitmentId",
886
+ type: "uint256",
887
+ internalType: "uint256"
888
+ }],
889
+ stateMutability: "nonpayable"
890
+ },
891
+ {
892
+ type: "function",
893
+ name: "nextCommitmentId",
894
+ inputs: [],
895
+ outputs: [{
896
+ name: "",
897
+ type: "uint256",
898
+ internalType: "uint256"
899
+ }],
900
+ stateMutability: "view"
901
+ },
902
+ {
903
+ type: "function",
904
+ name: "redirect",
905
+ inputs: [
906
+ {
907
+ name: "commitmentId",
908
+ type: "uint256",
909
+ internalType: "uint256"
910
+ },
911
+ {
912
+ name: "recipient",
913
+ type: "address",
914
+ internalType: "address"
915
+ },
916
+ {
917
+ name: "documentHash",
918
+ type: "bytes32",
919
+ internalType: "bytes32"
920
+ }
921
+ ],
922
+ outputs: [],
923
+ stateMutability: "nonpayable"
924
+ },
925
+ {
926
+ type: "function",
927
+ name: "send",
928
+ inputs: [{
929
+ name: "item",
930
+ type: "tuple",
931
+ internalType: "struct CapxulPaymentsV2.PaymentItem",
932
+ components: [
933
+ {
934
+ name: "settlementId",
935
+ type: "bytes32",
936
+ internalType: "bytes32"
937
+ },
938
+ {
939
+ name: "recipient",
940
+ type: "address",
941
+ internalType: "address"
942
+ },
943
+ {
944
+ name: "token",
945
+ type: "address",
946
+ internalType: "address"
947
+ },
948
+ {
949
+ name: "amount",
950
+ type: "uint256",
951
+ internalType: "uint256"
952
+ },
953
+ {
954
+ name: "kind",
955
+ type: "uint16",
956
+ internalType: "uint16"
957
+ },
958
+ {
959
+ name: "documentHash",
960
+ type: "bytes32",
961
+ internalType: "bytes32"
962
+ }
963
+ ]
964
+ }],
965
+ outputs: [],
966
+ stateMutability: "nonpayable"
967
+ },
968
+ {
969
+ type: "function",
970
+ name: "sendBatch",
971
+ inputs: [{
972
+ name: "items",
973
+ type: "tuple[]",
974
+ internalType: "struct CapxulPaymentsV2.PaymentItem[]",
975
+ components: [
976
+ {
977
+ name: "settlementId",
978
+ type: "bytes32",
979
+ internalType: "bytes32"
980
+ },
981
+ {
982
+ name: "recipient",
983
+ type: "address",
984
+ internalType: "address"
985
+ },
986
+ {
987
+ name: "token",
988
+ type: "address",
989
+ internalType: "address"
990
+ },
991
+ {
992
+ name: "amount",
993
+ type: "uint256",
994
+ internalType: "uint256"
995
+ },
996
+ {
997
+ name: "kind",
998
+ type: "uint16",
999
+ internalType: "uint16"
1000
+ },
1001
+ {
1002
+ name: "documentHash",
1003
+ type: "bytes32",
1004
+ internalType: "bytes32"
1005
+ }
1006
+ ]
1007
+ }],
1008
+ outputs: [],
1009
+ stateMutability: "nonpayable"
1010
+ },
1011
+ {
1012
+ type: "function",
1013
+ name: "vestedAmount",
1014
+ inputs: [{
1015
+ name: "commitmentId",
1016
+ type: "uint256",
1017
+ internalType: "uint256"
1018
+ }],
1019
+ outputs: [{
1020
+ name: "",
1021
+ type: "uint256",
1022
+ internalType: "uint256"
1023
+ }],
1024
+ stateMutability: "view"
1025
+ },
1026
+ {
1027
+ type: "event",
1028
+ name: "CommitmentCancelled",
1029
+ inputs: [
1030
+ {
1031
+ name: "commitmentId",
1032
+ type: "uint256",
1033
+ indexed: true,
1034
+ internalType: "uint256"
1035
+ },
1036
+ {
1037
+ name: "settlementId",
1038
+ type: "bytes32",
1039
+ indexed: true,
1040
+ internalType: "bytes32"
1041
+ },
1042
+ {
1043
+ name: "creator",
1044
+ type: "address",
1045
+ indexed: true,
1046
+ internalType: "address"
1047
+ },
1048
+ {
1049
+ name: "vestedUnclaimed",
1050
+ type: "uint256",
1051
+ indexed: false,
1052
+ internalType: "uint256"
1053
+ },
1054
+ {
1055
+ name: "unvestedReturned",
1056
+ type: "uint256",
1057
+ indexed: false,
1058
+ internalType: "uint256"
1059
+ },
1060
+ {
1061
+ name: "documentHash",
1062
+ type: "bytes32",
1063
+ indexed: false,
1064
+ internalType: "bytes32"
1065
+ }
1066
+ ],
1067
+ anonymous: false
1068
+ },
1069
+ {
1070
+ type: "event",
1071
+ name: "CommitmentCreated",
1072
+ inputs: [
1073
+ {
1074
+ name: "commitmentId",
1075
+ type: "uint256",
1076
+ indexed: true,
1077
+ internalType: "uint256"
1078
+ },
1079
+ {
1080
+ name: "settlementId",
1081
+ type: "bytes32",
1082
+ indexed: true,
1083
+ internalType: "bytes32"
1084
+ },
1085
+ {
1086
+ name: "creator",
1087
+ type: "address",
1088
+ indexed: true,
1089
+ internalType: "address"
1090
+ },
1091
+ {
1092
+ name: "recipient",
1093
+ type: "address",
1094
+ indexed: false,
1095
+ internalType: "address"
1096
+ },
1097
+ {
1098
+ name: "token",
1099
+ type: "address",
1100
+ indexed: false,
1101
+ internalType: "address"
1102
+ },
1103
+ {
1104
+ name: "totalAmount",
1105
+ type: "uint256",
1106
+ indexed: false,
1107
+ internalType: "uint256"
1108
+ },
1109
+ {
1110
+ name: "startTime",
1111
+ type: "uint48",
1112
+ indexed: false,
1113
+ internalType: "uint48"
1114
+ },
1115
+ {
1116
+ name: "cliffTime",
1117
+ type: "uint48",
1118
+ indexed: false,
1119
+ internalType: "uint48"
1120
+ },
1121
+ {
1122
+ name: "endTime",
1123
+ type: "uint48",
1124
+ indexed: false,
1125
+ internalType: "uint48"
1126
+ },
1127
+ {
1128
+ name: "kind",
1129
+ type: "uint16",
1130
+ indexed: false,
1131
+ internalType: "uint16"
1132
+ },
1133
+ {
1134
+ name: "documentHash",
1135
+ type: "bytes32",
1136
+ indexed: false,
1137
+ internalType: "bytes32"
1138
+ }
1139
+ ],
1140
+ anonymous: false
1141
+ },
1142
+ {
1143
+ type: "event",
1144
+ name: "CommitmentRedirected",
1145
+ inputs: [
1146
+ {
1147
+ name: "commitmentId",
1148
+ type: "uint256",
1149
+ indexed: true,
1150
+ internalType: "uint256"
1151
+ },
1152
+ {
1153
+ name: "settlementId",
1154
+ type: "bytes32",
1155
+ indexed: true,
1156
+ internalType: "bytes32"
1157
+ },
1158
+ {
1159
+ name: "oldRecipient",
1160
+ type: "address",
1161
+ indexed: true,
1162
+ internalType: "address"
1163
+ },
1164
+ {
1165
+ name: "newRecipient",
1166
+ type: "address",
1167
+ indexed: false,
1168
+ internalType: "address"
1169
+ },
1170
+ {
1171
+ name: "documentHash",
1172
+ type: "bytes32",
1173
+ indexed: false,
1174
+ internalType: "bytes32"
1175
+ }
1176
+ ],
1177
+ anonymous: false
1178
+ },
1179
+ {
1180
+ type: "event",
1181
+ name: "FundsClaimed",
1182
+ inputs: [
1183
+ {
1184
+ name: "commitmentId",
1185
+ type: "uint256",
1186
+ indexed: true,
1187
+ internalType: "uint256"
1188
+ },
1189
+ {
1190
+ name: "settlementId",
1191
+ type: "bytes32",
1192
+ indexed: true,
1193
+ internalType: "bytes32"
1194
+ },
1195
+ {
1196
+ name: "recipient",
1197
+ type: "address",
1198
+ indexed: true,
1199
+ internalType: "address"
1200
+ },
1201
+ {
1202
+ name: "amount",
1203
+ type: "uint256",
1204
+ indexed: false,
1205
+ internalType: "uint256"
1206
+ },
1207
+ {
1208
+ name: "documentHash",
1209
+ type: "bytes32",
1210
+ indexed: false,
1211
+ internalType: "bytes32"
1212
+ }
1213
+ ],
1214
+ anonymous: false
1215
+ },
1216
+ {
1217
+ type: "event",
1218
+ name: "PaymentSent",
1219
+ inputs: [
1220
+ {
1221
+ name: "settlementId",
1222
+ type: "bytes32",
1223
+ indexed: true,
1224
+ internalType: "bytes32"
1225
+ },
1226
+ {
1227
+ name: "sender",
1228
+ type: "address",
1229
+ indexed: true,
1230
+ internalType: "address"
1231
+ },
1232
+ {
1233
+ name: "recipient",
1234
+ type: "address",
1235
+ indexed: true,
1236
+ internalType: "address"
1237
+ },
1238
+ {
1239
+ name: "token",
1240
+ type: "address",
1241
+ indexed: false,
1242
+ internalType: "address"
1243
+ },
1244
+ {
1245
+ name: "amount",
1246
+ type: "uint256",
1247
+ indexed: false,
1248
+ internalType: "uint256"
1249
+ },
1250
+ {
1251
+ name: "kind",
1252
+ type: "uint16",
1253
+ indexed: false,
1254
+ internalType: "uint16"
1255
+ },
1256
+ {
1257
+ name: "documentHash",
1258
+ type: "bytes32",
1259
+ indexed: false,
1260
+ internalType: "bytes32"
1261
+ }
1262
+ ],
1263
+ anonymous: false
1264
+ },
1265
+ {
1266
+ type: "error",
1267
+ name: "AlreadyCancelled",
1268
+ inputs: []
1269
+ },
1270
+ {
1271
+ type: "error",
1272
+ name: "AlreadyClaimed",
1273
+ inputs: []
1274
+ },
1275
+ {
1276
+ type: "error",
1277
+ name: "DocumentHashMismatch",
1278
+ inputs: [{
1279
+ name: "expected",
1280
+ type: "bytes32",
1281
+ internalType: "bytes32"
1282
+ }, {
1283
+ name: "supplied",
1284
+ type: "bytes32",
1285
+ internalType: "bytes32"
1286
+ }]
1287
+ },
1288
+ {
1289
+ type: "error",
1290
+ name: "InvalidTimeParams",
1291
+ inputs: []
1292
+ },
1293
+ {
1294
+ type: "error",
1295
+ name: "NotCreator",
1296
+ inputs: []
1297
+ },
1298
+ {
1299
+ type: "error",
1300
+ name: "NotRecipient",
1301
+ inputs: []
1302
+ },
1303
+ {
1304
+ type: "error",
1305
+ name: "NothingToClaim",
1306
+ inputs: []
1307
+ },
1308
+ {
1309
+ type: "error",
1310
+ name: "SettlementIdConsumed",
1311
+ inputs: [{
1312
+ name: "settlementId",
1313
+ type: "bytes32",
1314
+ internalType: "bytes32"
1315
+ }]
1316
+ },
1317
+ {
1318
+ type: "error",
1319
+ name: "ZeroAddress",
1320
+ inputs: []
1321
+ },
1322
+ {
1323
+ type: "error",
1324
+ name: "ZeroAmount",
1325
+ inputs: []
1326
+ },
1327
+ {
1328
+ type: "error",
1329
+ name: "ZeroDocumentHash",
1330
+ inputs: []
1331
+ },
1332
+ {
1333
+ type: "error",
1334
+ name: "ZeroSettlementId",
1335
+ inputs: []
1336
+ }
1337
+ ];
1338
+ /** Immutable CapxulPaymentsV2 deployment on Base Sepolia. */
1339
+ const CAPXUL_PAYMENTS_V2_ADDRESS = "0xA3ACDD016f706eD432A9a0545C45F0943f996b60";
704
1340
  padHex(stringToHex("FM_DAILY"), {
705
1341
  size: 32,
706
1342
  dir: "right"
@@ -712,6 +1348,16 @@ padHex(concat([MULTI_SEND_CALL_ONLY, "0x8d80ff0a"]), {
712
1348
  dir: "right",
713
1349
  size: 32
714
1350
  });
1351
+ function paymentsV2Signature(name) {
1352
+ const item = CAPXUL_PAYMENTS_V2_ABI.find((candidate) => candidate.type === "function" && candidate.name === name);
1353
+ if (item === void 0) throw new Error(`CapxulPaymentsV2 ABI has no ${name} function`);
1354
+ return toFunctionSignature(item);
1355
+ }
1356
+ paymentsV2Signature("send");
1357
+ paymentsV2Signature("sendBatch");
1358
+ paymentsV2Signature("createCommitment");
1359
+ paymentsV2Signature("cancel");
1360
+ paymentsV2Signature("redirect");
715
1361
  new Map([
716
1362
  ["assignRoles(address,bytes32[],bool[])", "AssignRoles(address,bytes32[],bool[])"],
717
1363
  ["allowTarget(bytes32,address,uint8)", "AllowTarget(bytes32,address,uint8)"],
@@ -1608,6 +2254,24 @@ function mapAccountLifecycle(input) {
1608
2254
  }
1609
2255
  //#endregion
1610
2256
  //#region ../wire/src/brands.ts
2257
+ const lowercasedString = Schema.String.pipe(Schema.decodeTo(Schema.String, {
2258
+ decode: SchemaGetter.transform((value) => value.toLowerCase()),
2259
+ encode: SchemaGetter.transform((value) => value)
2260
+ }));
2261
+ const addressSchema = (name) => lowercasedString.pipe(Schema.refine((value) => EVM_ADDRESS_RE$1.test(value), { message: `${name} must be a 0x-prefixed EVM address` }));
2262
+ const bytes32BrandSchema = (name) => lowercasedString.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: `${name} must be a 0x-prefixed bytes32 value` }));
2263
+ /** Lowercase, 0x-prefixed bytes32 evidence without a public brand. */
2264
+ const Bytes32Schema = bytes32BrandSchema("value");
2265
+ const AddressSchema$1 = addressSchema("address");
2266
+ const SafeAddressSchema = addressSchema("safe address");
2267
+ const ModuleAddressSchema = addressSchema("module address");
2268
+ const TxHashSchema$1 = bytes32BrandSchema("transaction hash");
2269
+ const RoleKeySchema = bytes32BrandSchema("role key");
2270
+ const AllowanceKeySchema = bytes32BrandSchema("allowance key");
2271
+ const BlockNumberSchema$1 = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
2272
+ const LogIndexSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
2273
+ const WeiAmountSchema$1 = Schema.String.pipe(Schema.refine((value) => WEI_RE.test(value), { message: "must be a non-negative integer string" }));
2274
+ const SettlementIdSchema = bytes32BrandSchema("settlementId").pipe(Schema.refine((value) => value !== ZERO_BYTES32, { message: "settlementId must not be zero" }));
1611
2275
  /**
1612
2276
  * `AppId` schema. Mirrors `toAppId` from `@capxul/types`:
1613
2277
  * `app_` + Crockford-base32 ULID (26 chars, first char in `[0-7]`).
@@ -1627,13 +2291,15 @@ const DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;
1627
2291
  * `DocumentHash` schema. Mirrors `toDocumentHash`: bare or 0x-prefixed bytes32,
1628
2292
  * normalized to lowercase 0x-prefixed form.
1629
2293
  */
1630
- const DocumentHashSchema$1 = Schema.String.pipe(Schema.decodeTo(Schema.String, {
2294
+ const DocumentHashSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1631
2295
  decode: SchemaGetter.transform((s) => {
1632
2296
  const stripped = s.startsWith("0x") || s.startsWith("0X") ? s.slice(2) : s;
1633
2297
  return DOCUMENT_HASH_HEX_RE.test(stripped) ? `0x${stripped.toLowerCase()}` : s;
1634
2298
  }),
1635
2299
  encode: SchemaGetter.transform((s) => s)
1636
2300
  }), Schema.refine((s) => BYTES32_RE.test(s), { message: "must be 32 bytes of hex" }));
2301
+ /** L2 orchestrated money evidence requires a nonzero Document hash. */
2302
+ const NonzeroDocumentHashSchema = DocumentHashSchema.pipe(Schema.refine((value) => value !== ZERO_BYTES32, { message: "documentHash must not be zero" }));
1637
2303
  /**
1638
2304
  * `SessionToken` schema. Mirrors `toSessionToken`: non-empty string.
1639
2305
  * Issuance source distinguishes SDK-handshake tokens from auth-session
@@ -1710,15 +2376,6 @@ const CAPXUL_FUNCTIONS = {
1710
2376
  faucetMint: "account/actions:faucetMint",
1711
2377
  readBalance: "account/actions:readBalance"
1712
2378
  },
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
2379
  "financialOps/addressBook": {
1723
2380
  add: "financialOps/addressBook:add",
1724
2381
  get: "financialOps/addressBook:get",
@@ -1730,28 +2387,11 @@ const CAPXUL_FUNCTIONS = {
1730
2387
  "financialOps/destinations": {
1731
2388
  add: "financialOps/destinations:add",
1732
2389
  list: "financialOps/destinations:list",
1733
- payout: "financialOps/destinations:payout",
1734
2390
  remove: "financialOps/destinations:remove"
1735
2391
  },
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
- },
2392
+ "financialOps/mutations": { createPayee: "financialOps/mutations:createPayee" },
1752
2393
  "financialOps/queries": {
1753
2394
  depositInstructions: "financialOps/queries:depositInstructions",
1754
- getCommitmentRef: "financialOps/queries:getCommitmentRef",
1755
2395
  getPayee: "financialOps/queries:getPayee",
1756
2396
  getPayment: "financialOps/queries:getPayment",
1757
2397
  listPayments: "financialOps/queries:listPayments",
@@ -1768,8 +2408,7 @@ const CAPXUL_FUNCTIONS = {
1768
2408
  get: "financialOps/requestsInbox:get",
1769
2409
  inboxList: "financialOps/requestsInbox:inboxList",
1770
2410
  issue: "financialOps/requestsInbox:issue",
1771
- list: "financialOps/requestsInbox:list",
1772
- reconcile: "financialOps/requestsInbox:reconcile"
2411
+ list: "financialOps/requestsInbox:list"
1773
2412
  },
1774
2413
  "identity/mutations": {
1775
2414
  completeOnboarding: "identity/mutations:completeOnboarding",
@@ -1780,24 +2419,44 @@ const CAPXUL_FUNCTIONS = {
1780
2419
  loadByAuthUserId: "identity/queries:loadByAuthUserId",
1781
2420
  usernameAvailable: "identity/queries:usernameAvailable"
1782
2421
  },
2422
+ "holdings/actions": { current: "holdings/actions:current" },
2423
+ "movement/activity": {
2424
+ annotate: "movement/activity:annotate",
2425
+ get: "movement/activity:get",
2426
+ list: "movement/activity:list"
2427
+ },
2428
+ "moneyExecution/actions": {
2429
+ preparePermissionExecution: "moneyExecution/actions:preparePermissionExecution",
2430
+ preparePaymentExecution: "moneyExecution/actions:preparePaymentExecution",
2431
+ submitPermissionExecution: "moneyExecution/actions:submitPermissionExecution",
2432
+ submitPaymentExecution: "moneyExecution/actions:submitPaymentExecution"
2433
+ },
2434
+ "moneyExecution/paymentCommandActions": {
2435
+ preparePaymentLifecycleExecution: "moneyExecution/paymentCommandActions:preparePaymentLifecycleExecution",
2436
+ prepareOrganizationPaymentExecution: "moneyExecution/paymentCommandActions:prepareOrganizationPaymentExecution",
2437
+ submitPaymentCommandExecution: "moneyExecution/paymentCommandActions:submitPaymentCommandExecution"
2438
+ },
1783
2439
  media: {
1784
2440
  generateUploadUrl: "media:generateUploadUrl",
1785
2441
  setOrgLogo: "media:setOrgLogo",
1786
2442
  setProfileImage: "media:setProfileImage"
1787
2443
  },
1788
2444
  "org/actions": {
1789
- assignRole: "org/actions:assignRole",
1790
2445
  confirmBootstrap: "org/actions:confirmBootstrap",
1791
- deployOrgRoles: "org/actions:deployOrgRoles",
1792
2446
  detectAndAcceptPendingInvitations: "org/actions:detectAndAcceptPendingInvitations",
1793
2447
  inviteMember: "org/actions:inviteMember",
1794
2448
  prepareBootstrap: "org/actions:prepareBootstrap",
1795
2449
  prepareFounderAccount: "org/actions:prepareFounderAccount",
1796
2450
  readTreasury: "org/actions:readTreasury",
1797
- removeMember: "org/actions:removeMember",
1798
2451
  resumeBootstrapSubmission: "org/actions:resumeBootstrapSubmission",
1799
2452
  submitBootstrap: "org/actions:submitBootstrap"
1800
2453
  },
2454
+ "permission/actions": { verify: "permission/actions:verify" },
2455
+ "permission/mutations": { command: "permission/mutations:command" },
2456
+ "permission/queries": {
2457
+ authorize: "permission/queries:authorize",
2458
+ read: "permission/queries:read"
2459
+ },
1801
2460
  "org/lifecycle": {
1802
2461
  getProofReceipt: "org/lifecycle:getProofReceipt",
1803
2462
  load: "org/lifecycle:load",
@@ -1825,31 +2484,19 @@ const CAPXUL_FUNCTIONS = {
1825
2484
  loadByAuthUserId: "smartAccount/queries:loadByAuthUserId",
1826
2485
  loadBySmartAccountAddress: "smartAccount/queries:loadBySmartAccountAddress"
1827
2486
  },
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
2487
  system: { health: "system:health" }
1839
2488
  };
1840
2489
  //#endregion
1841
2490
  //#region ../wire/src/status.ts
1842
- /** Payment lifecycle states carried on the wire (ADR-0018 P1). */
1843
- const PAYMENT_STATUSES = [
2491
+ /** The closed L2 Payment status authority. */
2492
+ const L2_PAYMENT_STATUSES = [
1844
2493
  "pending",
1845
- "submitted",
1846
- "pending_claim",
2494
+ "settling",
1847
2495
  "scheduled",
1848
2496
  "streaming",
2497
+ "pending_claim",
1849
2498
  "settled",
1850
2499
  "cancelled",
1851
- "redirected",
1852
- "expired",
1853
2500
  "failed"
1854
2501
  ];
1855
2502
  /** What a payment is FOR. Pairs with `PAYMENT_DOCUMENT_KINDS`. */
@@ -1888,7 +2535,7 @@ const HANDLE_RE = /^@?[a-z0-9][a-z0-9-]{2,31}$/;
1888
2535
  const ORG_HANDLE_RE = /^[a-z0-9][a-z0-9-]{2,31}$/;
1889
2536
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1890
2537
  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" })));
2538
+ 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
2539
  const PayeeIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PAYEE_ID_RE.test(value), { message: "must be payee_ plus an alphanumeric id" })));
1893
2540
  const OrgIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => ORG_ID_RE.test(value), { message: "must be org_ plus an alphanumeric id" })));
1894
2541
  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 +2543,7 @@ const DecimalStringSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((v
1896
2543
  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
2544
  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
2545
  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" })));
2546
+ const Uint8Schema$1 = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0 && value <= 255, { message: "must be a uint8" })));
1900
2547
  const Uint64Schema = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" })));
1901
2548
  const PaymentDocumentDomain = Schema.Struct({
1902
2549
  name: Schema.Literal("CapxulPayments"),
@@ -1917,10 +2564,10 @@ const InvoiceDocument = Schema.Struct({
1917
2564
  payeeRef: Schema.String,
1918
2565
  amount: MinorUnitStringSchema,
1919
2566
  currency: CurrencyCodeSchema$1,
1920
- decimals: Uint8Schema,
2567
+ decimals: Uint8Schema$1,
1921
2568
  issuedAt: Uint64Schema,
1922
2569
  dueAt: Uint64Schema,
1923
- lineItemsHash: DocumentHashSchema$1
2570
+ lineItemsHash: DocumentHashSchema
1924
2571
  });
1925
2572
  const PayslipDocument = Schema.Struct({
1926
2573
  kind: Schema.Literal(2),
@@ -1930,7 +2577,7 @@ const PayslipDocument = Schema.Struct({
1930
2577
  gross: MinorUnitStringSchema,
1931
2578
  net: MinorUnitStringSchema,
1932
2579
  currency: CurrencyCodeSchema$1,
1933
- decimals: Uint8Schema,
2580
+ decimals: Uint8Schema$1,
1934
2581
  issuedAt: Uint64Schema
1935
2582
  });
1936
2583
  const ReceiptDocument = Schema.Struct({
@@ -1938,7 +2585,7 @@ const ReceiptDocument = Schema.Struct({
1938
2585
  reference: Schema.String,
1939
2586
  amount: MinorUnitStringSchema,
1940
2587
  currency: CurrencyCodeSchema$1,
1941
- decimals: Uint8Schema,
2588
+ decimals: Uint8Schema$1,
1942
2589
  paidAt: Uint64Schema,
1943
2590
  note: Schema.String
1944
2591
  });
@@ -1948,7 +2595,7 @@ const WithdrawalDocument = Schema.Struct({
1948
2595
  reference: Schema.String,
1949
2596
  amount: MinorUnitStringSchema,
1950
2597
  currency: CurrencyCodeSchema$1,
1951
- decimals: Uint8Schema,
2598
+ decimals: Uint8Schema$1,
1952
2599
  destChain: ChainIdSchema$1,
1953
2600
  destAddress: WithdrawalDestAddressSchema,
1954
2601
  settledAt: Uint64Schema,
@@ -1961,7 +2608,7 @@ const FinancialOpsMoney = Schema.Struct({
1961
2608
  decimals: Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" })))
1962
2609
  });
1963
2610
  const PaymentDocument = Schema.Struct({
1964
- documentHash: DocumentHashSchema$1,
2611
+ documentHash: DocumentHashSchema,
1965
2612
  kind: Schema.Literals(PAYMENT_DOCUMENT_KINDS),
1966
2613
  title: Schema.optional(Schema.String),
1967
2614
  uri: Schema.optional(Schema.String),
@@ -2087,8 +2734,8 @@ const PaymentRef = Schema.Union([
2087
2734
  })
2088
2735
  ]);
2089
2736
  const Payment = Schema.Struct({
2090
- id: PaymentIdSchema,
2091
- status: Schema.Literals(PAYMENT_STATUSES),
2737
+ id: PaymentIdSchema$1,
2738
+ status: Schema.Literals(L2_PAYMENT_STATUSES),
2092
2739
  amount: FinancialOpsMoney,
2093
2740
  paymentType: PaymentType,
2094
2741
  recipient: PaymentRecipient,
@@ -2152,128 +2799,1154 @@ Schema.Struct({
2152
2799
  version: Schema.Literal(1),
2153
2800
  payments: Schema.Array(Payment)
2154
2801
  });
2155
- `
2156
- .capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;
2157
- font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;
2158
- color:var(--ink);background:var(--bg);max-width:44rem;margin:0 auto;padding:2.75rem 3rem;
2159
- border:1px solid var(--line);border-radius:16px;box-shadow:0 1px 2px rgba(0,0,0,.04),0 12px 32px rgba(0,0,0,.06);
2160
- line-height:1.5;font-size:15px;overflow-wrap:anywhere;word-break:break-word}
2161
- .capxul-doc *{box-sizing:border-box;min-width:0}
2162
- .capxul-doc .doc-header{display:flex;flex-direction:column;gap:1.25rem;padding-bottom:1.5rem;border-bottom:1px solid var(--line);margin-bottom:1.75rem}
2163
- .capxul-doc .doc-brand{display:flex;align-items:center;gap:.5rem;color:var(--accent);font-weight:600}
2164
- .capxul-doc .doc-brand-mark{font-size:1.1rem}
2165
- .capxul-doc .doc-brand-name{letter-spacing:.02em}
2166
- .capxul-doc .doc-headline{display:flex;align-items:baseline;justify-content:space-between;gap:1rem;flex-wrap:wrap}
2167
- .capxul-doc .doc-title{font-size:1.9rem;font-weight:700;letter-spacing:-.02em;margin:0}
2168
- .capxul-doc .doc-badge{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;
2169
- color:var(--accent);background:rgba(10,125,75,.1);padding:.3rem .6rem;border-radius:999px;max-width:100%;text-align:right}
2170
- .capxul-doc .doc-parties{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;margin-bottom:1.75rem}
2171
- .capxul-doc .doc-party{display:flex;flex-direction:column;gap:.15rem}
2172
- .capxul-doc .doc-party-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
2173
- .capxul-doc .doc-party-name{font-weight:600}
2174
- .capxul-doc .doc-meta{display:flex;flex-direction:column;gap:.4rem;margin-bottom:1.75rem}
2175
- .capxul-doc .doc-meta-row{display:flex;justify-content:space-between;gap:1rem;font-size:.92rem}
2176
- .capxul-doc .doc-meta-label{color:var(--muted);flex-shrink:0}
2177
- .capxul-doc .doc-meta-value{font-weight:500;text-align:right}
2178
- .capxul-doc time{color:var(--ink);font-variant-numeric:tabular-nums}
2179
- .capxul-doc .doc-line-items{width:100%;border-collapse:collapse;margin:.5rem 0 1.5rem;font-size:.92rem}
2180
- .capxul-doc .doc-line-items th{text-align:left;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;
2181
- color:var(--muted);font-weight:600;padding:.5rem .25rem;border-bottom:1px solid var(--line)}
2182
- .capxul-doc .doc-line-items td{padding:.7rem .25rem;border-bottom:1px solid var(--line)}
2183
- .capxul-doc .doc-li-qty,.capxul-doc .doc-li-unit,.capxul-doc .doc-li-total{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
2184
- .capxul-doc .doc-li-desc{width:100%}
2185
- .capxul-doc .doc-totals{display:flex;flex-direction:column;gap:.5rem;margin-top:.5rem}
2186
- .capxul-doc .doc-total-line{display:flex;justify-content:space-between;align-items:baseline;gap:1rem}
2187
- .capxul-doc .doc-total-label{color:var(--muted)}
2188
- .capxul-doc .doc-total-deduction .doc-amount-value{color:var(--muted)}
2189
- .capxul-doc .doc-total-grand{border-top:2px solid var(--ink);margin-top:.5rem;padding-top:.75rem;font-size:1.15rem}
2190
- .capxul-doc .doc-total-grand .doc-amount-value{font-weight:700}
2191
- .capxul-doc .doc-amount-value{font-variant-numeric:tabular-nums;font-weight:600}
2192
- .capxul-doc .doc-hero{text-align:center;padding:1.5rem 0 2rem}
2193
- .capxul-doc .doc-hero-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
2194
- .capxul-doc .doc-hero-amount{font-size:2.6rem;font-weight:700;letter-spacing:-.02em;margin-top:.35rem}
2195
- .capxul-doc .doc-note{color:var(--ink);background:#f7f7f8;border-radius:10px;padding:.9rem 1.1rem;margin:0}
2196
- .capxul-doc .doc-dest-address{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9rem}
2197
- .capxul-doc .doc-footer{margin-top:1.75rem;padding-top:1.25rem;border-top:1px solid var(--line);color:var(--muted);font-size:.9rem}
2198
- .capxul-doc code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.82rem;color:var(--muted);word-break:break-all}
2199
- @media (max-width:540px){.capxul-doc{padding:1.75rem 1.25rem}.capxul-doc .doc-parties{grid-template-columns:1fr}}
2200
- `.trim();
2201
- //#endregion
2202
- //#region ../wire/src/secret-material.ts
2203
- const SENSITIVE_MATERIAL_PATTERNS = [
2204
- /0x[a-fA-F0-9]{40,}/u,
2205
- /(?:^|[^a-fA-F0-9])[a-fA-F0-9]{64}(?:$|[^a-fA-F0-9])/u,
2206
- /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/u,
2207
- /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/iu
2208
- ];
2209
- /**
2210
- * Reject: does the value carry any known secret material? Best effort — callers
2211
- * drop the whole value on a match; a false negative is a leak, a false positive
2212
- * merely omits an observation field.
2213
- */
2214
- function containsSensitiveMaterial(value) {
2215
- return SENSITIVE_MATERIAL_PATTERNS.some((pattern) => pattern.test(value));
2216
- }
2217
2802
  //#endregion
2218
- //#region ../wire/src/observation-context.ts
2219
- /** Single bounded HTTP carrier used before a Convex action envelope exists. */
2220
- const OBSERVATION_CONTEXT_HEADER = "x-capxul-observation-context";
2221
- const FIELD_RULES = {
2222
- application: {
2223
- maxLength: 64,
2224
- pattern: /^[A-Za-z0-9][A-Za-z0-9._-]*$/u
2225
- },
2226
- applicationId: {
2227
- maxLength: 30,
2228
- pattern: APP_ID_RE
2229
- },
2230
- release: {
2231
- maxLength: 128,
2232
- pattern: /^[A-Za-z0-9][A-Za-z0-9._+@:/-]*$/u
2233
- },
2234
- sessionId: {
2235
- maxLength: 128,
2236
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2237
- },
2238
- organizationId: {
2239
- maxLength: 128,
2240
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2241
- },
2242
- journeyId: {
2243
- maxLength: 128,
2244
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2245
- },
2246
- correlationId: {
2247
- maxLength: 128,
2248
- pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
2249
- },
2250
- anonymousId: {
2251
- maxLength: 128,
2252
- pattern: /^anon_[A-Za-z0-9-]+$/u
2253
- },
2254
- traceparent: {
2255
- maxLength: 55,
2256
- pattern: /^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/u
2257
- }
2803
+ //#region ../wire/src/l2-money.ts
2804
+ const nonEmpty = (name) => Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: `${name} must not be empty` }));
2805
+ const nonNegativeInteger = (name) => Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: `${name} must be a non-negative safe integer` }));
2806
+ const BaseSepoliaChainIdSchema = ChainIdSchema$1.pipe(Schema.refine((value) => value === 84532, { message: "chainId must be 84532" }));
2807
+ const Uint16Schema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0 && value <= 65535, { message: "kind must be a uint16 value" }));
2808
+ const Uint8Schema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0 && value <= 255, { message: "must be a uint8 value" }));
2809
+ 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" }));
2810
+ const HexDataSchema = Schema.String.pipe(Schema.refine((value) => /^0x(?:[0-9a-fA-F]{2})*$/u.test(value), { message: "must be 0x-prefixed byte data" }));
2811
+ const Uint48Schema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0 && value <= 0xffffffffffff, { message: "must be a uint48 value" }));
2812
+ const Uint256StringSchema = Schema.String.pipe(Schema.refine((value) => {
2813
+ if (!/^(0|[1-9][0-9]*)$/u.test(value)) return false;
2814
+ return BigInt(value) < 1n << 256n;
2815
+ }, { message: "must be a uint256 base-10 string" }));
2816
+ const PaymentIdSchema = nonEmpty("paymentId").pipe(Schema.refine((value) => value.length > 0));
2817
+ const MovementIdSchema = nonEmpty("movementId").pipe(Schema.refine((value) => value.length > 0));
2818
+ const PermissionIdSchema = nonEmpty("permissionId").pipe(Schema.refine((value) => value.length > 0));
2819
+ const PermissionAssignmentIdSchema = nonEmpty("permissionAssignmentId").pipe(Schema.refine((value) => value.length > 0));
2820
+ const PaymentCommandIdSchema = nonEmpty("commandId").pipe(Schema.refine((value) => value.length > 0));
2821
+ const PAYMENT_PURPOSE_KIND_CODES = {
2822
+ quick_pay: 0,
2823
+ invoice: 1,
2824
+ payroll: 2,
2825
+ reimbursement: 3
2258
2826
  };
2259
- /**
2260
- * Copy only the canonical allowlist and silently omit malformed/sensitive
2261
- * values. Observation metadata is best effort and may never reject a domain
2262
- * operation.
2263
- */
2264
- function sanitizeObservationContext(input) {
2265
- if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
2266
- const source = input;
2267
- const sanitized = {};
2268
- for (const field of Object.keys(FIELD_RULES)) {
2269
- const value = source[field];
2270
- if (!isSafeField(field, value)) continue;
2271
- sanitized[field] = value;
2272
- }
2273
- return Object.keys(sanitized).length === 0 ? void 0 : sanitized;
2274
- }
2275
- /** Encode only the sanitized allowlist; absence stays absence. */
2276
- function encodeObservationContextHeader(input) {
2827
+ const PaymentPurposeKindSchema = Schema.String.pipe(Schema.refine((value) => Object.hasOwn(PAYMENT_PURPOSE_KIND_CODES, value), { message: "purposeKind must be a registered L2 value" }));
2828
+ const AccountActorRefSchema = Schema.Struct({
2829
+ kind: Schema.Literal("account"),
2830
+ accountId: nonEmpty("accountId")
2831
+ });
2832
+ const OrganizationActorRefSchema = Schema.Struct({
2833
+ kind: Schema.Literal("organization"),
2834
+ orgId: nonEmpty("orgId")
2835
+ });
2836
+ const ActorRefSchema = Schema.Union([AccountActorRefSchema, OrganizationActorRefSchema]);
2837
+ const hasActorBoundPermission = (actor, orgId, permissionId) => actor.kind === "organization" ? orgId === actor.orgId && permissionId !== void 0 : orgId === void 0 && permissionId === void 0;
2838
+ const ActorOrDestinationRefSchema = Schema.Union([ActorRefSchema, Schema.Struct({
2839
+ kind: Schema.Literal("destination"),
2840
+ destinationId: nonEmpty("destinationId")
2841
+ })]);
2842
+ Schema.Literals([
2843
+ "Payment",
2844
+ "Payout",
2845
+ "Deposit"
2846
+ ]);
2847
+ const PaymentStatusSchema = Schema.Literals(L2_PAYMENT_STATUSES);
2848
+ const ReleaseTermsSchema = PaymentTiming;
2849
+ const PaymentLedgerBaseSchema = Schema.Struct({
2850
+ paymentId: PaymentIdSchema,
2851
+ status: PaymentStatusSchema,
2852
+ actor: ActorRefSchema,
2853
+ recipient: ActorOrDestinationRefSchema,
2854
+ amount: FinancialOpsMoney,
2855
+ chainId: ChainIdSchema$1,
2856
+ tokenAddress: AddressSchema$1,
2857
+ release: ReleaseTermsSchema,
2858
+ createdAt: nonNegativeInteger("createdAt"),
2859
+ updatedAt: nonNegativeInteger("updatedAt")
2860
+ });
2861
+ const PaymentLedgerRecordSchema = Schema.Union([Schema.Struct({
2862
+ ...PaymentLedgerBaseSchema.fields,
2863
+ ledgerKind: Schema.Literals(["Payment", "Payout"]),
2864
+ purposeKind: PaymentPurposeKindSchema,
2865
+ permissionId: Schema.optional(PermissionIdSchema),
2866
+ settlementId: SettlementIdSchema,
2867
+ movementId: Schema.optional(MovementIdSchema),
2868
+ documentHash: NonzeroDocumentHashSchema,
2869
+ userOpHash: Schema.optional(Bytes32Schema),
2870
+ txHash: Schema.optional(TxHashSchema$1),
2871
+ settlementLogIndex: Schema.optional(LogIndexSchema),
2872
+ settledBlockNumber: Schema.optional(BlockNumberSchema$1),
2873
+ settledBlockHash: Schema.optional(Bytes32Schema),
2874
+ settledEventLogIndex: Schema.optional(LogIndexSchema)
2875
+ }), Schema.Struct({
2876
+ ...PaymentLedgerBaseSchema.fields,
2877
+ ledgerKind: Schema.Literal("Deposit"),
2878
+ movementId: MovementIdSchema,
2879
+ settlementId: Schema.optional(Schema.Never),
2880
+ documentHash: Schema.optional(Schema.Never),
2881
+ permissionId: Schema.optional(Schema.Never),
2882
+ purposeKind: Schema.optional(Schema.Never)
2883
+ })]).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" }));
2884
+ const MovementIdentitySchema = Schema.Struct({
2885
+ chainId: ChainIdSchema$1,
2886
+ tokenAddress: AddressSchema$1,
2887
+ txHash: TxHashSchema$1,
2888
+ logIndex: LogIndexSchema
2889
+ });
2890
+ const MovementCanonicalStateSchema = Schema.Literals([
2891
+ "observed",
2892
+ "finalized",
2893
+ "removed"
2894
+ ]);
2895
+ const MovementSchema = Schema.Struct({
2896
+ ...MovementIdentitySchema.fields,
2897
+ movementId: MovementIdSchema,
2898
+ blockNumber: BlockNumberSchema$1,
2899
+ blockHash: Bytes32Schema,
2900
+ source: AddressSchema$1,
2901
+ destination: AddressSchema$1,
2902
+ rawAmount: WeiAmountSchema$1,
2903
+ canonicalState: MovementCanonicalStateSchema
2904
+ });
2905
+ const MovementClassificationSchema = Schema.Literals([
2906
+ "protocol_settlement",
2907
+ "deposit",
2908
+ "movement_only_outflow"
2909
+ ]);
2910
+ const MovementAttributionSchema = Schema.Struct({
2911
+ movementId: MovementIdSchema,
2912
+ actor: ActorRefSchema,
2913
+ side: Schema.Literals(["source", "destination"]),
2914
+ classification: MovementClassificationSchema
2915
+ });
2916
+ Schema.Struct({
2917
+ movementId: MovementIdSchema,
2918
+ actor: ActorRefSchema,
2919
+ counterpartyLabel: Schema.optional(Schema.String),
2920
+ accountingCategory: Schema.optional(Schema.String),
2921
+ memo: Schema.optional(Schema.String),
2922
+ lastEditor: ActorRefSchema,
2923
+ updatedAt: nonNegativeInteger("updatedAt")
2924
+ });
2925
+ const ReceiptRefSchema = Schema.Struct({
2926
+ chainId: BaseSepoliaChainIdSchema,
2927
+ userOpHash: Bytes32Schema,
2928
+ transactionHash: TxHashSchema$1,
2929
+ blockNumber: BlockNumberSchema$1,
2930
+ blockHash: Bytes32Schema
2931
+ });
2932
+ const EventRefSchema = Schema.Struct({
2933
+ ...ReceiptRefSchema.fields,
2934
+ emitter: AddressSchema$1,
2935
+ transactionIndex: LogIndexSchema,
2936
+ logIndex: LogIndexSchema,
2937
+ topic0: Bytes32Schema,
2938
+ dataHash: Bytes32Schema
2939
+ });
2940
+ const PermissionOperationSchema = Schema.Literals([
2941
+ "create",
2942
+ "change",
2943
+ "assign",
2944
+ "revoke",
2945
+ "replace"
2946
+ ]);
2947
+ const PermissionStateSchema = Schema.Literals([
2948
+ "pending",
2949
+ "active",
2950
+ "suspended",
2951
+ "revoked",
2952
+ "superseded",
2953
+ "quarantined"
2954
+ ]);
2955
+ const StoredPermissionCommandSchema = Schema.Struct({
2956
+ commandId: PaymentCommandIdSchema,
2957
+ orgId: nonEmpty("orgId"),
2958
+ operation: PermissionOperationSchema,
2959
+ permissionId: PermissionIdSchema,
2960
+ permissionAssignmentId: Schema.NullOr(PermissionAssignmentIdSchema),
2961
+ expectedRevision: nonNegativeInteger("expectedRevision"),
2962
+ userOpSenderSafe: SafeAddressSchema,
2963
+ organizationSafe: SafeAddressSchema,
2964
+ rolesModule: ModuleAddressSchema,
2965
+ roleKey: RoleKeySchema,
2966
+ allowanceKey: Schema.NullOr(AllowanceKeySchema),
2967
+ memberSafe: Schema.NullOr(SafeAddressSchema),
2968
+ expectedAuthorityEvents: Schema.Array(Bytes32Schema)
2969
+ });
2970
+ Schema.Struct({
2971
+ command: StoredPermissionCommandSchema,
2972
+ userOpHash: Bytes32Schema
2973
+ });
2974
+ Schema.Union([
2975
+ Schema.Struct({
2976
+ status: Schema.Literal("pending"),
2977
+ reason: Schema.Literals(["receipt_missing", "not_finalized"]),
2978
+ receipt: Schema.optional(ReceiptRefSchema)
2979
+ }),
2980
+ Schema.Struct({
2981
+ status: Schema.Literal("verified"),
2982
+ commandId: PaymentCommandIdSchema,
2983
+ receipt: ReceiptRefSchema,
2984
+ events: Schema.Array(EventRefSchema),
2985
+ factsHash: Bytes32Schema
2986
+ }),
2987
+ Schema.Struct({
2988
+ status: Schema.Literal("mismatch"),
2989
+ code: Schema.Literals([
2990
+ "wrong_chain",
2991
+ "wrong_sender",
2992
+ "failed_user_operation",
2993
+ "non_canonical_block",
2994
+ "wrong_contract_identity",
2995
+ "missing_event",
2996
+ "extra_authority_event",
2997
+ "wrong_event_order",
2998
+ "wrong_fact_tuple",
2999
+ "wrong_state",
3000
+ "conflicting_replay"
3001
+ ]),
3002
+ receipt: Schema.optional(ReceiptRefSchema)
3003
+ }),
3004
+ Schema.Struct({
3005
+ status: Schema.Literal("provider_failure"),
3006
+ retryable: Schema.Literal(true)
3007
+ })
3008
+ ]);
3009
+ Schema.Struct({
3010
+ commandId: PaymentCommandIdSchema,
3011
+ expectedRevision: nonNegativeInteger("expectedRevision"),
3012
+ verification: Schema.Struct({
3013
+ status: Schema.Literal("verified"),
3014
+ commandId: PaymentCommandIdSchema,
3015
+ receipt: ReceiptRefSchema,
3016
+ events: Schema.Array(EventRefSchema),
3017
+ factsHash: Bytes32Schema
3018
+ })
3019
+ });
3020
+ Schema.Union([Schema.Struct({
3021
+ status: Schema.Literals(["applied", "replayed"]),
3022
+ revision: nonNegativeInteger("revision")
3023
+ }), Schema.Struct({ status: Schema.Literals(["revision_mismatch", "conflicting_replay"]) })]);
3024
+ const PermissionSchema = Schema.Struct({
3025
+ permissionId: PermissionIdSchema,
3026
+ orgId: nonEmpty("orgId"),
3027
+ type: Schema.Literals(["budget", "managePeople"]),
3028
+ state: PermissionStateSchema,
3029
+ revision: nonNegativeInteger("revision"),
3030
+ roleKey: RoleKeySchema,
3031
+ tokenAddress: Schema.optional(AddressSchema$1),
3032
+ limitRaw: Schema.optional(WeiAmountSchema$1),
3033
+ allowanceKey: Schema.optional(AllowanceKeySchema)
3034
+ });
3035
+ const PermissionAssignmentSchema = Schema.Struct({
3036
+ permissionAssignmentId: PermissionAssignmentIdSchema,
3037
+ permissionId: PermissionIdSchema,
3038
+ actor: ActorRefSchema,
3039
+ state: PermissionStateSchema
3040
+ });
3041
+ Schema.Struct({
3042
+ orgId: nonEmpty("orgId"),
3043
+ actor: ActorRefSchema,
3044
+ permissionId: PermissionIdSchema,
3045
+ tokenAddress: AddressSchema$1,
3046
+ rawAmount: WeiAmountSchema$1
3047
+ });
3048
+ Schema.Struct({
3049
+ permission: PermissionSchema,
3050
+ assignment: PermissionAssignmentSchema
3051
+ });
3052
+ Schema.Struct({
3053
+ chainId: ChainIdSchema$1,
3054
+ tokenAddress: AddressSchema$1,
3055
+ symbol: nonEmpty("symbol"),
3056
+ decimals: nonNegativeInteger("decimals"),
3057
+ deploymentStartBlock: BlockNumberSchema$1
3058
+ });
3059
+ const HoldingRowSchema = Schema.Union([Schema.Struct({
3060
+ assetKind: Schema.Literal("native"),
3061
+ symbol: Schema.optional(Schema.String),
3062
+ decimals: Schema.optional(nonNegativeInteger("decimals")),
3063
+ rawBalance: WeiAmountSchema$1
3064
+ }), Schema.Struct({
3065
+ assetKind: Schema.Literal("erc20"),
3066
+ tokenAddress: AddressSchema$1,
3067
+ symbol: Schema.optional(Schema.String),
3068
+ decimals: Schema.optional(nonNegativeInteger("decimals")),
3069
+ rawBalance: WeiAmountSchema$1
3070
+ })]);
3071
+ Schema.Struct({
3072
+ actor: ActorRefSchema,
3073
+ chainId: ChainIdSchema$1,
3074
+ observedAt: nonNegativeInteger("observedAt"),
3075
+ stale: Schema.Boolean,
3076
+ rows: Schema.Array(HoldingRowSchema)
3077
+ });
3078
+ const PaymentCoreErrorSchema = Schema.Union([
3079
+ Schema.Struct({
3080
+ code: Schema.Literal("INVALID_TRANSITION"),
3081
+ status: PaymentStatusSchema,
3082
+ event: nonEmpty("event")
3083
+ }),
3084
+ Schema.Struct({
3085
+ code: Schema.Literal("ALREADY_SETTLED"),
3086
+ paymentId: PaymentIdSchema
3087
+ }),
3088
+ Schema.Struct({ code: Schema.Literals([
3089
+ "EVIDENCE_MISSING",
3090
+ "EVIDENCE_MISMATCH",
3091
+ "EVIDENCE_REPLAY"
3092
+ ]) })
3093
+ ]);
3094
+ Schema.Union([
3095
+ Schema.Struct({ type: Schema.Literal("commitment_created") }),
3096
+ Schema.Struct({
3097
+ type: Schema.Literal("claim"),
3098
+ rawAmount: WeiAmountSchema$1
3099
+ }),
3100
+ Schema.Struct({ type: Schema.Literal("cancel") }),
3101
+ Schema.Struct({
3102
+ type: Schema.Literal("redirect"),
3103
+ recipient: ActorOrDestinationRefSchema
3104
+ }),
3105
+ Schema.Struct({
3106
+ type: Schema.Literal("fail"),
3107
+ reasonCode: nonEmpty("reasonCode")
3108
+ })
3109
+ ]);
3110
+ const PaymentTransitionEventSchema = Schema.Union([
3111
+ Schema.Struct({
3112
+ type: Schema.Literal("claim"),
3113
+ rawAmount: WeiAmountSchema$1
3114
+ }),
3115
+ Schema.Struct({ type: Schema.Literal("cancel") }),
3116
+ Schema.Struct({
3117
+ type: Schema.Literal("redirect"),
3118
+ recipient: ActorOrDestinationRefSchema
3119
+ }),
3120
+ Schema.Struct({
3121
+ type: Schema.Literal("fail"),
3122
+ reasonCode: nonEmpty("reasonCode")
3123
+ })
3124
+ ]);
3125
+ const ExpectedPaymentCommonSchema = Schema.Struct({
3126
+ chainId: BaseSepoliaChainIdSchema,
3127
+ contractAddress: AddressSchema$1,
3128
+ userOpHash: Bytes32Schema,
3129
+ userOpSenderSafe: SafeAddressSchema
3130
+ });
3131
+ Schema.Union([
3132
+ Schema.Struct({
3133
+ ...ExpectedPaymentCommonSchema.fields,
3134
+ operation: Schema.Literal("send"),
3135
+ paymentSenderSafe: SafeAddressSchema,
3136
+ itemIndex: nonNegativeInteger("itemIndex"),
3137
+ settlementId: SettlementIdSchema,
3138
+ purposeKind: PaymentPurposeKindSchema,
3139
+ kind: Uint16Schema,
3140
+ documentHash: NonzeroDocumentHashSchema,
3141
+ tokenAddress: AddressSchema$1,
3142
+ recipient: AddressSchema$1,
3143
+ rawAmount: WeiAmountSchema$1
3144
+ }),
3145
+ Schema.Struct({
3146
+ ...ExpectedPaymentCommonSchema.fields,
3147
+ operation: Schema.Literal("create_commitment"),
3148
+ paymentSenderSafe: SafeAddressSchema,
3149
+ settlementId: SettlementIdSchema,
3150
+ purposeKind: PaymentPurposeKindSchema,
3151
+ kind: Uint16Schema,
3152
+ documentHash: NonzeroDocumentHashSchema,
3153
+ tokenAddress: AddressSchema$1,
3154
+ recipient: AddressSchema$1,
3155
+ totalAmount: WeiAmountSchema$1,
3156
+ startTime: Uint48Schema,
3157
+ cliffTime: Uint48Schema,
3158
+ endTime: Uint48Schema
3159
+ }),
3160
+ Schema.Struct({
3161
+ ...ExpectedPaymentCommonSchema.fields,
3162
+ operation: Schema.Literal("claim_commitment"),
3163
+ commitmentId: Uint256StringSchema,
3164
+ settlementId: SettlementIdSchema,
3165
+ documentHash: NonzeroDocumentHashSchema,
3166
+ tokenAddress: AddressSchema$1,
3167
+ creator: AddressSchema$1,
3168
+ currentRecipient: AddressSchema$1,
3169
+ totalAmount: WeiAmountSchema$1,
3170
+ claimedBefore: WeiAmountSchema$1
3171
+ }),
3172
+ Schema.Struct({
3173
+ ...ExpectedPaymentCommonSchema.fields,
3174
+ operation: Schema.Literal("cancel_commitment"),
3175
+ commitmentId: Uint256StringSchema,
3176
+ settlementId: SettlementIdSchema,
3177
+ documentHash: NonzeroDocumentHashSchema,
3178
+ tokenAddress: AddressSchema$1,
3179
+ creator: AddressSchema$1,
3180
+ currentRecipient: AddressSchema$1,
3181
+ totalAmount: WeiAmountSchema$1,
3182
+ claimedBefore: WeiAmountSchema$1
3183
+ }),
3184
+ Schema.Struct({
3185
+ ...ExpectedPaymentCommonSchema.fields,
3186
+ operation: Schema.Literal("redirect_commitment"),
3187
+ commitmentId: Uint256StringSchema,
3188
+ settlementId: SettlementIdSchema,
3189
+ documentHash: NonzeroDocumentHashSchema,
3190
+ creator: AddressSchema$1,
3191
+ currentRecipient: AddressSchema$1,
3192
+ newRecipient: AddressSchema$1,
3193
+ claimedBefore: Schema.Literal("0")
3194
+ })
3195
+ ]);
3196
+ const PaymentVerificationMismatchCodeSchema = Schema.Literals([
3197
+ "wrong_chain",
3198
+ "wrong_sender",
3199
+ "failed_user_operation",
3200
+ "wrong_transaction",
3201
+ "failed_transaction",
3202
+ "non_canonical_block",
3203
+ "wrong_contract_identity",
3204
+ "missing_event",
3205
+ "wrong_commitment_id",
3206
+ "wrong_settlement_id",
3207
+ "wrong_event_sender",
3208
+ "wrong_event_recipient",
3209
+ "wrong_event_token",
3210
+ "wrong_event_amount",
3211
+ "wrong_kind",
3212
+ "zero_document_hash",
3213
+ "wrong_document_hash",
3214
+ "missing_bound_transfer",
3215
+ "wrong_token",
3216
+ "wrong_source",
3217
+ "wrong_destination",
3218
+ "wrong_amount"
3219
+ ]);
3220
+ const FinalizedTransferRangeSchema = Schema.Struct({
3221
+ chainId: BaseSepoliaChainIdSchema,
3222
+ tokenAddress: AddressSchema$1,
3223
+ fromBlock: BlockNumberSchema$1,
3224
+ toBlock: BlockNumberSchema$1
3225
+ }).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" }));
3226
+ const FinalizedTransferEvidenceSchema = Schema.Struct({
3227
+ ...MovementIdentitySchema.fields,
3228
+ blockNumber: BlockNumberSchema$1,
3229
+ blockHash: Bytes32Schema,
3230
+ source: AddressSchema$1,
3231
+ destination: AddressSchema$1,
3232
+ rawAmount: WeiAmountSchema$1,
3233
+ removed: Schema.Boolean
3234
+ });
3235
+ const FinalizedBlockReferenceSchema = Schema.Struct({
3236
+ chainId: BaseSepoliaChainIdSchema,
3237
+ blockNumber: BlockNumberSchema$1,
3238
+ blockHash: Bytes32Schema
3239
+ });
3240
+ Schema.Struct({
3241
+ range: FinalizedTransferRangeSchema,
3242
+ finalizedHead: FinalizedBlockReferenceSchema,
3243
+ anchor: FinalizedBlockReferenceSchema,
3244
+ transfers: Schema.Array(FinalizedTransferEvidenceSchema),
3245
+ requestCount: nonNegativeInteger("requestCount")
3246
+ });
3247
+ const FinalizedPermissionFactRangeSchema = Schema.Struct({
3248
+ chainId: BaseSepoliaChainIdSchema,
3249
+ organizationSafe: SafeAddressSchema,
3250
+ rolesModules: Schema.Array(ModuleAddressSchema),
3251
+ fromBlock: BlockNumberSchema$1,
3252
+ toBlock: BlockNumberSchema$1
3253
+ }).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" }));
3254
+ const FinalizedPermissionFactCommonSchema = Schema.Struct({
3255
+ chainId: BaseSepoliaChainIdSchema,
3256
+ transactionHash: TxHashSchema$1,
3257
+ blockNumber: BlockNumberSchema$1,
3258
+ blockHash: Bytes32Schema,
3259
+ logIndex: LogIndexSchema,
3260
+ emitter: AddressSchema$1,
3261
+ topic0: Bytes32Schema,
3262
+ dataHash: Bytes32Schema,
3263
+ authorityHash: Bytes32Schema
3264
+ });
3265
+ const FinalizedPermissionModuleFactSchema = Schema.Struct({
3266
+ ...FinalizedPermissionFactCommonSchema.fields,
3267
+ kind: Schema.Literals(["module_enabled", "module_disabled"]),
3268
+ organizationSafe: SafeAddressSchema,
3269
+ module: ModuleAddressSchema
3270
+ });
3271
+ const FinalizedPermissionRoleAssignmentFactSchema = Schema.Struct({
3272
+ ...FinalizedPermissionFactCommonSchema.fields,
3273
+ kind: Schema.Literal("assignment"),
3274
+ rolesModule: ModuleAddressSchema,
3275
+ memberSafe: SafeAddressSchema,
3276
+ roleKeys: Schema.Array(RoleKeySchema),
3277
+ memberOf: Schema.Array(Schema.Boolean)
3278
+ });
3279
+ const FinalizedPermissionTargetAuthorityFactSchema = Schema.Union([Schema.Struct({
3280
+ ...FinalizedPermissionFactCommonSchema.fields,
3281
+ kind: Schema.Literal("allow_target"),
3282
+ rolesModule: ModuleAddressSchema,
3283
+ roleKey: RoleKeySchema,
3284
+ target: AddressSchema$1,
3285
+ options: Uint8Schema
3286
+ }), Schema.Struct({
3287
+ ...FinalizedPermissionFactCommonSchema.fields,
3288
+ kind: Schema.Literals(["scope_target", "revoke_target"]),
3289
+ rolesModule: ModuleAddressSchema,
3290
+ roleKey: RoleKeySchema,
3291
+ target: AddressSchema$1
3292
+ })]);
3293
+ const PermissionScopeConditionSchema = Schema.Struct({
3294
+ parent: Uint8Schema,
3295
+ paramType: Uint8Schema,
3296
+ operator: Uint8Schema,
3297
+ compValue: HexDataSchema
3298
+ });
3299
+ const FinalizedPermissionFunctionAuthorityFactSchema = Schema.Union([
3300
+ Schema.Struct({
3301
+ ...FinalizedPermissionFactCommonSchema.fields,
3302
+ kind: Schema.Literal("allow_function"),
3303
+ rolesModule: ModuleAddressSchema,
3304
+ roleKey: RoleKeySchema,
3305
+ target: AddressSchema$1,
3306
+ selector: Bytes4Schema,
3307
+ options: Uint8Schema
3308
+ }),
3309
+ Schema.Struct({
3310
+ ...FinalizedPermissionFactCommonSchema.fields,
3311
+ kind: Schema.Literal("scope_function"),
3312
+ rolesModule: ModuleAddressSchema,
3313
+ roleKey: RoleKeySchema,
3314
+ target: AddressSchema$1,
3315
+ selector: Bytes4Schema,
3316
+ options: Uint8Schema,
3317
+ conditions: Schema.Array(PermissionScopeConditionSchema)
3318
+ }),
3319
+ Schema.Struct({
3320
+ ...FinalizedPermissionFactCommonSchema.fields,
3321
+ kind: Schema.Literal("revoke_function"),
3322
+ rolesModule: ModuleAddressSchema,
3323
+ roleKey: RoleKeySchema,
3324
+ target: AddressSchema$1,
3325
+ selector: Bytes4Schema
3326
+ })
3327
+ ]);
3328
+ const FinalizedPermissionAllowanceAuthorityFactSchema = Schema.Struct({
3329
+ ...FinalizedPermissionFactCommonSchema.fields,
3330
+ kind: Schema.Literal("allowance"),
3331
+ rolesModule: ModuleAddressSchema,
3332
+ allowanceKey: AllowanceKeySchema,
3333
+ balance: WeiAmountSchema$1,
3334
+ maxRefill: WeiAmountSchema$1,
3335
+ refill: WeiAmountSchema$1,
3336
+ period: Uint256StringSchema,
3337
+ timestamp: Uint256StringSchema
3338
+ });
3339
+ const FinalizedPermissionFactSchema = Schema.Union([
3340
+ FinalizedPermissionModuleFactSchema,
3341
+ FinalizedPermissionRoleAssignmentFactSchema,
3342
+ FinalizedPermissionTargetAuthorityFactSchema,
3343
+ FinalizedPermissionFunctionAuthorityFactSchema,
3344
+ FinalizedPermissionAllowanceAuthorityFactSchema
3345
+ ]);
3346
+ Schema.Struct({
3347
+ range: FinalizedPermissionFactRangeSchema,
3348
+ finalizedHead: FinalizedBlockReferenceSchema,
3349
+ anchor: FinalizedBlockReferenceSchema,
3350
+ facts: Schema.Array(FinalizedPermissionFactSchema),
3351
+ requestCount: nonNegativeInteger("requestCount")
3352
+ });
3353
+ const FinalizedMoneyEvidenceCommonSchema = Schema.Struct({
3354
+ chainId: BaseSepoliaChainIdSchema,
3355
+ contractAddress: AddressSchema$1,
3356
+ userOpHash: Bytes32Schema,
3357
+ txHash: TxHashSchema$1,
3358
+ blockNumber: BlockNumberSchema$1,
3359
+ blockHash: Bytes32Schema,
3360
+ blockTimestamp: Uint48Schema,
3361
+ eventLogIndex: LogIndexSchema
3362
+ });
3363
+ const FinalizedPaymentEvidenceSchema = Schema.Struct({
3364
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
3365
+ operation: Schema.Literal("send"),
3366
+ settlementId: SettlementIdSchema,
3367
+ purposeKind: PaymentPurposeKindSchema,
3368
+ kind: Uint16Schema,
3369
+ documentHash: NonzeroDocumentHashSchema,
3370
+ tokenAddress: AddressSchema$1,
3371
+ transferLogIndex: LogIndexSchema,
3372
+ source: AddressSchema$1,
3373
+ destination: AddressSchema$1,
3374
+ rawAmount: WeiAmountSchema$1
3375
+ });
3376
+ const FinalizedCommitmentCreationEvidenceSchema = Schema.Struct({
3377
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
3378
+ operation: Schema.Literal("create_commitment"),
3379
+ commitmentId: Uint256StringSchema,
3380
+ settlementId: SettlementIdSchema,
3381
+ creator: AddressSchema$1,
3382
+ recipient: AddressSchema$1,
3383
+ tokenAddress: AddressSchema$1,
3384
+ totalAmount: WeiAmountSchema$1,
3385
+ startTime: Uint48Schema,
3386
+ cliffTime: Uint48Schema,
3387
+ endTime: Uint48Schema,
3388
+ kind: Uint16Schema,
3389
+ purposeKind: PaymentPurposeKindSchema,
3390
+ documentHash: NonzeroDocumentHashSchema,
3391
+ transferLogIndex: LogIndexSchema
3392
+ });
3393
+ const FinalizedCommitmentClaimEvidenceSchema = Schema.Struct({
3394
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
3395
+ operation: Schema.Literal("claim_commitment"),
3396
+ commitmentId: Uint256StringSchema,
3397
+ settlementId: SettlementIdSchema,
3398
+ creator: AddressSchema$1,
3399
+ recipient: AddressSchema$1,
3400
+ tokenAddress: AddressSchema$1,
3401
+ totalAmount: WeiAmountSchema$1,
3402
+ claimedBefore: WeiAmountSchema$1,
3403
+ rawAmount: WeiAmountSchema$1,
3404
+ documentHash: NonzeroDocumentHashSchema,
3405
+ transferLogIndex: LogIndexSchema
3406
+ });
3407
+ const FinalizedCommitmentCancelEvidenceSchema = Schema.Struct({
3408
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
3409
+ operation: Schema.Literal("cancel_commitment"),
3410
+ commitmentId: Uint256StringSchema,
3411
+ settlementId: SettlementIdSchema,
3412
+ creator: AddressSchema$1,
3413
+ currentRecipient: AddressSchema$1,
3414
+ tokenAddress: AddressSchema$1,
3415
+ totalAmount: WeiAmountSchema$1,
3416
+ claimedBefore: WeiAmountSchema$1,
3417
+ vestedUnclaimed: WeiAmountSchema$1,
3418
+ unvestedReturned: WeiAmountSchema$1,
3419
+ documentHash: NonzeroDocumentHashSchema,
3420
+ transfer: Schema.NullOr(FinalizedTransferEvidenceSchema)
3421
+ });
3422
+ const FinalizedCommitmentRedirectEvidenceSchema = Schema.Struct({
3423
+ ...FinalizedMoneyEvidenceCommonSchema.fields,
3424
+ operation: Schema.Literal("redirect_commitment"),
3425
+ commitmentId: Uint256StringSchema,
3426
+ settlementId: SettlementIdSchema,
3427
+ creator: AddressSchema$1,
3428
+ oldRecipient: AddressSchema$1,
3429
+ newRecipient: AddressSchema$1,
3430
+ claimedBefore: Schema.Literal("0"),
3431
+ documentHash: NonzeroDocumentHashSchema,
3432
+ transfer: Schema.Null
3433
+ });
3434
+ const FinalizedMoneyEvidenceSchema = Schema.Union([
3435
+ FinalizedPaymentEvidenceSchema,
3436
+ FinalizedCommitmentCreationEvidenceSchema,
3437
+ FinalizedCommitmentClaimEvidenceSchema,
3438
+ FinalizedCommitmentCancelEvidenceSchema,
3439
+ FinalizedCommitmentRedirectEvidenceSchema
3440
+ ]);
3441
+ Schema.Union([
3442
+ Schema.Struct({
3443
+ status: Schema.Literal("pending"),
3444
+ reason: Schema.Literals(["receipt_missing", "not_finalized"]),
3445
+ receipt: Schema.optional(ReceiptRefSchema)
3446
+ }),
3447
+ Schema.Struct({
3448
+ status: Schema.Literal("verified"),
3449
+ evidence: FinalizedMoneyEvidenceSchema
3450
+ }),
3451
+ Schema.Struct({
3452
+ status: Schema.Literal("mismatch"),
3453
+ code: PaymentVerificationMismatchCodeSchema,
3454
+ receipt: Schema.optional(ReceiptRefSchema)
3455
+ }),
3456
+ Schema.Struct({
3457
+ status: Schema.Literal("provider_failure"),
3458
+ retryable: Schema.Literal(true)
3459
+ })
3460
+ ]);
3461
+ const FinalizedAttributedInboundMovementSchema = Schema.Struct({
3462
+ movement: MovementSchema,
3463
+ attribution: MovementAttributionSchema
3464
+ });
3465
+ const PaymentCommandLineageSchema = Schema.Union([Schema.Struct({
3466
+ kind: Schema.Literal("payroll"),
3467
+ runId: nonEmpty("runId")
3468
+ }), Schema.Struct({
3469
+ kind: Schema.Literal("payment_request"),
3470
+ requestId: nonEmpty("requestId")
3471
+ })]);
3472
+ const ProtocolBirthInputSchema = Schema.Struct({
3473
+ requestKey: nonEmpty("requestKey"),
3474
+ actor: ActorRefSchema,
3475
+ recipient: ActorOrDestinationRefSchema,
3476
+ recipientSafe: SafeAddressSchema,
3477
+ paymentSenderSafe: SafeAddressSchema,
3478
+ amount: FinancialOpsMoney,
3479
+ ledgerKind: Schema.Literals(["Payment", "Payout"]),
3480
+ purposeKind: PaymentPurposeKindSchema,
3481
+ permissionId: Schema.optional(PermissionIdSchema),
3482
+ settlementId: SettlementIdSchema,
3483
+ documentHash: NonzeroDocumentHashSchema,
3484
+ release: ReleaseTermsSchema,
3485
+ lineage: Schema.optional(PaymentCommandLineageSchema)
3486
+ }).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" }));
3487
+ Schema.Union([
3488
+ Schema.Struct({
3489
+ kind: Schema.Literal("birth"),
3490
+ birth: ProtocolBirthInputSchema
3491
+ }),
3492
+ Schema.Struct({
3493
+ kind: Schema.Literal("birth_deposit"),
3494
+ movement: FinalizedAttributedInboundMovementSchema
3495
+ }),
3496
+ Schema.Struct({
3497
+ kind: Schema.Literal("rollback_deposit"),
3498
+ movementId: MovementIdSchema
3499
+ }),
3500
+ Schema.Struct({
3501
+ kind: Schema.Literal("record_submission"),
3502
+ commandId: PaymentCommandIdSchema,
3503
+ paymentIds: Schema.Array(PaymentIdSchema),
3504
+ userOpHash: Bytes32Schema
3505
+ }),
3506
+ Schema.Struct({
3507
+ kind: Schema.Literal("apply_finalized_evidence"),
3508
+ paymentId: PaymentIdSchema,
3509
+ evidence: FinalizedMoneyEvidenceSchema
3510
+ }),
3511
+ Schema.Struct({
3512
+ kind: Schema.Literal("transition"),
3513
+ paymentId: PaymentIdSchema,
3514
+ event: PaymentTransitionEventSchema
3515
+ })
3516
+ ]);
3517
+ Schema.Union([
3518
+ Schema.Struct({
3519
+ outcome: Schema.Literal("created"),
3520
+ payments: Schema.Array(PaymentLedgerRecordSchema)
3521
+ }),
3522
+ Schema.Struct({
3523
+ outcome: Schema.Literal("changed"),
3524
+ payment: PaymentLedgerRecordSchema
3525
+ }),
3526
+ Schema.Struct({
3527
+ outcome: Schema.Literal("replayed"),
3528
+ payment: PaymentLedgerRecordSchema
3529
+ }),
3530
+ Schema.Struct({
3531
+ outcome: Schema.Literal("removed"),
3532
+ paymentId: PaymentIdSchema,
3533
+ movementId: MovementIdSchema
3534
+ }),
3535
+ Schema.Struct({
3536
+ outcome: Schema.Literal("refused"),
3537
+ error: PaymentCoreErrorSchema
3538
+ })
3539
+ ]);
3540
+ const PaymentBirthItemSchema = Schema.Union([Schema.Struct({
3541
+ operation: Schema.Literal("send"),
3542
+ recipient: ActorOrDestinationRefSchema,
3543
+ amount: FinancialOpsMoney,
3544
+ purposeKind: PaymentPurposeKindSchema,
3545
+ documentHash: Schema.optional(NonzeroDocumentHashSchema)
3546
+ }), Schema.Struct({
3547
+ operation: Schema.Literal("create_commitment"),
3548
+ recipient: ActorOrDestinationRefSchema,
3549
+ amount: FinancialOpsMoney,
3550
+ release: ReleaseTermsSchema.pipe(Schema.refine((release) => release.kind === "scheduled" || release.kind === "stream", { message: "Commitment release must be scheduled or stream" })),
3551
+ purposeKind: PaymentPurposeKindSchema,
3552
+ documentHash: Schema.optional(NonzeroDocumentHashSchema)
3553
+ })]);
3554
+ const PaymentBirthCommandSchema = Schema.Struct({
3555
+ kind: Schema.Literal("birth"),
3556
+ requestKey: nonEmpty("requestKey"),
3557
+ actor: ActorRefSchema,
3558
+ orgId: Schema.optional(nonEmpty("orgId")),
3559
+ permissionId: Schema.optional(PermissionIdSchema),
3560
+ lineage: Schema.optional(PaymentCommandLineageSchema),
3561
+ items: Schema.Array(PaymentBirthItemSchema)
3562
+ }).pipe(Schema.refine((command) => hasActorBoundPermission(command.actor, command.orgId, command.permissionId), { message: "Organization Payment commands require matching orgId and permissionId; personal commands forbid both" }));
3563
+ Schema.Union([
3564
+ PaymentBirthCommandSchema,
3565
+ Schema.Struct({
3566
+ kind: Schema.Literal("claim_commitment"),
3567
+ actor: AccountActorRefSchema,
3568
+ paymentId: PaymentIdSchema
3569
+ }),
3570
+ Schema.Struct({
3571
+ kind: Schema.Literal("cancel_commitment"),
3572
+ actor: ActorRefSchema,
3573
+ paymentId: PaymentIdSchema
3574
+ }),
3575
+ Schema.Struct({
3576
+ kind: Schema.Literal("redirect_commitment"),
3577
+ actor: ActorRefSchema,
3578
+ paymentId: PaymentIdSchema,
3579
+ recipient: ActorOrDestinationRefSchema
3580
+ })
3581
+ ]);
3582
+ const PaymentExecutionRouteSchema = Schema.Union([Schema.Struct({
3583
+ kind: Schema.Literal("direct"),
3584
+ userOpSenderSafe: SafeAddressSchema
3585
+ }), Schema.Struct({
3586
+ kind: Schema.Literal("zodiac_role"),
3587
+ userOpSenderSafe: SafeAddressSchema,
3588
+ organizationSafe: SafeAddressSchema,
3589
+ rolesModule: ModuleAddressSchema,
3590
+ roleKey: RoleKeySchema
3591
+ })]);
3592
+ const PreparedMoneyItemSchema = Schema.Union([
3593
+ Schema.Struct({
3594
+ operation: Schema.Literal("send"),
3595
+ paymentId: PaymentIdSchema,
3596
+ settlementId: SettlementIdSchema,
3597
+ recipientSafe: SafeAddressSchema,
3598
+ tokenAddress: AddressSchema$1,
3599
+ rawAmount: WeiAmountSchema$1,
3600
+ kind: Uint16Schema,
3601
+ documentHash: NonzeroDocumentHashSchema
3602
+ }),
3603
+ Schema.Struct({
3604
+ operation: Schema.Literal("create_commitment"),
3605
+ paymentId: PaymentIdSchema,
3606
+ settlementId: SettlementIdSchema,
3607
+ recipientSafe: SafeAddressSchema,
3608
+ tokenAddress: AddressSchema$1,
3609
+ totalAmount: WeiAmountSchema$1,
3610
+ startTime: Uint48Schema,
3611
+ cliffTime: Uint48Schema,
3612
+ endTime: Uint48Schema,
3613
+ kind: Uint16Schema,
3614
+ documentHash: NonzeroDocumentHashSchema
3615
+ }),
3616
+ Schema.Struct({
3617
+ operation: Schema.Literal("claim_commitment"),
3618
+ paymentId: PaymentIdSchema,
3619
+ commitmentId: Uint256StringSchema
3620
+ }),
3621
+ Schema.Struct({
3622
+ operation: Schema.Literal("cancel_commitment"),
3623
+ paymentId: PaymentIdSchema,
3624
+ commitmentId: Uint256StringSchema,
3625
+ documentHash: NonzeroDocumentHashSchema
3626
+ }),
3627
+ Schema.Struct({
3628
+ operation: Schema.Literal("redirect_commitment"),
3629
+ paymentId: PaymentIdSchema,
3630
+ commitmentId: Uint256StringSchema,
3631
+ recipientSafe: SafeAddressSchema,
3632
+ documentHash: NonzeroDocumentHashSchema
3633
+ })
3634
+ ]);
3635
+ Schema.Struct({
3636
+ commandId: PaymentCommandIdSchema,
3637
+ chainId: ChainIdSchema$1,
3638
+ contractAddress: AddressSchema$1,
3639
+ senderSafe: SafeAddressSchema,
3640
+ executionRoute: PaymentExecutionRouteSchema,
3641
+ items: Schema.Array(PreparedMoneyItemSchema)
3642
+ });
3643
+ Schema.Struct({
3644
+ commandId: PaymentCommandIdSchema,
3645
+ paymentIds: Schema.Array(PaymentIdSchema),
3646
+ userOpHash: Bytes32Schema
3647
+ });
3648
+ 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" }));
3649
+ 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" }));
3650
+ const PaymentExecutionIntentSchema = Schema.Struct({
3651
+ to: PaymentRef,
3652
+ amount: FinancialOpsMoney,
3653
+ paymentType: Schema.optional(Schema.Literals([
3654
+ "unspecified",
3655
+ "invoice",
3656
+ "payroll",
3657
+ "reimbursement"
3658
+ ])),
3659
+ document: Schema.optional(AttachablePaymentDocumentEnvelope),
3660
+ timing: Schema.optional(PaymentTiming),
3661
+ lineItems: Schema.optional(Schema.Array(LineItem))
3662
+ });
3663
+ Schema.Struct({
3664
+ requestKey: nonEmpty("requestKey"),
3665
+ signerAddress: AddressSchema$1,
3666
+ payment: PaymentExecutionIntentSchema
3667
+ });
3668
+ Schema.Struct({
3669
+ executionId: MoneyExecutionIdSchema,
3670
+ commandId: PaymentCommandIdSchema,
3671
+ paymentId: PaymentIdSchema,
3672
+ requestKey: nonEmpty("requestKey"),
3673
+ payment: PaymentExecutionIntentSchema,
3674
+ purposeKind: PaymentPurposeKindSchema,
3675
+ emitPaymentInitiated: Schema.Boolean,
3676
+ chainId: BaseSepoliaChainIdSchema,
3677
+ signerAddress: AddressSchema$1,
3678
+ userOpSenderSafe: SafeAddressSchema,
3679
+ digest: Bytes32Schema
3680
+ });
3681
+ Schema.Struct({
3682
+ executionId: MoneyExecutionIdSchema,
3683
+ signature: OwnerSignatureSchema
3684
+ });
3685
+ Schema.Struct({
3686
+ executionId: MoneyExecutionIdSchema,
3687
+ commandId: PaymentCommandIdSchema,
3688
+ userOpHash: Bytes32Schema,
3689
+ payment: Payment
3690
+ });
3691
+ Schema.Struct({
3692
+ executionId: MoneyExecutionIdSchema,
3693
+ commandId: PaymentCommandIdSchema,
3694
+ userOpHash: Bytes32Schema,
3695
+ payments: Schema.Array(Payment)
3696
+ });
3697
+ const PaymentLifecycleExecutionIntentSchema = Schema.Union([
3698
+ Schema.Struct({
3699
+ kind: Schema.Literal("claim"),
3700
+ paymentId: PaymentIdSchema
3701
+ }),
3702
+ Schema.Struct({
3703
+ kind: Schema.Literal("cancel"),
3704
+ paymentId: PaymentIdSchema
3705
+ }),
3706
+ Schema.Struct({
3707
+ kind: Schema.Literal("redirect"),
3708
+ paymentId: PaymentIdSchema,
3709
+ recipient: PaymentRef
3710
+ })
3711
+ ]);
3712
+ Schema.Struct({
3713
+ signerAddress: AddressSchema$1,
3714
+ intent: PaymentLifecycleExecutionIntentSchema
3715
+ });
3716
+ const OrganizationPaymentExecutionItemSchema = Schema.Struct({
3717
+ to: PaymentRef,
3718
+ amount: FinancialOpsMoney,
3719
+ paymentType: Schema.optional(Schema.Literals([
3720
+ "unspecified",
3721
+ "invoice",
3722
+ "payroll",
3723
+ "reimbursement"
3724
+ ])),
3725
+ document: Schema.optional(AttachablePaymentDocumentEnvelope)
3726
+ });
3727
+ Schema.Struct({
3728
+ orgId: nonEmpty("orgId"),
3729
+ permissionId: PermissionIdSchema,
3730
+ requestKey: nonEmpty("requestKey"),
3731
+ signerAddress: AddressSchema$1,
3732
+ items: Schema.Array(OrganizationPaymentExecutionItemSchema),
3733
+ lineage: Schema.optional(PaymentCommandLineageSchema)
3734
+ });
3735
+ Schema.Struct({
3736
+ executionId: MoneyExecutionIdSchema,
3737
+ commandId: PaymentCommandIdSchema,
3738
+ paymentIds: Schema.Array(PaymentIdSchema),
3739
+ request: Schema.Union([PaymentLifecycleExecutionIntentSchema, Schema.Struct({
3740
+ orgId: nonEmpty("orgId"),
3741
+ permissionId: PermissionIdSchema,
3742
+ requestKey: nonEmpty("requestKey"),
3743
+ items: Schema.Array(OrganizationPaymentExecutionItemSchema),
3744
+ lineage: Schema.optional(PaymentCommandLineageSchema)
3745
+ })]),
3746
+ chainId: BaseSepoliaChainIdSchema,
3747
+ signerAddress: AddressSchema$1,
3748
+ userOpSenderSafe: SafeAddressSchema,
3749
+ digest: Bytes32Schema
3750
+ });
3751
+ const PermissionIntentSchema = Schema.Union([Schema.Struct({
3752
+ type: Schema.Literal("budget"),
3753
+ limit: FinancialOpsMoney
3754
+ }), Schema.Struct({ type: Schema.Literal("managePeople") })]);
3755
+ const PermissionCommandSchema = Schema.Union([
3756
+ Schema.Struct({
3757
+ operation: Schema.Literal("create"),
3758
+ requestKey: nonEmpty("requestKey"),
3759
+ intent: PermissionIntentSchema
3760
+ }),
3761
+ Schema.Struct({
3762
+ operation: Schema.Literal("change"),
3763
+ requestKey: nonEmpty("requestKey"),
3764
+ permissionId: PermissionIdSchema,
3765
+ intent: PermissionIntentSchema
3766
+ }),
3767
+ Schema.Struct({
3768
+ operation: Schema.Literal("assign"),
3769
+ requestKey: nonEmpty("requestKey"),
3770
+ permissionId: PermissionIdSchema,
3771
+ accountId: nonEmpty("accountId")
3772
+ }),
3773
+ Schema.Struct({
3774
+ operation: Schema.Literal("revoke"),
3775
+ requestKey: nonEmpty("requestKey"),
3776
+ permissionAssignmentId: PermissionAssignmentIdSchema
3777
+ }),
3778
+ Schema.Struct({
3779
+ operation: Schema.Literal("replace"),
3780
+ requestKey: nonEmpty("requestKey")
3781
+ })
3782
+ ]);
3783
+ const PermissionChainCallSchema = Schema.Struct({
3784
+ to: AddressSchema$1,
3785
+ value: Schema.Literal("0"),
3786
+ data: HexDataSchema
3787
+ });
3788
+ const PermissionResourceSchema = Schema.Union([
3789
+ PermissionSchema,
3790
+ PermissionAssignmentSchema,
3791
+ Schema.Array(PermissionSchema)
3792
+ ]);
3793
+ Schema.Struct({
3794
+ status: Schema.Literal("prepared"),
3795
+ commandId: PaymentCommandIdSchema,
3796
+ operation: PermissionOperationSchema,
3797
+ expectedRevision: nonNegativeInteger("expectedRevision"),
3798
+ userOpSenderSafe: SafeAddressSchema,
3799
+ organizationSafe: SafeAddressSchema,
3800
+ calls: Schema.Array(PermissionChainCallSchema),
3801
+ value: PermissionResourceSchema
3802
+ });
3803
+ Schema.Struct({
3804
+ orgId: nonEmpty("orgId"),
3805
+ signerAddress: AddressSchema$1,
3806
+ command: PermissionCommandSchema
3807
+ });
3808
+ Schema.Struct({
3809
+ executionId: MoneyExecutionIdSchema,
3810
+ commandId: PaymentCommandIdSchema,
3811
+ operation: PermissionOperationSchema,
3812
+ orgId: nonEmpty("orgId"),
3813
+ command: PermissionCommandSchema,
3814
+ expectedRevision: nonNegativeInteger("expectedRevision"),
3815
+ chainId: BaseSepoliaChainIdSchema,
3816
+ signerAddress: AddressSchema$1,
3817
+ userOpSenderSafe: SafeAddressSchema,
3818
+ digest: Bytes32Schema,
3819
+ value: PermissionResourceSchema
3820
+ });
3821
+ Schema.Struct({
3822
+ status: Schema.Literal("submitted"),
3823
+ executionId: MoneyExecutionIdSchema,
3824
+ commandId: PaymentCommandIdSchema,
3825
+ userOpHash: Bytes32Schema,
3826
+ value: PermissionResourceSchema
3827
+ });
3828
+ `
3829
+ .capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;
3830
+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;
3831
+ color:var(--ink);background:var(--bg);max-width:44rem;margin:0 auto;padding:2.75rem 3rem;
3832
+ border:1px solid var(--line);border-radius:16px;box-shadow:0 1px 2px rgba(0,0,0,.04),0 12px 32px rgba(0,0,0,.06);
3833
+ line-height:1.5;font-size:15px;overflow-wrap:anywhere;word-break:break-word}
3834
+ .capxul-doc *{box-sizing:border-box;min-width:0}
3835
+ .capxul-doc .doc-header{display:flex;flex-direction:column;gap:1.25rem;padding-bottom:1.5rem;border-bottom:1px solid var(--line);margin-bottom:1.75rem}
3836
+ .capxul-doc .doc-brand{display:flex;align-items:center;gap:.5rem;color:var(--accent);font-weight:600}
3837
+ .capxul-doc .doc-brand-mark{font-size:1.1rem}
3838
+ .capxul-doc .doc-brand-name{letter-spacing:.02em}
3839
+ .capxul-doc .doc-headline{display:flex;align-items:baseline;justify-content:space-between;gap:1rem;flex-wrap:wrap}
3840
+ .capxul-doc .doc-title{font-size:1.9rem;font-weight:700;letter-spacing:-.02em;margin:0}
3841
+ .capxul-doc .doc-badge{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;
3842
+ color:var(--accent);background:rgba(10,125,75,.1);padding:.3rem .6rem;border-radius:999px;max-width:100%;text-align:right}
3843
+ .capxul-doc .doc-parties{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;margin-bottom:1.75rem}
3844
+ .capxul-doc .doc-party{display:flex;flex-direction:column;gap:.15rem}
3845
+ .capxul-doc .doc-party-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
3846
+ .capxul-doc .doc-party-name{font-weight:600}
3847
+ .capxul-doc .doc-meta{display:flex;flex-direction:column;gap:.4rem;margin-bottom:1.75rem}
3848
+ .capxul-doc .doc-meta-row{display:flex;justify-content:space-between;gap:1rem;font-size:.92rem}
3849
+ .capxul-doc .doc-meta-label{color:var(--muted);flex-shrink:0}
3850
+ .capxul-doc .doc-meta-value{font-weight:500;text-align:right}
3851
+ .capxul-doc time{color:var(--ink);font-variant-numeric:tabular-nums}
3852
+ .capxul-doc .doc-line-items{width:100%;border-collapse:collapse;margin:.5rem 0 1.5rem;font-size:.92rem}
3853
+ .capxul-doc .doc-line-items th{text-align:left;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;
3854
+ color:var(--muted);font-weight:600;padding:.5rem .25rem;border-bottom:1px solid var(--line)}
3855
+ .capxul-doc .doc-line-items td{padding:.7rem .25rem;border-bottom:1px solid var(--line)}
3856
+ .capxul-doc .doc-li-qty,.capxul-doc .doc-li-unit,.capxul-doc .doc-li-total{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
3857
+ .capxul-doc .doc-li-desc{width:100%}
3858
+ .capxul-doc .doc-totals{display:flex;flex-direction:column;gap:.5rem;margin-top:.5rem}
3859
+ .capxul-doc .doc-total-line{display:flex;justify-content:space-between;align-items:baseline;gap:1rem}
3860
+ .capxul-doc .doc-total-label{color:var(--muted)}
3861
+ .capxul-doc .doc-total-deduction .doc-amount-value{color:var(--muted)}
3862
+ .capxul-doc .doc-total-grand{border-top:2px solid var(--ink);margin-top:.5rem;padding-top:.75rem;font-size:1.15rem}
3863
+ .capxul-doc .doc-total-grand .doc-amount-value{font-weight:700}
3864
+ .capxul-doc .doc-amount-value{font-variant-numeric:tabular-nums;font-weight:600}
3865
+ .capxul-doc .doc-hero{text-align:center;padding:1.5rem 0 2rem}
3866
+ .capxul-doc .doc-hero-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}
3867
+ .capxul-doc .doc-hero-amount{font-size:2.6rem;font-weight:700;letter-spacing:-.02em;margin-top:.35rem}
3868
+ .capxul-doc .doc-note{color:var(--ink);background:#f7f7f8;border-radius:10px;padding:.9rem 1.1rem;margin:0}
3869
+ .capxul-doc .doc-dest-address{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9rem}
3870
+ .capxul-doc .doc-footer{margin-top:1.75rem;padding-top:1.25rem;border-top:1px solid var(--line);color:var(--muted);font-size:.9rem}
3871
+ .capxul-doc code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.82rem;color:var(--muted);word-break:break-all}
3872
+ @media (max-width:540px){.capxul-doc{padding:1.75rem 1.25rem}.capxul-doc .doc-parties{grid-template-columns:1fr}}
3873
+ `.trim();
3874
+ //#endregion
3875
+ //#region ../wire/src/secret-material.ts
3876
+ const SENSITIVE_MATERIAL_PATTERNS = [
3877
+ /0x[a-fA-F0-9]{40,}/u,
3878
+ /(?:^|[^a-fA-F0-9])[a-fA-F0-9]{64}(?:$|[^a-fA-F0-9])/u,
3879
+ /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/u,
3880
+ /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/iu
3881
+ ];
3882
+ /**
3883
+ * Reject: does the value carry any known secret material? Best effort — callers
3884
+ * drop the whole value on a match; a false negative is a leak, a false positive
3885
+ * merely omits an observation field.
3886
+ */
3887
+ function containsSensitiveMaterial(value) {
3888
+ return SENSITIVE_MATERIAL_PATTERNS.some((pattern) => pattern.test(value));
3889
+ }
3890
+ //#endregion
3891
+ //#region ../wire/src/observation-context.ts
3892
+ /** Single bounded HTTP carrier used before a Convex action envelope exists. */
3893
+ const OBSERVATION_CONTEXT_HEADER = "x-capxul-observation-context";
3894
+ const FIELD_RULES = {
3895
+ application: {
3896
+ maxLength: 64,
3897
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._-]*$/u
3898
+ },
3899
+ applicationId: {
3900
+ maxLength: 30,
3901
+ pattern: APP_ID_RE
3902
+ },
3903
+ release: {
3904
+ maxLength: 128,
3905
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._+@:/-]*$/u
3906
+ },
3907
+ sessionId: {
3908
+ maxLength: 128,
3909
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3910
+ },
3911
+ organizationId: {
3912
+ maxLength: 128,
3913
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3914
+ },
3915
+ journeyId: {
3916
+ maxLength: 128,
3917
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3918
+ },
3919
+ correlationId: {
3920
+ maxLength: 128,
3921
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
3922
+ },
3923
+ anonymousId: {
3924
+ maxLength: 128,
3925
+ pattern: /^anon_[A-Za-z0-9-]+$/u
3926
+ },
3927
+ traceparent: {
3928
+ maxLength: 55,
3929
+ pattern: /^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/u
3930
+ }
3931
+ };
3932
+ /**
3933
+ * Copy only the canonical allowlist and silently omit malformed/sensitive
3934
+ * values. Observation metadata is best effort and may never reject a domain
3935
+ * operation.
3936
+ */
3937
+ function sanitizeObservationContext(input) {
3938
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return void 0;
3939
+ const source = input;
3940
+ const sanitized = {};
3941
+ for (const field of Object.keys(FIELD_RULES)) {
3942
+ const value = source[field];
3943
+ if (!isSafeField(field, value)) continue;
3944
+ sanitized[field] = value;
3945
+ }
3946
+ return Object.keys(sanitized).length === 0 ? void 0 : sanitized;
3947
+ }
3948
+ /** Encode only the sanitized allowlist; absence stays absence. */
3949
+ function encodeObservationContextHeader(input) {
2277
3950
  const sanitized = sanitizeObservationContext(input);
2278
3951
  return sanitized === void 0 ? void 0 : JSON.stringify(sanitized);
2279
3952
  }
@@ -2295,14 +3968,30 @@ const actorScopeContract = {
2295
3968
  requestsList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].list),
2296
3969
  requestsGet: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].get),
2297
3970
  requestsCancel: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].cancel),
2298
- requestsReconcile: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].reconcile),
2299
3971
  inboxList: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].inboxList),
2300
3972
  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)
3973
+ inboxDecline: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/requestsInbox"].decline)
2304
3974
  };
2305
3975
  //#endregion
3976
+ //#region src/domain/money/from-wei.ts
3977
+ /**
3978
+ * Lift an on-chain integer (e.g. USDX 6-decimal) into consumer `Money`.
3979
+ * Canon `account-balance-model.md` §10 — internal at the SDK boundary only.
3980
+ */
3981
+ function fromWei(rawBalance, decimals, currency) {
3982
+ if (!Number.isInteger(decimals) || decimals < 0) throw new Error(`fromWei: decimals must be a non-negative integer, got ${String(decimals)}`);
3983
+ const normalized = rawBalance.trim();
3984
+ if (!/^\d+$/.test(normalized)) {
3985
+ const truncated = normalized.length > 80 ? `${normalized.slice(0, 80)}…` : normalized;
3986
+ throw new Error(`fromWei: rawBalance must be a base-10 integer string, got ${truncated}`);
3987
+ }
3988
+ return {
3989
+ currency: toCurrencyCode(currency),
3990
+ value: formatUnits(BigInt(normalized), decimals),
3991
+ decimals
3992
+ };
3993
+ }
3994
+ //#endregion
2306
3995
  //#region src/surface/contacts.ts
2307
3996
  function makeActorRelationshipMethods(deps) {
2308
3997
  const domain = deps.actor.kind === "account" ? "account" : "org";
@@ -2312,11 +4001,11 @@ function makeActorRelationshipMethods(deps) {
2312
4001
  const fns = actorScopeContract;
2313
4002
  return {
2314
4003
  addressBook: {
2315
- list: (options) => mapOk$2(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
4004
+ list: (options) => mapOk$1(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
2316
4005
  get: async (entryId, options) => {
2317
4006
  const ref = refFromEntryId(entryId);
2318
4007
  if (!ref.ok) return ref;
2319
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
4008
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
2320
4009
  actor,
2321
4010
  ref: ref.value
2322
4011
  })), (entry) => entry === null ? null : mapAddressBookEntry(entry));
@@ -2324,7 +4013,7 @@ function makeActorRelationshipMethods(deps) {
2324
4013
  add: async (input, options) => {
2325
4014
  const ref = normalizeRefForBackend$1(input.ref, "ref");
2326
4015
  if (!ref.ok) return ref;
2327
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
4016
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
2328
4017
  actor,
2329
4018
  ref: ref.value,
2330
4019
  ...input.label === void 0 ? {} : { label: input.label }
@@ -2333,7 +4022,7 @@ function makeActorRelationshipMethods(deps) {
2333
4022
  hide: async (entryId, options) => {
2334
4023
  const ref = refFromEntryId(entryId);
2335
4024
  if (!ref.ok) return ref;
2336
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
4025
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
2337
4026
  actor,
2338
4027
  ref: ref.value
2339
4028
  })), mapAddressBookEntry);
@@ -2341,7 +4030,7 @@ function makeActorRelationshipMethods(deps) {
2341
4030
  unhide: async (entryId, options) => {
2342
4031
  const ref = refFromEntryId(entryId);
2343
4032
  if (!ref.ok) return ref;
2344
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
4033
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
2345
4034
  actor,
2346
4035
  ref: ref.value
2347
4036
  })), mapAddressBookEntry);
@@ -2349,7 +4038,7 @@ function makeActorRelationshipMethods(deps) {
2349
4038
  label: async (input, options) => {
2350
4039
  const ref = refFromEntryId(input.entryId);
2351
4040
  if (!ref.ok) return ref;
2352
- return mapOk$2(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
4041
+ return mapOk$1(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
2353
4042
  actor,
2354
4043
  ref: ref.value,
2355
4044
  label: input.label
@@ -2360,7 +4049,7 @@ function makeActorRelationshipMethods(deps) {
2360
4049
  issue: async (input, options) => {
2361
4050
  const payer = normalizeRefForBackend$1(input.payer, "payer");
2362
4051
  if (!payer.ok) return payer;
2363
- return mapOk$2(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
4052
+ return mapOk$1(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
2364
4053
  actor,
2365
4054
  payer: payer.value,
2366
4055
  amount: input.amount,
@@ -2369,43 +4058,41 @@ function makeActorRelationshipMethods(deps) {
2369
4058
  ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
2370
4059
  })), (request) => mapActorRequest(request, input.payer));
2371
4060
  },
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, {
4061
+ list: (options) => mapOk$1(awaitableConvex(options?.signal, "requests.list", () => convexCall.query(fns.requestsList, { actor })), (requests) => requests.map((request) => mapActorRequest(request))),
4062
+ get: (requestId, options) => mapOk$1(awaitableConvex(options?.signal, "requests.get", () => convexCall.query(fns.requestsGet, {
2374
4063
  actor,
2375
4064
  paymentRequestId: requestId
2376
4065
  })), (request) => request === null ? null : mapActorRequest(request)),
2377
- cancel: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "requests.cancel", () => convexCall.mutation(fns.requestsCancel, {
4066
+ cancel: (requestId, options) => mapOk$1(awaitableConvex(options?.signal, "requests.cancel", () => convexCall.mutation(fns.requestsCancel, {
2378
4067
  actor,
2379
4068
  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
- }
4069
+ })), (request) => mapActorRequest(request))
2384
4070
  },
2385
4071
  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, {
2388
- actor,
2389
- paymentRequestId: input.requestId,
2390
- ...input.timing === void 0 ? {} : { timing: input.timing }
2391
- })), mapApprovedInboxPayment),
2392
- decline: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "inbox.decline", () => convexCall.mutation(fns.inboxDecline, {
4072
+ list: (options) => mapOk$1(awaitableConvex(options?.signal, "inbox.list", () => convexCall.query(fns.inboxList, { actor })), (items) => items.map(mapInboxItem)),
4073
+ approve: async (input, options) => {
4074
+ const result = await awaitableConvex(options?.signal, "inbox.approve", () => convexCall.mutation(fns.inboxApprove, {
4075
+ actor,
4076
+ paymentRequestId: input.requestId,
4077
+ ...input.timing === void 0 ? {} : { timing: input.timing },
4078
+ ...input.permissionId === void 0 ? {} : { permissionId: input.permissionId }
4079
+ }));
4080
+ if (!result.ok) return result;
4081
+ return mapApprovedInboxPayment(result.value, input);
4082
+ },
4083
+ decline: (requestId, options) => mapOk$1(awaitableConvex(options?.signal, "inbox.decline", () => convexCall.mutation(fns.inboxDecline, {
2393
4084
  actor,
2394
4085
  paymentRequestId: requestId
2395
4086
  })), mapInboxItem)
2396
4087
  },
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
4088
  profile: {
2402
4089
  get: (options) => {
2403
4090
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
2404
- return missingConvexCall$1(`${domain}.profile.get`);
4091
+ return missingConvexCall(`${domain}.profile.get`);
2405
4092
  },
2406
4093
  depositInstructions: (options) => {
2407
4094
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
2408
- return missingConvexCall$1(`${domain}.profile.depositInstructions`);
4095
+ return missingConvexCall(`${domain}.profile.depositInstructions`);
2409
4096
  }
2410
4097
  }
2411
4098
  };
@@ -2413,37 +4100,32 @@ function makeActorRelationshipMethods(deps) {
2413
4100
  function makeNotImplementedActorRelationshipMethods(deps, domain) {
2414
4101
  return {
2415
4102
  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")
4103
+ list: () => missingConvexCall("addressBook.list"),
4104
+ get: () => missingConvexCall("addressBook.get"),
4105
+ add: () => missingConvexCall("addressBook.add"),
4106
+ hide: () => missingConvexCall("addressBook.hide"),
4107
+ unhide: () => missingConvexCall("addressBook.unhide"),
4108
+ label: () => missingConvexCall("addressBook.label")
2422
4109
  },
2423
4110
  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")
4111
+ issue: () => missingConvexCall("requests.issue"),
4112
+ list: () => missingConvexCall("requests.list"),
4113
+ get: () => missingConvexCall("requests.get"),
4114
+ cancel: () => missingConvexCall("requests.cancel")
2429
4115
  },
2430
4116
  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")
4117
+ list: () => missingConvexCall("inbox.list"),
4118
+ approve: () => missingConvexCall("inbox.approve"),
4119
+ decline: () => missingConvexCall("inbox.decline")
2438
4120
  },
2439
4121
  profile: {
2440
4122
  get: (options) => {
2441
4123
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
2442
- return missingConvexCall$1(`${domain}.profile.get`);
4124
+ return missingConvexCall(`${domain}.profile.get`);
2443
4125
  },
2444
4126
  depositInstructions: (options) => {
2445
4127
  if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
2446
- return missingConvexCall$1(`${domain}.profile.depositInstructions`);
4128
+ return missingConvexCall(`${domain}.profile.depositInstructions`);
2447
4129
  }
2448
4130
  }
2449
4131
  };
@@ -2460,13 +4142,13 @@ async function mapAccountProfile(resultPromise) {
2460
4142
  }
2461
4143
  };
2462
4144
  }
2463
- function missingConvexCall$1(operation) {
4145
+ function missingConvexCall(operation) {
2464
4146
  return Promise.resolve({
2465
4147
  ok: false,
2466
4148
  error: Errors.providerError("convex", operation, "ConvexCallPort is required")
2467
4149
  });
2468
4150
  }
2469
- async function mapOk$2(resultOrPromise, f) {
4151
+ async function mapOk$1(resultOrPromise, f) {
2470
4152
  const result = await resultOrPromise;
2471
4153
  if (!result.ok) return result;
2472
4154
  return {
@@ -2512,59 +4194,45 @@ function mapInboxItem(item) {
2512
4194
  status: mapInboxStatus(item.status)
2513
4195
  };
2514
4196
  }
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
- function mapApprovedInboxPayment(item) {
2525
- if (item.settledPayment !== void 0) return normalizePaymentTiming$2(item.settledPayment);
2526
- const zero = {
2527
- ...item.amount,
2528
- value: "0"
2529
- };
2530
- const status = item.settledPaymentStatus ?? (item.status === "paid" ? "settled" : "pending");
2531
- const timing = item.settledPaymentTiming ?? { kind: "instant" };
2532
- return {
2533
- id: item.settledPaymentId ?? `payment_${item.id}`,
2534
- status,
2535
- amount: item.amount,
2536
- paymentType: "invoice",
2537
- recipient: paymentRecipientFromRef(item.issuer),
2538
- documents: [],
2539
- timing,
2540
- released: status === "settled" ? item.amount : zero,
2541
- availableToClaim: zero,
2542
- createdAt: item.createdAt ?? 0,
2543
- updatedAt: item.updatedAt ?? item.createdAt ?? 0
4197
+ function mapApprovedInboxPayment(command, input) {
4198
+ const item = command.items[0];
4199
+ if (item === void 0 || item.operation !== "send" && item.operation !== "create_commitment") return {
4200
+ ok: false,
4201
+ error: Errors.providerError("convex", "inbox.approve", "reply has no payment birth item")
2544
4202
  };
2545
- }
2546
- function paymentRecipientFromRef(ref) {
2547
- switch (ref.kind) {
2548
- case "handle": return {
2549
- kind: "handle",
2550
- label: ref.handle
2551
- };
2552
- case "email": return {
2553
- kind: "email",
2554
- label: ref.email
2555
- };
2556
- case "orgHandle": return {
2557
- kind: "org",
2558
- label: ref.orgHandle
4203
+ try {
4204
+ const amount = fromWei(item.operation === "send" ? item.rawAmount : item.totalAmount, 6, "USD");
4205
+ const zero = {
4206
+ ...amount,
4207
+ value: "0"
2559
4208
  };
2560
- case "capxulUserId": return {
2561
- kind: "capxulUserId",
2562
- label: ref.capxulUserId
4209
+ const timing = input.timing ?? { kind: "instant" };
4210
+ return {
4211
+ ok: true,
4212
+ value: {
4213
+ id: item.paymentId,
4214
+ status: timing.kind === "instant" ? "pending" : timing.kind === "scheduled" ? "scheduled" : "streaming",
4215
+ amount,
4216
+ paymentType: "invoice",
4217
+ recipient: {
4218
+ kind: "external_address",
4219
+ label: item.recipientSafe
4220
+ },
4221
+ documents: [{
4222
+ documentHash: item.documentHash,
4223
+ kind: "invoice"
4224
+ }],
4225
+ timing,
4226
+ released: zero,
4227
+ availableToClaim: zero,
4228
+ createdAt: 0,
4229
+ updatedAt: 0
4230
+ }
2563
4231
  };
2564
- case "payeeId": return {
2565
- kind: "payee",
2566
- label: ref.payeeId,
2567
- payeeId: ref.payeeId
4232
+ } catch (cause) {
4233
+ return {
4234
+ ok: false,
4235
+ error: Errors.providerError("convex", "inbox.approve", cause)
2568
4236
  };
2569
4237
  }
2570
4238
  }
@@ -2592,13 +4260,6 @@ function mapInboxStatus(status) {
2592
4260
  default: return "open";
2593
4261
  }
2594
4262
  }
2595
- function normalizePaymentTiming$2(payment) {
2596
- const { release: _release, ...rest } = payment;
2597
- return {
2598
- ...rest,
2599
- timing: payment.timing ?? payment.release ?? { kind: "instant" }
2600
- };
2601
- }
2602
4263
  function normalizeRefForBackend$1(ref, field) {
2603
4264
  try {
2604
4265
  if (typeof ref === "string") throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
@@ -2944,7 +4605,7 @@ function makeAccountMethods(deps) {
2944
4605
  }
2945
4606
  //#endregion
2946
4607
  //#region package.json
2947
- var version = "1.2.3";
4608
+ var version = "2.0.1";
2948
4609
  //#endregion
2949
4610
  //#region src/ports/auth-client.ts
2950
4611
  var AuthClientError = class extends Data.TaggedError("AuthClientError") {};
@@ -3048,51 +4709,19 @@ function wireChainId(chainId) {
3048
4709
  return chainId;
3049
4710
  }
3050
4711
  //#endregion
3051
- //#region src/domain/money/to-wei.ts
3052
- /**
3053
- * Lower consumer `Money` into an on-chain integer string for guarded writes.
3054
- * Canon `account-balance-model.md` §10 — internal at the SDK boundary only.
3055
- */
3056
- function toWei(money) {
3057
- return parseUnits(money.value, money.decimals).toString();
3058
- }
3059
- //#endregion
3060
- //#region src/ports/account-read.ts
3061
- var AccountReadError = class extends Data.TaggedError("AccountReadError") {};
3062
- function accountReadErrorFromCapxul(operation, error, cause = error) {
3063
- return new AccountReadError({
3064
- operation,
3065
- publicCode: error.code,
3066
- publicError: error,
3067
- cause,
3068
- ...error.details === void 0 ? {} : { details: error.details }
3069
- });
3070
- }
3071
- var AccountReadPortTag = class extends Context.Service()("@capxul/sdk/ports/AccountReadPort") {};
3072
- //#endregion
3073
- //#region src/domain/money/from-wei.ts
4712
+ //#region src/domain/money/to-wei.ts
3074
4713
  /**
3075
- * Lift an on-chain integer (e.g. USDX 6-decimal) into consumer `Money`.
4714
+ * Lower consumer `Money` into an on-chain integer string for guarded writes.
3076
4715
  * Canon `account-balance-model.md` §10 — internal at the SDK boundary only.
3077
4716
  */
3078
- function fromWei(rawBalance, decimals, currency) {
3079
- if (!Number.isInteger(decimals) || decimals < 0) throw new Error(`fromWei: decimals must be a non-negative integer, got ${String(decimals)}`);
3080
- const normalized = rawBalance.trim();
3081
- if (!/^\d+$/.test(normalized)) {
3082
- const truncated = normalized.length > 80 ? `${normalized.slice(0, 80)}…` : normalized;
3083
- throw new Error(`fromWei: rawBalance must be a base-10 integer string, got ${truncated}`);
3084
- }
3085
- return {
3086
- currency: toCurrencyCode(currency),
3087
- value: formatUnits(BigInt(normalized), decimals),
3088
- decimals
3089
- };
4717
+ function toWei(money) {
4718
+ return parseUnits(money.value, money.decimals).toString();
3090
4719
  }
3091
4720
  //#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({
4721
+ //#region src/ports/account-read.ts
4722
+ var AccountReadError = class extends Data.TaggedError("AccountReadError") {};
4723
+ function accountReadErrorFromCapxul(operation, error, cause = error) {
4724
+ return new AccountReadError({
3096
4725
  operation,
3097
4726
  publicCode: error.code,
3098
4727
  publicError: error,
@@ -3100,7 +4729,7 @@ function subAccountErrorFromCapxul(operation, error, cause = error) {
3100
4729
  ...error.details === void 0 ? {} : { details: error.details }
3101
4730
  });
3102
4731
  }
3103
- var SubAccountPortTag = class extends Context.Service()("@capxul/sdk/ports/SubAccountPort") {};
4732
+ var AccountReadPortTag = class extends Context.Service()("@capxul/sdk/ports/AccountReadPort") {};
3104
4733
  //#endregion
3105
4734
  //#region src/ports/smart-account.ts
3106
4735
  var SmartAccountError = class extends Data.TaggedError("SmartAccountError") {};
@@ -3130,31 +4759,15 @@ const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeI
3130
4759
  const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
3131
4760
  const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
3132
4761
  const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
3133
- const SUBACCOUNT_ID_TELEMETRY_RE = /^subaccount_[0-9A-Za-z]+$/;
3134
4762
  const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
3135
4763
  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
4764
  const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
3138
4765
  const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
3139
4766
  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
4767
  const OptionalAccountId = Schema.optional(AccountIdSchema);
3151
- const OptionalSubAccountId = Schema.optional(SubAccountIdSchema);
3152
4768
  const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
3153
4769
  const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
3154
4770
  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
4771
  const OptionalAddress = Schema.optional(AddressSchema);
3159
4772
  const OptionalAppId = Schema.optional(AppIdSchema);
3160
4773
  const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
@@ -3163,11 +4776,6 @@ const OptionalDurationMs = Schema.optional(DurationMsSchema);
3163
4776
  const OptionalEpochMs = Schema.optional(EpochMsSchema);
3164
4777
  const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
3165
4778
  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
4779
  /**
3172
4780
  * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
3173
4781
  * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
@@ -3293,45 +4901,6 @@ const FaucetFailedProps = Schema.Struct({
3293
4901
  ...TelemetryEnvelopeProps,
3294
4902
  reason: OptionalString
3295
4903
  });
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
4904
  const ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;
3336
4905
  const OrgIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => ORG_ID_TELEMETRY_RE.test(value), { message: "must be org_ plus an alphanumeric id" }));
3337
4906
  const OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);
@@ -3456,75 +5025,70 @@ const OrgInviteAcceptedProps = Schema.Struct({
3456
5025
  role: OptionalString,
3457
5026
  status: OptionalString
3458
5027
  });
3459
- const OrgRoleGrantedProps = Schema.Struct({
5028
+ const OrgInviteExpiredProps = Schema.Struct({
3460
5029
  ...TelemetryEnvelopeProps,
3461
5030
  org_id: OptionalOrgId,
5031
+ email_domain: OptionalString,
5032
+ reason: OptionalString,
3462
5033
  role: OptionalString,
3463
- status: OptionalString,
3464
- txHash: OptionalTxHash
5034
+ status: OptionalString
3465
5035
  });
3466
- const OrgMemberActiveProps = Schema.Struct({
5036
+ const PaymentInitiatedProps = Schema.Struct({
3467
5037
  ...TelemetryEnvelopeProps,
3468
- org_id: OptionalOrgId,
3469
- role: OptionalString,
3470
- status: OptionalString,
3471
- durationMs: OptionalDurationMs
5038
+ kind: Schema.String,
5039
+ payment_id: Schema.String
3472
5040
  });
3473
- const OrgMemberRemovedProps = Schema.Struct({
5041
+ const PaymentSettledL2Props = Schema.Struct({
3474
5042
  ...TelemetryEnvelopeProps,
3475
- org_id: OptionalOrgId,
3476
- role: OptionalString,
3477
- status: OptionalString,
3478
- txHash: OptionalTxHash
5043
+ kind: Schema.String,
5044
+ chain_id: Schema.Number,
5045
+ settlement_id: Schema.String
3479
5046
  });
3480
- const OrgInviteExpiredProps = Schema.Struct({
5047
+ const PaymentFailedL2Props = Schema.Struct({
3481
5048
  ...TelemetryEnvelopeProps,
3482
- org_id: OptionalOrgId,
3483
- email_domain: OptionalString,
3484
- reason: OptionalString,
3485
- role: OptionalString,
3486
- status: OptionalString
5049
+ kind: Schema.String,
5050
+ payment_id: Schema.String,
5051
+ reason_code: Schema.String
3487
5052
  });
3488
- const OrgRoleGrantFailedProps = Schema.Struct({
5053
+ const DepositInitiatedProps = Schema.Struct({ ...TelemetryEnvelopeProps });
5054
+ const DepositSettledProps = Schema.Struct({
3489
5055
  ...TelemetryEnvelopeProps,
3490
- org_id: OptionalOrgId,
3491
- reason: OptionalString,
3492
- role: OptionalString
5056
+ chain_id: Schema.Number,
5057
+ tx_hash: Schema.String,
5058
+ log_index: Schema.Number
3493
5059
  });
3494
- const OptionalPaymentId = Schema.optional(PaymentIdTelemetrySchema);
3495
- const OptionalPayeeId = Schema.optional(PayeeIdTelemetrySchema);
3496
- const OptionalDocumentHash = Schema.optional(DocumentHashSchema);
3497
- const PaymentTargetTelemetryProps = Schema.Struct({
5060
+ const PermissionMirrorVerificationProps = Schema.Struct({
3498
5061
  ...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({
5062
+ outcome: Schema.String,
5063
+ reason: Schema.String,
5064
+ chain_id: Schema.Number,
5065
+ finality: Schema.String,
5066
+ lag_blocks: Schema.Number,
5067
+ retry_count: Schema.Number
5068
+ });
5069
+ const MovementScanWindowProps = Schema.Struct({
3509
5070
  ...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
5071
+ chain_id: Schema.Number,
5072
+ token_address: Schema.String,
5073
+ from_block: Schema.Number,
5074
+ to_block: Schema.Number,
5075
+ log_count: Schema.Number,
5076
+ request_count: Schema.Number,
5077
+ outcome: Schema.String
5078
+ });
5079
+ const MovementScanCheckpointProps = Schema.Struct({
5080
+ ...TelemetryEnvelopeProps,
5081
+ chain_id: Schema.Number,
5082
+ token_address: Schema.String,
5083
+ next_block: Schema.Number,
5084
+ anchor_block_number: Schema.Number
3518
5085
  });
3519
- const WithdrawalTargetTelemetryProps = Schema.Struct({
5086
+ const MovementScanIncidentProps = Schema.Struct({
3520
5087
  ...TelemetryEnvelopeProps,
3521
- payment_id: OptionalPaymentId,
3522
- document_hash: OptionalDocumentHash,
3523
- amount: OptionalWeiAmount,
3524
- currency: OptionalCurrencyCode,
3525
- status: OptionalString,
3526
- reason: OptionalString,
3527
- durationMs: OptionalDurationMs
5088
+ chain_id: Schema.Number,
5089
+ token_address: Schema.String,
5090
+ incident_kind: Schema.String,
5091
+ anchor_block_number: Schema.Number
3528
5092
  });
3529
5093
  Schema.Struct({
3530
5094
  name: Schema.Literal("auth_otp_requested"),
@@ -3626,38 +5190,6 @@ Schema.Struct({
3626
5190
  name: Schema.Literal("faucet_failed"),
3627
5191
  props: FaucetFailedProps
3628
5192
  });
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
5193
  Schema.Struct({
3662
5194
  name: Schema.Literal("org_create_started"),
3663
5195
  props: OrgCreateStartedProps
@@ -3690,97 +5222,45 @@ Schema.Struct({
3690
5222
  name: Schema.Literal("org_invite_accepted"),
3691
5223
  props: OrgInviteAcceptedProps
3692
5224
  });
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
5225
  Schema.Struct({
3706
5226
  name: Schema.Literal("org_invite_expired"),
3707
5227
  props: OrgInviteExpiredProps
3708
5228
  });
3709
5229
  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
5230
+ name: Schema.Literal("payment_initiated"),
5231
+ props: PaymentInitiatedProps
3728
5232
  });
3729
5233
  Schema.Struct({
3730
5234
  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
5235
+ props: PaymentSettledL2Props
3744
5236
  });
3745
5237
  Schema.Struct({
3746
5238
  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
5239
+ props: PaymentFailedL2Props
3756
5240
  });
3757
5241
  Schema.Struct({
3758
- name: Schema.Literal("stream_cancelled"),
3759
- props: StreamTargetTelemetryProps
5242
+ name: Schema.Literal("deposit_initiated"),
5243
+ props: DepositInitiatedProps
3760
5244
  });
3761
5245
  Schema.Struct({
3762
- name: Schema.Literal("stream_completed"),
3763
- props: StreamTargetTelemetryProps
5246
+ name: Schema.Literal("deposit_settled"),
5247
+ props: DepositSettledProps
3764
5248
  });
3765
5249
  Schema.Struct({
3766
- name: Schema.Literal("stream_failed"),
3767
- props: StreamTargetTelemetryProps
5250
+ name: Schema.Literal("permission_mirror_verification"),
5251
+ props: PermissionMirrorVerificationProps
3768
5252
  });
3769
5253
  Schema.Struct({
3770
- name: Schema.Literal("withdrawal_requested"),
3771
- props: WithdrawalTargetTelemetryProps
5254
+ name: Schema.Literal("movement_scan_window"),
5255
+ props: MovementScanWindowProps
3772
5256
  });
3773
5257
  Schema.Struct({
3774
- name: Schema.Literal("withdrawal_submitted"),
3775
- props: WithdrawalTargetTelemetryProps
5258
+ name: Schema.Literal("movement_scan_checkpoint"),
5259
+ props: MovementScanCheckpointProps
3776
5260
  });
3777
5261
  Schema.Struct({
3778
- name: Schema.Literal("withdrawal_settled"),
3779
- props: WithdrawalTargetTelemetryProps
3780
- });
3781
- Schema.Struct({
3782
- name: Schema.Literal("withdrawal_failed"),
3783
- props: WithdrawalTargetTelemetryProps
5262
+ name: Schema.Literal("movement_scan_incident"),
5263
+ props: MovementScanIncidentProps
3784
5264
  });
3785
5265
  function redactTelemetryEvent(event, options = {}) {
3786
5266
  const props = redactTelemetryProps(event.name, event.props, options);
@@ -4167,7 +5647,8 @@ const accountLane = (input, config, session, send) => Effect.gen(function* () {
4167
5647
  if (Result.isFailure(existing)) return yield* failAt("provision", existing.failure);
4168
5648
  const provisioned = yield* Effect.result(existing.success === null ? call("smart-account.provision", input.ports.smartAccount.provision({
4169
5649
  authUserId: toAuthUserId(session.authUserId),
4170
- chainId: toChainId(input.chainId)
5650
+ chainId: toChainId(input.chainId),
5651
+ email: toEmail(session.email)
4171
5652
  })) : Effect.succeed(existing.success));
4172
5653
  if (Result.isFailure(provisioned)) return yield* failAt("provision", provisioned.failure);
4173
5654
  const account = provisioned.success;
@@ -4817,7 +6298,8 @@ function provisionSmartAccountProgram() {
4817
6298
  if (session === null) return yield* Effect.fail(Errors.notAuthenticated());
4818
6299
  const provisioned = yield* deps.smartAccountPort.provision({
4819
6300
  authUserId: session.authUserId,
4820
- chainId: deps.chainId
6301
+ chainId: deps.chainId,
6302
+ email: session.email
4821
6303
  }).pipe(Effect.mapError((failure) => failure.publicError));
4822
6304
  yield* Effect.promise(() => emitProvisioningTelemetry(deps.telemetry, provisioned));
4823
6305
  return provisioned;
@@ -4903,11 +6385,6 @@ function makeIdentityMethods(deps) {
4903
6385
  function moneyToWeiAmount(money) {
4904
6386
  return toWei(money);
4905
6387
  }
4906
- function transferDirection(from, to) {
4907
- if (from === "main") return "add";
4908
- if (to === "main") return "out";
4909
- return "between";
4910
- }
4911
6388
  /** Fire-and-forget emit through an optional port; never throws. */
4912
6389
  async function emitMoneyTelemetry(telemetry, event) {
4913
6390
  if (telemetry === void 0) return;
@@ -4941,52 +6418,18 @@ function emitAccountBalanceFailed(telemetry, reason) {
4941
6418
  props: { reason }
4942
6419
  });
4943
6420
  }
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) {
6421
+ function emitDepositInitiated(telemetry) {
4973
6422
  return emitMoneyTelemetry(telemetry, {
4974
- name: "subaccount_renamed",
4975
- props: { sub_account_id: subAccountId }
6423
+ name: "deposit_initiated",
6424
+ props: {}
4976
6425
  });
4977
6426
  }
4978
- function emitSubAccountDeleted(telemetry, subAccountId) {
6427
+ function emitPaymentInitiated(telemetry, input) {
4979
6428
  return emitMoneyTelemetry(telemetry, {
4980
- name: "subaccount_deleted",
4981
- props: { sub_account_id: subAccountId }
4982
- });
4983
- }
4984
- function emitSubAccountOpFailed(telemetry, op, reason) {
4985
- return emitMoneyTelemetry(telemetry, {
4986
- name: "subaccount_op_failed",
6429
+ name: "payment_initiated",
4987
6430
  props: {
4988
- op,
4989
- reason
6431
+ kind: input.kind,
6432
+ payment_id: input.paymentId
4990
6433
  }
4991
6434
  });
4992
6435
  }
@@ -5120,23 +6563,160 @@ const financialOpsContract = {
5120
6563
  addDestination: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].add),
5121
6564
  listDestinations: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].list),
5122
6565
  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
6566
  listPayments: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].listPayments),
5134
6567
  getPayment: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].getPayment),
6568
+ activityList: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].list),
6569
+ activityGet: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].get),
6570
+ activityAnnotate: makeFunctionReference(CAPXUL_FUNCTIONS["movement/activity"].annotate),
5135
6571
  verifyPaymentDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].verifyPaymentDocument),
5136
- renderStoredDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].renderStoredDocument),
5137
- getCommitmentRef: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].getCommitmentRef)
6572
+ renderStoredDocument: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].renderStoredDocument)
6573
+ };
6574
+ //#endregion
6575
+ //#region src/contract/money-execution.ts
6576
+ const moneyExecutionContract = {
6577
+ preparePermissionExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].preparePermissionExecution),
6578
+ preparePaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].preparePaymentExecution),
6579
+ prepareOrganizationPaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/paymentCommandActions"].prepareOrganizationPaymentExecution),
6580
+ preparePaymentLifecycleExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/paymentCommandActions"].preparePaymentLifecycleExecution),
6581
+ submitPaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].submitPaymentExecution),
6582
+ submitPermissionExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].submitPermissionExecution),
6583
+ submitPaymentCommandExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/paymentCommandActions"].submitPaymentCommandExecution)
5138
6584
  };
5139
6585
  //#endregion
6586
+ //#region src/surface/payment-execution.ts
6587
+ function mismatch(field, message) {
6588
+ return {
6589
+ ok: false,
6590
+ error: Errors.invalidInput(field, message)
6591
+ };
6592
+ }
6593
+ function cancelled(operation) {
6594
+ return {
6595
+ ok: false,
6596
+ error: Errors.cancelled({ operation })
6597
+ };
6598
+ }
6599
+ function isAborted$2(signal) {
6600
+ return signal?.aborted === true;
6601
+ }
6602
+ async function signerCall(operation, run) {
6603
+ try {
6604
+ return {
6605
+ ok: true,
6606
+ value: await run()
6607
+ };
6608
+ } catch (cause) {
6609
+ return {
6610
+ ok: false,
6611
+ error: cause instanceof CapxulError ? cause : Errors.providerError("wallet-signer", operation, cause)
6612
+ };
6613
+ }
6614
+ }
6615
+ async function executePersonalPayment(deps, payment, signal, requestKey) {
6616
+ if (isAborted$2(signal)) return cancelled("payments.pay");
6617
+ if (deps.signer === void 0) return mismatch("signer", "payments.pay requires a configured CapxulSigner");
6618
+ const session = deps.actor.authSession();
6619
+ if (session === null) return {
6620
+ ok: false,
6621
+ error: Errors.notAuthenticated()
6622
+ };
6623
+ const signerAddress = await signerCall("getAddress", () => deps.signer.getAddress());
6624
+ if (!signerAddress.ok) return signerAddress;
6625
+ const expectedSafe = deriveCapxulSafeAddress({ email: session.email });
6626
+ const resolvedRequestKey = requestKey ?? `pay_${crypto.randomUUID()}`;
6627
+ const prepared = await runIfActive(signal, "payments.prepareExecution", () => deps.convexCall.action(deps.functions.preparePaymentExecution, { input: {
6628
+ requestKey: resolvedRequestKey,
6629
+ signerAddress: signerAddress.value,
6630
+ payment
6631
+ } }));
6632
+ if (!prepared.ok) return prepared;
6633
+ if (prepared.value.requestKey !== resolvedRequestKey || JSON.stringify(prepared.value.payment) !== JSON.stringify(payment)) return mismatch("payment", "prepared Payment execution uses another request");
6634
+ if (prepared.value.chainId !== deps.chainId) return mismatch("chainId", "prepared Payment execution uses another chain");
6635
+ if (prepared.value.signerAddress.toLowerCase() !== signerAddress.value.toLowerCase()) return mismatch("signerAddress", "prepared Payment execution uses another signer");
6636
+ if (prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return mismatch("userOpSenderSafe", "prepared Payment execution uses another Account Safe");
6637
+ if (prepared.value.emitPaymentInitiated) await emitPaymentInitiated(deps.telemetry, {
6638
+ kind: prepared.value.purposeKind,
6639
+ paymentId: prepared.value.paymentId
6640
+ });
6641
+ if (isAborted$2(signal)) return cancelled("payments.pay");
6642
+ const signature = await signerCall("signUserOpHash", () => deps.signer.signUserOpHash(prepared.value.digest));
6643
+ if (!signature.ok) return signature;
6644
+ if (isAborted$2(signal)) return cancelled("payments.pay");
6645
+ return runIfActive(void 0, "payments.submitExecution", () => deps.convexCall.action(deps.functions.submitPaymentExecution, { input: {
6646
+ executionId: prepared.value.executionId,
6647
+ signature: signature.value
6648
+ } }));
6649
+ }
6650
+ //#endregion
6651
+ //#region src/surface/payment-command-execution.ts
6652
+ function isAborted$1(signal) {
6653
+ return signal?.aborted === true;
6654
+ }
6655
+ function signerFailure(operation, cause) {
6656
+ return {
6657
+ ok: false,
6658
+ error: cause instanceof CapxulError ? cause : Errors.providerError("wallet-signer", operation, cause)
6659
+ };
6660
+ }
6661
+ async function executePrepared(deps, prepare, expectedRequest, signal) {
6662
+ if (isAborted$1(signal)) return {
6663
+ ok: false,
6664
+ error: Errors.cancelled({ operation: "payments" })
6665
+ };
6666
+ const session = deps.actor.authSession();
6667
+ if (session === null) return {
6668
+ ok: false,
6669
+ error: Errors.notAuthenticated()
6670
+ };
6671
+ let signerAddress;
6672
+ try {
6673
+ signerAddress = await deps.signer.getAddress();
6674
+ } catch (cause) {
6675
+ return signerFailure("getAddress", cause);
6676
+ }
6677
+ const prepared = await prepare(signerAddress);
6678
+ if (!prepared.ok) return prepared;
6679
+ if (JSON.stringify(prepared.value.request) !== JSON.stringify(expectedRequest)) return {
6680
+ ok: false,
6681
+ error: Errors.invalidInput("payment", "prepared command mismatch")
6682
+ };
6683
+ const expectedSafe = deriveCapxulSafeAddress({ email: session.email });
6684
+ if (prepared.value.chainId !== deps.chainId || prepared.value.signerAddress.toLowerCase() !== signerAddress.toLowerCase() || prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return {
6685
+ ok: false,
6686
+ error: Errors.invalidInput("payment", "prepared authority mismatch")
6687
+ };
6688
+ if (isAborted$1(signal)) return {
6689
+ ok: false,
6690
+ error: Errors.cancelled({ operation: "payments" })
6691
+ };
6692
+ let signature;
6693
+ try {
6694
+ signature = await deps.signer.signUserOpHash(prepared.value.digest);
6695
+ } catch (cause) {
6696
+ return signerFailure("signUserOpHash", cause);
6697
+ }
6698
+ if (isAborted$1(signal)) return {
6699
+ ok: false,
6700
+ error: Errors.cancelled({ operation: "payments" })
6701
+ };
6702
+ return runIfActive(void 0, "payments.submitCommandExecution", () => deps.convexCall.action(deps.functions.submitPaymentCommandExecution, { input: {
6703
+ executionId: prepared.value.executionId,
6704
+ signature
6705
+ } }));
6706
+ }
6707
+ function executePaymentLifecycle(deps, intent, signal) {
6708
+ return executePrepared(deps, (signerAddress) => runIfActive(signal, "payments.prepareLifecycleExecution", () => deps.convexCall.action(deps.functions.preparePaymentLifecycleExecution, { input: {
6709
+ signerAddress,
6710
+ intent
6711
+ } })), intent, signal);
6712
+ }
6713
+ function executeOrganizationPayment(deps, input, signal) {
6714
+ return executePrepared(deps, (signerAddress) => runIfActive(signal, "organizationPayments.prepareExecution", () => deps.convexCall.action(deps.functions.prepareOrganizationPaymentExecution, { input: {
6715
+ ...input,
6716
+ signerAddress
6717
+ } })), input, signal);
6718
+ }
6719
+ //#endregion
5140
6720
  //#region src/surface/money.ts
5141
6721
  function actorReferenceToBackend(actor) {
5142
6722
  if (actor === void 0) return void 0;
@@ -5150,12 +6730,74 @@ function actorReferenceToBackend(actor) {
5150
6730
  case "org": return actor;
5151
6731
  }
5152
6732
  }
6733
+ function paymentExecutionIntent(input) {
6734
+ if (actorReferenceToBackend(input.actor)?.kind === "org") return {
6735
+ ok: false,
6736
+ error: Errors.notImplemented("payments", "pay.organizationActor")
6737
+ };
6738
+ const to = normalizeTargetForBackend(input.to, "to");
6739
+ if (!to.ok) return to;
6740
+ return {
6741
+ ok: true,
6742
+ value: {
6743
+ to: to.value,
6744
+ amount: input.amount,
6745
+ ...input.paymentType === void 0 ? {} : { paymentType: input.paymentType },
6746
+ ...input.document === void 0 ? {} : { document: input.document },
6747
+ ...input.timing === void 0 ? {} : { timing: input.timing },
6748
+ ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
6749
+ }
6750
+ };
6751
+ }
5153
6752
  function makeFinancialOpsMethods(deps) {
5154
6753
  const fns = deps.functions ?? financialOpsContract;
6754
+ const executionFns = deps.moneyExecutionFunctions ?? moneyExecutionContract;
6755
+ const pay = async (input, options) => {
6756
+ if (options?.signal?.aborted === true) return {
6757
+ ok: false,
6758
+ error: Errors.cancelled({ operation: "payments.pay" })
6759
+ };
6760
+ const payment = paymentExecutionIntent(input);
6761
+ if (!payment.ok) return payment;
6762
+ if (deps.actor === void 0 || deps.chainId === void 0) return {
6763
+ ok: false,
6764
+ error: Errors.notImplemented("payments", "executionComposition")
6765
+ };
6766
+ return mapOk(await executePersonalPayment({
6767
+ actor: deps.actor,
6768
+ chainId: deps.chainId,
6769
+ convexCall: deps.convexCall,
6770
+ functions: executionFns,
6771
+ ...deps.signer === void 0 ? {} : { signer: deps.signer },
6772
+ ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
6773
+ }, payment.value, options?.signal, input.requestKey), (submitted) => normalizePaymentTiming(submitted.payment));
6774
+ };
6775
+ const lifecycleDependencies = () => deps.actor === void 0 || deps.chainId === void 0 || deps.signer === void 0 ? {
6776
+ ok: false,
6777
+ error: Errors.notImplemented("payments", "executionComposition")
6778
+ } : {
6779
+ ok: true,
6780
+ value: {
6781
+ actor: deps.actor,
6782
+ chainId: deps.chainId,
6783
+ convexCall: deps.convexCall,
6784
+ functions: executionFns,
6785
+ signer: deps.signer
6786
+ }
6787
+ };
6788
+ const runLifecycle = async (intent, signal) => {
6789
+ const execution = lifecycleDependencies();
6790
+ if (!execution.ok) return execution;
6791
+ return mapOk(await executePaymentLifecycle(execution.value, intent, signal), (submitted) => {
6792
+ const payment = submitted.payments[0];
6793
+ if (payment === void 0 || submitted.payments.length !== 1) throw Errors.unknown();
6794
+ return normalizePaymentTiming(payment);
6795
+ });
6796
+ };
5155
6797
  return {
5156
6798
  me: {
5157
6799
  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, {}))
6800
+ depositInstructions: (options) => runIfActive(options?.signal, "me.depositInstructions", () => deps.convexCall.query(fns.depositInstructions, {}).pipe(Effect.tap(() => Effect.promise(() => emitDepositInitiated(deps.telemetry)))))
5159
6801
  },
5160
6802
  handles: { resolve: (handle, options) => runIfActive(options?.signal, "handles.resolve", () => deps.convexCall.query(fns.resolveHandle, { handle })) },
5161
6803
  payees: {
@@ -5169,8 +6811,8 @@ function makeFinancialOpsMethods(deps) {
5169
6811
  },
5170
6812
  targets: { resolve: async (reference, options) => {
5171
6813
  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));
6814
+ case "handle": return mapOk(await runIfActive(options?.signal, "targets.resolve.handle", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle })), (target) => resolvedTargetFromResolution(reference, target));
6815
+ case "email": return mapOk(await runIfActive(options?.signal, "targets.resolve.email", () => deps.convexCall.query(fns.resolvePayee, { recipient: reference.email })), (target) => resolvedTargetFromResolution(reference, target));
5174
6816
  case "organization": {
5175
6817
  const resolved = await runIfActive(options?.signal, "targets.resolve.organization", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle }));
5176
6818
  if (!resolved.ok) return {
@@ -5220,7 +6862,7 @@ function makeFinancialOpsMethods(deps) {
5220
6862
  error: Errors.invalidInput("target", DESTINATION_SCOPE_MESSAGE)
5221
6863
  };
5222
6864
  const backendActor = actorReferenceToBackend(input.actor);
5223
- return mapOk$1(await runIfActive(options?.signal, "destinations.add", () => deps.convexCall.mutation(fns.addDestination, {
6865
+ return mapOk(await runIfActive(options?.signal, "destinations.add", () => deps.convexCall.mutation(fns.addDestination, {
5224
6866
  ...backendActor === void 0 ? {} : { actor: backendActor },
5225
6867
  ...isSelfTarget(scopeValue) ? { self: true } : { ref: scopeValue },
5226
6868
  kind: destinationKindToBackend(input.kind),
@@ -5235,129 +6877,61 @@ function makeFinancialOpsMethods(deps) {
5235
6877
  error: scope.error
5236
6878
  };
5237
6879
  const scopeValue = scope.value;
5238
- return mapOk$1(await runIfActive(options?.signal, "destinations.list", () => deps.convexCall.query(fns.listDestinations, {
6880
+ return mapOk(await runIfActive(options?.signal, "destinations.list", () => deps.convexCall.query(fns.listDestinations, {
5239
6881
  ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
5240
6882
  ...scopeValue !== void 0 && isSelfTarget(scopeValue) ? { self: true } : {},
5241
6883
  ...scopeValue !== void 0 && !isSelfTarget(scopeValue) ? { ref: scopeValue } : {}
5242
- })), (destinations) => destinations.map(destinationFromBackend).filter((destination) => input.kind === void 0 || destination.kind === input.kind));
5243
- },
5244
- remove: (input, options) => runIfActive(options?.signal, "destinations.remove", () => deps.convexCall.mutation(fns.removeDestination, {
5245
- ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
5246
- destinationId: input.destinationId
5247
- }))
5248
- },
5249
- 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, {
5298
- 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, {
6884
+ })), (destinations) => destinations.map(destinationFromBackend).filter((destination) => input.kind === void 0 || destination.kind === input.kind));
6885
+ },
6886
+ remove: (input, options) => runIfActive(options?.signal, "destinations.remove", () => deps.convexCall.mutation(fns.removeDestination, {
6887
+ ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
6888
+ destinationId: input.destinationId
6889
+ }))
6890
+ },
6891
+ payments: {
6892
+ pay,
6893
+ createCommitment: (input, options) => pay(input, options),
6894
+ claim: (paymentId, options) => runLifecycle({
6895
+ kind: "claim",
6896
+ paymentId
6897
+ }, options?.signal),
6898
+ list: async (options) => mapOk(await runIfActive(options?.signal, "payments.list", () => deps.convexCall.query(fns.listPayments, {})), (payments) => payments.map(normalizePaymentTiming)),
6899
+ get: async (paymentId, options) => mapOk(await runIfActive(options?.signal, "payments.get", () => deps.convexCall.query(fns.getPayment, { paymentId })), (payment) => payment === null ? null : normalizePaymentTiming(payment)),
6900
+ cancel: (paymentId, options) => runLifecycle({
6901
+ kind: "cancel",
6902
+ paymentId
6903
+ }, options?.signal),
6904
+ redirect: async (input, options) => {
6905
+ const recipient = normalizeTargetForBackend(input.to, "to");
6906
+ if (!recipient.ok) return recipient;
6907
+ return runLifecycle({
6908
+ kind: "redirect",
5329
6909
  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 }))
6910
+ recipient: recipient.value
6911
+ }, options?.signal);
5349
6912
  }
5350
6913
  },
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
- } },
6914
+ activity: {
6915
+ list: (params, options) => runIfActive(options?.signal, "activity.list", () => deps.convexCall.query(fns.activityList, { input: {
6916
+ ...params?.actor?.kind === "organization" ? { actor: {
6917
+ kind: "organization",
6918
+ orgId: params.actor.organizationId
6919
+ } } : {},
6920
+ ...params?.cursor === void 0 ? {} : { cursor: params.cursor },
6921
+ ...params?.limit === void 0 ? {} : { limit: params.limit }
6922
+ } })),
6923
+ get: (reference, options) => runIfActive(options?.signal, "activity.get", () => deps.convexCall.query(fns.activityGet, { input: reference })),
6924
+ annotate: (input, options) => runIfActive(options?.signal, "activity.annotate", () => deps.convexCall.mutation(fns.activityAnnotate, { input: {
6925
+ ...input.actor?.kind === "organization" ? { actor: {
6926
+ kind: "organization",
6927
+ orgId: input.actor.organizationId
6928
+ } } : {},
6929
+ movementId: input.movementId,
6930
+ ...input.counterpartyLabel === void 0 ? {} : { counterpartyLabel: input.counterpartyLabel },
6931
+ ...input.accountingCategory === void 0 ? {} : { accountingCategory: input.accountingCategory },
6932
+ ...input.memo === void 0 ? {} : { memo: input.memo }
6933
+ } }))
6934
+ },
5361
6935
  offramp: {
5362
6936
  quote: (input, options) => {
5363
6937
  if (options?.signal?.aborted) return Promise.resolve({
@@ -5386,18 +6960,6 @@ function makeFinancialOpsMethods(deps) {
5386
6960
  }
5387
6961
  };
5388
6962
  }
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
6963
  function nonEmptyRefValue(value, field) {
5402
6964
  const trimmed = value.trim();
5403
6965
  if (trimmed.length === 0) throw Errors.invalidInput(field, "Ref value must be non-empty");
@@ -5645,14 +7207,14 @@ function normalizeRefForBackend(ref, field) {
5645
7207
  };
5646
7208
  }
5647
7209
  }
5648
- function normalizePaymentTiming$1(payment) {
7210
+ function normalizePaymentTiming(payment) {
5649
7211
  const { release: _release, ...rest } = payment;
5650
7212
  return {
5651
7213
  ...rest,
5652
7214
  timing: payment.timing ?? payment.release ?? { kind: "instant" }
5653
7215
  };
5654
7216
  }
5655
- function mapOk$1(result, f) {
7217
+ function mapOk(result, f) {
5656
7218
  if (!result.ok) return result;
5657
7219
  try {
5658
7220
  return {
@@ -5725,120 +7287,157 @@ function makeSystemMethods(deps) {
5725
7287
  return { health: (nonce, options) => runIfActive(options?.signal, "system.health", () => deps.convexCall.query(healthQuery, { nonce })) };
5726
7288
  }
5727
7289
  //#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
- });
7290
+ //#region src/contract/permission.ts
7291
+ const permissionContract = { read: makeFunctionReference(CAPXUL_FUNCTIONS["permission/queries"].read) };
7292
+ //#endregion
7293
+ //#region src/surface/permissions.ts
7294
+ function isAborted(signal) {
7295
+ return signal?.aborted === true;
5753
7296
  }
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
- });
7297
+ function fail$1(cause, operation) {
7298
+ return {
7299
+ ok: false,
7300
+ error: cause instanceof CapxulError ? cause : Errors.providerError("wallet-signer", operation, cause)
7301
+ };
5764
7302
  }
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
- });
7303
+ async function execute(deps, orgId, command, signal) {
7304
+ if (isAborted(signal)) return {
7305
+ ok: false,
7306
+ error: Errors.cancelled({ operation: "permissions" })
7307
+ };
7308
+ if (deps.actor === void 0 || deps.chainId === void 0 || deps.signer === void 0) return {
7309
+ ok: false,
7310
+ error: Errors.notImplemented("permissions", "executionComposition")
7311
+ };
7312
+ const session = deps.actor.authSession();
7313
+ if (session === null) return {
7314
+ ok: false,
7315
+ error: Errors.notAuthenticated()
7316
+ };
7317
+ let signerAddress;
7318
+ try {
7319
+ signerAddress = await deps.signer.getAddress();
7320
+ } catch (cause) {
7321
+ return fail$1(cause, "getAddress");
7322
+ }
7323
+ const executionFns = deps.executionFunctions ?? moneyExecutionContract;
7324
+ const prepared = await runIfActive(signal, "permissions.prepareExecution", () => deps.convexCall.action(executionFns.preparePermissionExecution, { input: {
7325
+ orgId,
7326
+ signerAddress,
7327
+ command
7328
+ } }));
7329
+ if (!prepared.ok) return prepared;
7330
+ const expectedSafe = deriveCapxulSafeAddress({ email: session.email });
7331
+ 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 {
7332
+ ok: false,
7333
+ error: Errors.invalidInput("permission", "prepared authority mismatch")
7334
+ };
7335
+ if (isAborted(signal)) return {
7336
+ ok: false,
7337
+ error: Errors.cancelled({ operation: "permissions" })
7338
+ };
7339
+ let signature;
7340
+ try {
7341
+ signature = await deps.signer.signUserOpHash(prepared.value.digest);
7342
+ } catch (cause) {
7343
+ return fail$1(cause, "signUserOpHash");
7344
+ }
7345
+ if (isAborted(signal)) return {
7346
+ ok: false,
7347
+ error: Errors.cancelled({ operation: "permissions" })
7348
+ };
7349
+ return runIfActive(void 0, "permissions.submitExecution", () => deps.convexCall.action(executionFns.submitPermissionExecution, { input: {
7350
+ executionId: prepared.value.executionId,
7351
+ signature
7352
+ } }));
5771
7353
  }
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
- });
7354
+ function makePermissionMethods(deps, orgId) {
7355
+ const reads = deps.permissionFunctions ?? permissionContract;
7356
+ return {
7357
+ create: (input, options) => execute(deps, orgId, {
7358
+ operation: "create",
7359
+ ...input
7360
+ }, options?.signal),
7361
+ change: (input, options) => execute(deps, orgId, {
7362
+ operation: "change",
7363
+ ...input
7364
+ }, options?.signal),
7365
+ assign: (input, options) => execute(deps, orgId, {
7366
+ operation: "assign",
7367
+ ...input
7368
+ }, options?.signal),
7369
+ revoke: (input, options) => execute(deps, orgId, {
7370
+ operation: "revoke",
7371
+ ...input
7372
+ }, options?.signal),
7373
+ replace: (input, options) => execute(deps, orgId, {
7374
+ operation: "replace",
7375
+ ...input
7376
+ }, options?.signal),
7377
+ list: (options) => runIfActive(options?.signal, "permissions.list", () => deps.convexCall.query(reads.read, { orgId })),
7378
+ get: async (permissionId, options) => {
7379
+ const listed = await runIfActive(options?.signal, "permissions.get", () => deps.convexCall.query(reads.read, { orgId }));
7380
+ if (!listed.ok) return listed;
7381
+ return {
7382
+ ok: true,
7383
+ value: listed.value.permissions.find((row) => row.permissionId === permissionId) ?? null
7384
+ };
7385
+ }
7386
+ };
5782
7387
  }
5783
7388
  //#endregion
5784
- //#region src/surface/sub-accounts.ts
5785
- function makeSubAccountsMethods(deps) {
5786
- const layer = subAccountsDepsLayer(deps);
7389
+ //#region src/surface/organization-payments.ts
7390
+ function executionDependencies(input) {
7391
+ return input.actor === void 0 || input.chainId === void 0 || input.signer === void 0 ? null : {
7392
+ actor: input.actor,
7393
+ chainId: input.chainId,
7394
+ convexCall: input.convexCall,
7395
+ functions: moneyExecutionContract,
7396
+ signer: input.signer
7397
+ };
7398
+ }
7399
+ function makeOrganizationPaymentsMethods(deps, orgId) {
7400
+ const execute = async (input, signal) => {
7401
+ const execution = executionDependencies(deps);
7402
+ if (execution === null) return {
7403
+ ok: false,
7404
+ error: Errors.notImplemented("organizationPayments", "executionComposition")
7405
+ };
7406
+ const result = await executeOrganizationPayment(execution, {
7407
+ orgId,
7408
+ permissionId: input.permissionId,
7409
+ requestKey: input.requestKey,
7410
+ items: input.items,
7411
+ ...input.lineage === void 0 ? {} : { lineage: input.lineage }
7412
+ }, signal);
7413
+ return result.ok ? {
7414
+ ok: true,
7415
+ value: result.value.payments.map((payment) => normalizePaymentTiming(payment))
7416
+ } : result;
7417
+ };
5787
7418
  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 {
7419
+ pay: async (input, options) => {
7420
+ const { permissionId, requestKey, lineage, ...item } = input;
7421
+ const result = await execute({
7422
+ permissionId,
7423
+ requestKey,
7424
+ items: [item],
7425
+ ...lineage === void 0 ? {} : { lineage }
7426
+ }, options?.signal);
7427
+ if (!result.ok) return result;
7428
+ const payment = result.value[0];
7429
+ return payment === void 0 ? {
5818
7430
  ok: false,
5819
- error: Errors.cancelled({ operation: "subAccounts.delete" })
7431
+ error: Errors.unknown()
7432
+ } : {
7433
+ ok: true,
7434
+ value: payment
5820
7435
  };
5821
- return toCapxulResult(deleteSubAccountProgram(subAccountId), layer);
5822
7436
  },
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
- }
7437
+ payBatch: (input, options) => execute(input, options?.signal)
5830
7438
  };
5831
7439
  }
5832
7440
  //#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
7441
  //#region src/surface/_shared/org-telemetry.ts
5843
7442
  /** Extract the domain from an email for telemetry (never the local part / PII). */
5844
7443
  function emailDomain$1(email) {
@@ -5934,59 +7533,11 @@ function isOrgTelemetryDebugEnabled() {
5934
7533
  return globalThis.process?.env?.CAPXUL_DEBUG_TELEMETRY === "1";
5935
7534
  }
5936
7535
  //#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
7536
  //#region src/surface/org-deps.ts
5980
7537
  var OrgDepsTag = class extends Context.Service()("@capxul/sdk/OrgDeps") {};
5981
7538
  function orgDepsLayer(deps) {
5982
7539
  return Layer.succeed(OrgDepsTag, deps);
5983
7540
  }
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
7541
  /** Zero `Money` in the USDX-backed display currency (a fresh Org's treasury). */
5991
7542
  function zeroMoney() {
5992
7543
  return fromWei("0", 6, "USD");
@@ -6043,14 +7594,8 @@ function recipientsFromConfig(toRecipients) {
6043
7594
  if (toRecipients === void 0 || toRecipients === "anyone") return toRecipients;
6044
7595
  return toRecipients.map((recipient) => toAddress(recipient));
6045
7596
  }
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
7597
  function roleDefinitionFromConfig(definition) {
6052
7598
  const toRecipients = recipientsFromConfig(definition.spend?.toRecipients);
6053
- const subAccounts = subAccountsFromConfig(definition.subAccounts);
6054
7599
  return {
6055
7600
  label: definition.label,
6056
7601
  ...definition.spend === void 0 ? {} : { spend: {
@@ -6058,7 +7603,6 @@ function roleDefinitionFromConfig(definition) {
6058
7603
  ...definition.spend.perDay === void 0 ? {} : { perDay: moneyFromConfig(definition.spend.perDay) },
6059
7604
  ...toRecipients === void 0 ? {} : { toRecipients }
6060
7605
  } },
6061
- ...subAccounts === void 0 ? {} : { subAccounts },
6062
7606
  ...definition.canManageMembers === void 0 ? {} : { canManageMembers: definition.canManageMembers },
6063
7607
  ...definition.canManageRoles === void 0 ? {} : { canManageRoles: definition.canManageRoles }
6064
7608
  };
@@ -6084,36 +7628,6 @@ function hermeticMember(input) {
6084
7628
  revokeTxHash: input.revokeTxHash ?? null
6085
7629
  };
6086
7630
  }
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
7631
  function createOrgProgram(input) {
6118
7632
  return Effect.gen(function* () {
6119
7633
  const deps = yield* OrgDepsTag;
@@ -6205,14 +7719,6 @@ function listRolesProgram(orgId) {
6205
7719
  return startupRoleViews(orgId);
6206
7720
  });
6207
7721
  }
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
7722
  function listMembersProgram(orgId) {
6217
7723
  return Effect.gen(function* () {
6218
7724
  const deps = yield* OrgDepsTag;
@@ -6248,188 +7754,6 @@ function detectAndAcceptPendingInvitationsProgram() {
6248
7754
  return { matched: [] };
6249
7755
  });
6250
7756
  }
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
7757
  function listOrgsProgram() {
6434
7758
  return Effect.gen(function* () {
6435
7759
  const deps = yield* OrgDepsTag;
@@ -6516,18 +7840,13 @@ function isRetryableOrganizationSetupFailure(error) {
6516
7840
  //#endregion
6517
7841
  //#region src/surface/org.ts
6518
7842
  /**
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.
7843
+ * Org method surface (canon §C2/§C3, D13). The entity-scoped bundle is
7844
+ * constructed for each `org(orgId)` call. It has no shared mutable active-Org
7845
+ * state. The closed-over `orgId` is its only entity reference.
6525
7846
  */
6526
7847
  function makeOrgMethods(deps) {
6527
7848
  const layer = orgDepsLayer({
6528
7849
  ...deps.orgPort === void 0 ? {} : { orgPort: deps.orgPort },
6529
- ...deps.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: deps.orgRolesDeploymentPort },
6530
- ...deps.orgSpendPort === void 0 ? {} : { orgSpendPort: deps.orgSpendPort },
6531
7850
  ...deps.chainId === void 0 ? {} : { chainId: deps.chainId },
6532
7851
  ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
6533
7852
  });
@@ -6658,13 +7977,6 @@ function makeOrgMethods(deps) {
6658
7977
  });
6659
7978
  return toCapxulResult(listRolesProgram(orgId), layer);
6660
7979
  },
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
7980
  invite(_input, _options) {
6669
7981
  if (_options?.signal?.aborted) return Promise.resolve({
6670
7982
  ok: false,
@@ -6672,34 +7984,6 @@ function makeOrgMethods(deps) {
6672
7984
  });
6673
7985
  return toCapxulResult(inviteMemberProgram(orgId, _input), layer);
6674
7986
  },
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
7987
  auditLog(_options) {
6704
7988
  if (_options?.signal?.aborted) return Promise.resolve({
6705
7989
  ok: false,
@@ -6710,107 +7994,58 @@ function makeOrgMethods(deps) {
6710
7994
  error: Errors.notImplemented("organizationAuditLog", "list")
6711
7995
  });
6712
7996
  },
6713
- payroll: convexCall === void 0 ? makeNotImplementedPayrollMethods() : makePayrollMethods({
6714
- orgId: String(orgId),
6715
- convexCall
6716
- })
7997
+ permissions: convexCall === void 0 ? makeNotImplementedPermissionMethods() : makePermissionMethods({
7998
+ convexCall,
7999
+ ...deps.actor === void 0 ? {} : { actor: deps.actor },
8000
+ ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
8001
+ ...deps.signer === void 0 ? {} : { signer: deps.signer }
8002
+ }, String(orgId)),
8003
+ payments: convexCall === void 0 ? makeNotImplementedOrganizationPaymentsMethods() : makeOrganizationPaymentsMethods({
8004
+ convexCall,
8005
+ ...deps.actor === void 0 ? {} : { actor: deps.actor },
8006
+ ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
8007
+ ...deps.signer === void 0 ? {} : { signer: deps.signer }
8008
+ }, String(orgId))
6717
8009
  };
6718
8010
  }
6719
8011
  };
6720
8012
  }
6721
- function makePayrollMethods(deps) {
6722
- const fns = payrollContract;
6723
- 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))
6759
- };
6760
- }
6761
- function makeNotImplementedPayrollMethods() {
6762
- 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")
6770
- };
6771
- }
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;
8013
+ function makeNotImplementedPermissionMethods() {
6781
8014
  return {
6782
- ok: true,
6783
- value: f(result.value)
8015
+ create: permissionExecutionUnavailable,
8016
+ change: permissionExecutionUnavailable,
8017
+ assign: permissionExecutionUnavailable,
8018
+ revoke: permissionExecutionUnavailable,
8019
+ replace: permissionExecutionUnavailable,
8020
+ list: permissionExecutionUnavailable,
8021
+ get: permissionExecutionUnavailable
6784
8022
  };
6785
8023
  }
6786
- function mapPayrollRosterLine(line) {
8024
+ function makeNotImplementedOrganizationPaymentsMethods() {
6787
8025
  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
8026
+ pay: organizationPaymentExecutionUnavailable,
8027
+ payBatch: organizationPaymentExecutionUnavailable
6805
8028
  };
6806
- return { title: document.primaryType };
6807
8029
  }
6808
- function normalizePaymentTiming(payment) {
6809
- const { release: _release, ...rest } = payment;
6810
- return {
6811
- ...rest,
6812
- timing: payment.timing ?? payment.release ?? { kind: "instant" }
6813
- };
8030
+ const permissionExecutionUnavailable = () => Promise.resolve({
8031
+ ok: false,
8032
+ error: Errors.notImplemented("permissions", "executionComposition")
8033
+ });
8034
+ const organizationPaymentExecutionUnavailable = () => Promise.resolve({
8035
+ ok: false,
8036
+ error: Errors.notImplemented("organizationPayments", "executionComposition")
8037
+ });
8038
+ //#endregion
8039
+ //#region src/contract/holdings.ts
8040
+ const holdingsContract = { current: makeFunctionReference(CAPXUL_FUNCTIONS["holdings/actions"].current) };
8041
+ //#endregion
8042
+ //#region src/surface/holdings.ts
8043
+ function makeHoldingsMethods(deps) {
8044
+ const functions = deps.functions ?? holdingsContract;
8045
+ return { current: (input, options) => runIfActive(options?.signal, "holdings.current", () => deps.convexCall.action(functions.current, input?.actor?.kind === "organization" ? { actor: {
8046
+ kind: "organization",
8047
+ orgId: input.actor.organizationId
8048
+ } } : {})) };
6814
8049
  }
6815
8050
  //#endregion
6816
8051
  //#region src/surface/factory.ts
@@ -7213,7 +8448,13 @@ function assembleCapxulClient(input) {
7213
8448
  const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;
7214
8449
  let detectPendingOrgInvitations;
7215
8450
  let kickProvisioning;
7216
- const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });
8451
+ const financialOps = makeFinancialOpsMethods({
8452
+ actor,
8453
+ chainId: input.bootstrap.chainId,
8454
+ convexCall: input.ports.convexCall,
8455
+ ...input.signer === void 0 ? {} : { signer: input.signer },
8456
+ telemetry: input.ports.telemetry
8457
+ });
7217
8458
  const accountBundle = makeAccountMethods({
7218
8459
  actor,
7219
8460
  authCache,
@@ -7258,22 +8499,19 @@ function assembleCapxulClient(input) {
7258
8499
  });
7259
8500
  const system = makeSystemMethods({ convexCall: input.ports.convexCall });
7260
8501
  const media = makeMediaMethods({ convexCall: input.ports.convexCall });
8502
+ const holdings = makeHoldingsMethods({ convexCall: input.ports.convexCall });
7261
8503
  const accounts = makeAccountsMethods({
7262
8504
  accountReadPort: input.ports.accountRead,
7263
8505
  chainId: input.bootstrap.chainId,
7264
8506
  telemetry: input.ports.telemetry
7265
8507
  });
7266
- const subAccounts = makeSubAccountsMethods({
7267
- subAccountPort: input.ports.subAccount,
7268
- telemetry: input.ports.telemetry
7269
- });
7270
8508
  const orgMethods = makeOrgMethods({
8509
+ actor,
7271
8510
  chainId: input.bootstrap.chainId,
7272
8511
  telemetry: input.ports.telemetry,
7273
8512
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
7274
- ...input.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: input.orgRolesDeploymentPort },
7275
- ...input.orgSpendPort === void 0 ? {} : { orgSpendPort: input.orgSpendPort },
7276
8513
  convexCall: input.ports.convexCall,
8514
+ ...input.signer === void 0 ? {} : { signer: input.signer },
7277
8515
  ...input.organizationSetup === void 0 ? {} : { organizationSetup: input.organizationSetup }
7278
8516
  });
7279
8517
  if (selectedOrgPort !== void 0) detectPendingOrgInvitations = async () => {
@@ -7362,10 +8600,10 @@ function assembleCapxulClient(input) {
7362
8600
  destinations: financialOps.destinations,
7363
8601
  payments: financialOps.payments,
7364
8602
  activity: financialOps.activity,
8603
+ holdings,
7365
8604
  offramp: financialOps.offramp,
7366
8605
  paymentDocuments: financialOps.paymentDocuments,
7367
8606
  media,
7368
- subAccounts,
7369
8607
  createOrg: orgMethods.createOrg,
7370
8608
  orgs: orgMethods.orgs,
7371
8609
  org: orgMethods.org,
@@ -7394,6 +8632,4 @@ function withHostObservation(actor, snapshot) {
7394
8632
  };
7395
8633
  }
7396
8634
  //#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
8635
+ export { encodeObservationContextHeader as A, captureExceptionSync as B, BootstrapPortTag as C, version as D, AuthClientPortTag as E, isSettingUpLifecycle as F, destination as G, normalizeBindingEmail as H, formatTraceparent as I, copyInvocationObservation as L, CAPXUL_FUNCTIONS as M, BootstrapEnvelope as N, fromWei as O, EngineeringTelemetryBootstrapPolicy as P, readInvocationObservation as R, ClockPortTag as S, authClientPortFromPromiseAdapter as T, BASE_SEPOLIA_CHAIN_ID as U, CAPXUL_PAYMENTS_V2_ADDRESS as V, deriveCapxulSafeAddress as W, IdentityPortTag as _, observeFailedResult as a, convexCallErrorFromCapxul as b, PostHogTelemetryLayer as c, SmartAccountPortTag as d, smartAccountErrorFromCapxul as f, wireChainId as g, toWei as h, observationContextProps as i, sanitizeObservationContext as j, OBSERVATION_CONTEXT_HEADER as k, TelemetryPortTag as l, accountReadErrorFromCapxul as m, postHogProductTelemetry as n, postHogFailureObservation as o, AccountReadPortTag as p, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT as r, detectAuthCacheAdapter as s, assembleCapxulClient as t, redactTelemetryEvent as u, identityErrorFromCapxul as v, bootstrapErrorFromCapxul as w, ClockError as x, ConvexCallPortTag as y, captureException as z };