@playmos/sdk 0.3.11 → 0.3.13

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.
package/dist/index.cjs CHANGED
@@ -802,6 +802,182 @@ async function assertEnoughGas(provider, from, minWei) {
802
802
  });
803
803
  }
804
804
  }
805
+ function seriesToBytes32(series) {
806
+ const s = series.trim();
807
+ if (/^0x[0-9a-fA-F]{64}$/.test(s)) return s.toLowerCase();
808
+ return viem.keccak256(viem.toHex(s));
809
+ }
810
+ var identityToBytes32 = seriesToBytes32;
811
+
812
+ // src/chain/epochPrizePoolAbi.ts
813
+ var epochPrizePoolViewAbi = [
814
+ {
815
+ type: "function",
816
+ name: "currentEpochId",
817
+ stateMutability: "view",
818
+ inputs: [{ name: "series", type: "bytes32" }],
819
+ outputs: [{ type: "uint256" }]
820
+ },
821
+ {
822
+ type: "function",
823
+ name: "epochIdAt",
824
+ stateMutability: "view",
825
+ inputs: [
826
+ { name: "series", type: "bytes32" },
827
+ { name: "timestamp", type: "uint256" }
828
+ ],
829
+ outputs: [{ type: "uint256" }]
830
+ },
831
+ {
832
+ type: "function",
833
+ name: "epochPool",
834
+ stateMutability: "view",
835
+ inputs: [
836
+ { name: "series", type: "bytes32" },
837
+ { name: "epochId", type: "uint256" }
838
+ ],
839
+ outputs: [{ type: "uint256" }]
840
+ },
841
+ {
842
+ type: "function",
843
+ name: "epochOutgoingSeed",
844
+ stateMutability: "view",
845
+ inputs: [
846
+ { name: "series", type: "bytes32" },
847
+ { name: "epochId", type: "uint256" }
848
+ ],
849
+ outputs: [{ type: "uint256" }]
850
+ },
851
+ {
852
+ type: "function",
853
+ name: "epochIncomingSeed",
854
+ stateMutability: "view",
855
+ inputs: [
856
+ { name: "series", type: "bytes32" },
857
+ { name: "epochId", type: "uint256" }
858
+ ],
859
+ outputs: [{ type: "uint256" }]
860
+ },
861
+ {
862
+ type: "function",
863
+ name: "epochEntryCount",
864
+ stateMutability: "view",
865
+ inputs: [
866
+ { name: "series", type: "bytes32" },
867
+ { name: "epochId", type: "uint256" }
868
+ ],
869
+ outputs: [{ type: "uint256" }]
870
+ },
871
+ {
872
+ type: "function",
873
+ name: "getSeries",
874
+ stateMutability: "view",
875
+ inputs: [{ name: "series", type: "bytes32" }],
876
+ outputs: [
877
+ { name: "created", type: "bool" },
878
+ { name: "genesis", type: "uint256" },
879
+ { name: "epochDuration", type: "uint256" },
880
+ { name: "entry", type: "uint256" },
881
+ { name: "feeBps", type: "uint16" },
882
+ { name: "poolBps", type: "uint16" },
883
+ { name: "seedBps", type: "uint16" }
884
+ ]
885
+ },
886
+ {
887
+ type: "function",
888
+ name: "getEpoch",
889
+ stateMutability: "view",
890
+ inputs: [
891
+ { name: "series", type: "bytes32" },
892
+ { name: "epochId", type: "uint256" }
893
+ ],
894
+ outputs: [
895
+ { name: "pool", type: "uint256" },
896
+ { name: "outgoingSeed", type: "uint256" },
897
+ { name: "incomingSeed", type: "uint256" },
898
+ { name: "entryCount_", type: "uint256" },
899
+ { name: "terminal", type: "uint8" }
900
+ ]
901
+ },
902
+ {
903
+ type: "function",
904
+ name: "entryCount",
905
+ stateMutability: "view",
906
+ inputs: [
907
+ { name: "series", type: "bytes32" },
908
+ { name: "epochId", type: "uint256" },
909
+ { name: "identity", type: "bytes32" }
910
+ ],
911
+ outputs: [{ type: "uint256" }]
912
+ },
913
+ {
914
+ type: "function",
915
+ name: "claimableRefund",
916
+ stateMutability: "view",
917
+ inputs: [
918
+ { name: "series", type: "bytes32" },
919
+ { name: "epochId", type: "uint256" },
920
+ { name: "payer", type: "address" }
921
+ ],
922
+ outputs: [{ type: "uint256" }]
923
+ },
924
+ {
925
+ type: "function",
926
+ name: "withdrawable",
927
+ stateMutability: "view",
928
+ inputs: [{ name: "account", type: "address" }],
929
+ outputs: [{ type: "uint256" }]
930
+ }
931
+ ];
932
+ var epochPrizePoolEnterAbi = [
933
+ {
934
+ type: "function",
935
+ name: "enter",
936
+ stateMutability: "nonpayable",
937
+ inputs: [
938
+ { name: "series", type: "bytes32" },
939
+ { name: "identity", type: "bytes32" }
940
+ ],
941
+ outputs: []
942
+ }
943
+ ];
944
+ var epochPrizePoolRefundAbi = [
945
+ {
946
+ type: "function",
947
+ name: "claimRefund",
948
+ stateMutability: "nonpayable",
949
+ inputs: [
950
+ { name: "series", type: "bytes32" },
951
+ { name: "epochId", type: "uint256" },
952
+ { name: "payer", type: "address" }
953
+ ],
954
+ outputs: [{ name: "amount", type: "uint256" }]
955
+ },
956
+ {
957
+ type: "function",
958
+ name: "withdraw",
959
+ stateMutability: "nonpayable",
960
+ inputs: [],
961
+ outputs: []
962
+ }
963
+ ];
964
+ var epochPrizePoolExecuteSettlementAbi = [
965
+ {
966
+ type: "function",
967
+ name: "executeSignedSettlement",
968
+ stateMutability: "nonpayable",
969
+ inputs: [
970
+ { name: "series", type: "bytes32" },
971
+ { name: "epochId", type: "uint256" },
972
+ { name: "winners", type: "address[]" },
973
+ { name: "amounts", type: "uint256[]" },
974
+ { name: "signature", type: "bytes" }
975
+ ],
976
+ outputs: []
977
+ }
978
+ ];
979
+
980
+ // src/chain/calls.ts
805
981
  var toBytes32 = (s) => viem.keccak256(viem.toBytes(s));
806
982
  function buildIapCalls(args) {
807
983
  const payData = viem.encodeFunctionData({
@@ -833,6 +1009,53 @@ function buildWithdrawCall(prizePool) {
833
1009
  });
834
1010
  return { to: prizePool, data };
835
1011
  }
1012
+ function buildEpochExecuteSettlementCall(args) {
1013
+ return {
1014
+ to: args.epochPrizePool,
1015
+ data: viem.encodeFunctionData({
1016
+ abi: epochPrizePoolExecuteSettlementAbi,
1017
+ functionName: "executeSignedSettlement",
1018
+ args: [
1019
+ seriesToBytes32(args.series),
1020
+ args.epochId,
1021
+ args.winners.map((w) => viem.getAddress(w.toLowerCase())),
1022
+ args.amounts,
1023
+ args.signature
1024
+ ]
1025
+ })
1026
+ };
1027
+ }
1028
+ function buildEpochEntryCalls(args) {
1029
+ const enterData = viem.encodeFunctionData({
1030
+ abi: epochPrizePoolEnterAbi,
1031
+ functionName: "enter",
1032
+ args: [seriesToBytes32(args.series), identityToBytes32(args.identity)]
1033
+ });
1034
+ return [
1035
+ { to: args.usdc, data: encodeApprove(args.epochPrizePool, args.entryMicro) },
1036
+ { to: args.epochPrizePool, data: enterData }
1037
+ ];
1038
+ }
1039
+ function buildEpochClaimRefundCall(args) {
1040
+ return {
1041
+ to: args.epochPrizePool,
1042
+ data: viem.encodeFunctionData({
1043
+ abi: epochPrizePoolRefundAbi,
1044
+ functionName: "claimRefund",
1045
+ args: [seriesToBytes32(args.series), args.epochId, args.payer]
1046
+ })
1047
+ };
1048
+ }
1049
+ function buildEpochWithdrawCall(epochPrizePool) {
1050
+ return {
1051
+ to: epochPrizePool,
1052
+ data: viem.encodeFunctionData({
1053
+ abi: epochPrizePoolRefundAbi,
1054
+ functionName: "withdraw",
1055
+ args: []
1056
+ })
1057
+ };
1058
+ }
836
1059
 
837
1060
  // src/mock.ts
838
1061
  var MOCK_TX = `0x${"0".repeat(56)}deadbeef`;
@@ -894,13 +1117,902 @@ function mockVerifyResult(payment) {
894
1117
  return { ...payment, mock: true };
895
1118
  }
896
1119
 
897
- // src/x402.ts
1120
+ // src/epochs.ts
1121
+ var PLAYMOS_FEE_SINK_DEFAULT = "0xd84c190085aa59c48a9b478ea333d50b8df4ad42";
1122
+ var RETIRED_PLAYMOS_FEE_SINK = "0x1b8031e20ed96131a849a52290b4d640f286998d";
1123
+ var EPOCH_POOL_CONSTRUCTOR_TYPES = [
1124
+ { type: "address" },
1125
+ { type: "address" },
1126
+ { type: "address" },
1127
+ { type: "address" },
1128
+ { type: "uint256" }
1129
+ ];
1130
+ function encodeEpochPoolConstructorArgs(args) {
1131
+ return viem.encodeAbiParameters(EPOCH_POOL_CONSTRUCTOR_TYPES, [
1132
+ args.token,
1133
+ args.admin,
1134
+ args.operator,
1135
+ args.feeSink,
1136
+ args.refundTimeout
1137
+ ]);
1138
+ }
1139
+ function derivedEpochId(genesis, epochDuration, at) {
1140
+ if (epochDuration === 0n) {
1141
+ throw new ConfigError("epochDuration must be > 0");
1142
+ }
1143
+ if (at < genesis) {
1144
+ throw new ConfigError("epoch has not started (at < genesis)");
1145
+ }
1146
+ return (at - genesis) / epochDuration;
1147
+ }
1148
+ function epochPayableMicro(incomingSeed, pool) {
1149
+ return incomingSeed + pool;
1150
+ }
1151
+ function mockPodiumPayable(winners) {
1152
+ if (winners.length === 0) return void 0;
1153
+ let total = 0n;
1154
+ for (const w of winners) {
1155
+ if (typeof w === "string") return void 0;
1156
+ if (w.amountMicro != null && w.amountMicro !== "") {
1157
+ try {
1158
+ total += BigInt(w.amountMicro);
1159
+ } catch {
1160
+ return void 0;
1161
+ }
1162
+ continue;
1163
+ }
1164
+ if (w.amount) {
1165
+ try {
1166
+ total += parseUsdToMicro(w.amount);
1167
+ } catch {
1168
+ return void 0;
1169
+ }
1170
+ continue;
1171
+ }
1172
+ return void 0;
1173
+ }
1174
+ return {
1175
+ payable: formatMicroToUsd(total),
1176
+ payableMicro: total.toString()
1177
+ };
1178
+ }
1179
+ function mockWinnerMicro(w) {
1180
+ if (typeof w === "string") return void 0;
1181
+ if (w.amountMicro != null && w.amountMicro !== "" && /^\d+$/.test(w.amountMicro)) {
1182
+ return BigInt(w.amountMicro);
1183
+ }
1184
+ if (w.amount) {
1185
+ try {
1186
+ return parseUsdToMicro(w.amount);
1187
+ } catch {
1188
+ return void 0;
1189
+ }
1190
+ }
1191
+ return void 0;
1192
+ }
1193
+ function mockWinnerAmount(w) {
1194
+ const micro = mockWinnerMicro(w);
1195
+ if (micro === void 0) return {};
1196
+ return { amount: formatMicroToUsd(micro), amountMicro: micro.toString() };
1197
+ }
1198
+ var TERMINALS = ["none", "settled", "refunded", "rolled"];
1199
+ function terminalFromChain(raw) {
1200
+ return TERMINALS[raw] ?? "none";
1201
+ }
1202
+ function requireSeries(series) {
1203
+ if (typeof series !== "string" || series.trim() === "") {
1204
+ throw new MissingFieldError("series");
1205
+ }
1206
+ return series.trim();
1207
+ }
1208
+ function requireIdentity(identity) {
1209
+ if (typeof identity !== "string" || identity.trim() === "") {
1210
+ throw new MissingFieldError("identity");
1211
+ }
1212
+ return identity.trim();
1213
+ }
1214
+ function assertPinParity(label, local, fromService) {
1215
+ if (!fromService) {
1216
+ throw new ConfigError(
1217
+ `epochs.enter: the service did not return ${label}Bytes32 \u2014 cannot prove the on-chain id matches before paying.`,
1218
+ { field: `${label}Bytes32` }
1219
+ );
1220
+ }
1221
+ if (local.toLowerCase() !== fromService.toLowerCase()) {
1222
+ throw new ConfigError(
1223
+ `epochs.enter: ${label} derives differently in the SDK and the service (sdk=${local}, service=${fromService}). Refusing to enter \u2014 a paid entry under a mismatched id is never scored. See sdk#633.`,
1224
+ { field: `${label}Bytes32` }
1225
+ );
1226
+ }
1227
+ }
1228
+ function epochPathId(epochId) {
1229
+ if (epochId === void 0 || epochId === null || epochId === "") return "current";
1230
+ const s = String(epochId).trim();
1231
+ if (s === "current") return "current";
1232
+ if (!/^\d+$/.test(s)) {
1233
+ throw new ConfigError(`epochId must be a non-negative integer, got: ${JSON.stringify(epochId)}`);
1234
+ }
1235
+ return s;
1236
+ }
1237
+ function qs(params) {
1238
+ const u = new URLSearchParams();
1239
+ for (const [k, v] of Object.entries(params)) {
1240
+ if (v) u.set(k, v);
1241
+ }
1242
+ const s = u.toString();
1243
+ return s ? `?${s}` : "";
1244
+ }
1245
+ function pictureFromMicros(args) {
1246
+ const payableMicro = epochPayableMicro(args.incomingSeedMicro, args.poolMicro);
1247
+ return {
1248
+ series: args.series,
1249
+ epochId: args.epochId,
1250
+ pool: formatMicroToUsd(args.poolMicro),
1251
+ incomingSeed: formatMicroToUsd(args.incomingSeedMicro),
1252
+ outgoingSeed: formatMicroToUsd(args.outgoingSeedMicro),
1253
+ payable: formatMicroToUsd(payableMicro),
1254
+ poolMicro: args.poolMicro.toString(),
1255
+ incomingSeedMicro: args.incomingSeedMicro.toString(),
1256
+ outgoingSeedMicro: args.outgoingSeedMicro.toString(),
1257
+ payableMicro: payableMicro.toString(),
1258
+ via: args.via,
1259
+ epochPrizePool: args.epochPrizePool,
1260
+ ...args.mock ? { mock: true } : {}
1261
+ };
1262
+ }
1263
+ function toBig(value, fallback) {
1264
+ if (value === void 0) return fallback;
1265
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return BigInt(Math.trunc(value));
1266
+ if (typeof value === "string" && /^\d+$/.test(value.trim())) return BigInt(value.trim());
1267
+ throw new ConfigError(`expected a non-negative integer, got: ${JSON.stringify(value)}`);
1268
+ }
898
1269
  var ADDRESS_RE2 = /^0x[0-9a-fA-F]{40}$/;
1270
+ function requireAddr(raw, field) {
1271
+ if (typeof raw !== "string" || !ADDRESS_RE2.test(raw.trim())) {
1272
+ throw new MissingFieldError(field);
1273
+ }
1274
+ return raw.trim().toLowerCase();
1275
+ }
1276
+ function requireAddrKeepCase(raw, field) {
1277
+ if (typeof raw !== "string" || !ADDRESS_RE2.test(raw.trim())) {
1278
+ throw new MissingFieldError(field);
1279
+ }
1280
+ return raw.trim();
1281
+ }
1282
+ function requireEpochPool(input, cfg) {
1283
+ const raw = input?.epochPrizePool ?? cfg.contracts?.epochPrizePool;
1284
+ if (!raw) {
1285
+ throw new ConfigError(
1286
+ "epochs refund rail needs contracts.epochPrizePool (or pass epochPrizePool) \u2014 this is EpochPrizePool, not PrizePool",
1287
+ { field: "epochPrizePool" }
1288
+ );
1289
+ }
1290
+ return requireAddr(raw, "epochPrizePool");
1291
+ }
1292
+ function requirePastEpochId(epochId) {
1293
+ const id = epochPathId(epochId);
1294
+ if (id === "current") {
1295
+ throw new ConfigError("epochs refund rail requires a past epochId \u2014 Current is still taking entries");
1296
+ }
1297
+ return id;
1298
+ }
1299
+ function walletStatus(status) {
1300
+ if (status === "CONFIRMED") return "confirmed";
1301
+ if (status === "FAILED") return "failed";
1302
+ return "pending";
1303
+ }
1304
+ function sameAddr(a, b) {
1305
+ return a.toLowerCase() === b.toLowerCase();
1306
+ }
1307
+ function prepareStudioPoolLocal(input, playmosFeeSink, token, playmosAddresses = []) {
1308
+ const studio = requireAddr(input.studioWallet, "studioWallet");
1309
+ const locked = PLAYMOS_FEE_SINK_DEFAULT;
1310
+ if (playmosFeeSink && !sameAddr(playmosFeeSink, locked)) {
1311
+ throw new ConfigError("feeSink must equal the Playmos Sepolia treasury; refused before broadcast");
1312
+ }
1313
+ const sink = locked;
1314
+ const forbidden = [sink, ...playmosAddresses.map((a) => a.toLowerCase())];
1315
+ if (forbidden.some((a) => sameAddr(a, studio))) {
1316
+ throw new ConfigError("studioWallet must not be a Playmos address (Playmos never holds studio keys)");
1317
+ }
1318
+ if (input.feeSink && !sameAddr(input.feeSink, sink)) {
1319
+ throw new ConfigError("feeSink must equal the Playmos Sepolia treasury; refused before broadcast");
1320
+ }
1321
+ if (input.admin && !sameAddr(input.admin, studio)) {
1322
+ throw new ConfigError("admin must be the studio wallet from block one");
1323
+ }
1324
+ if (input.operator && !sameAddr(input.operator, studio)) {
1325
+ throw new ConfigError("operator must be the studio wallet from block one");
1326
+ }
1327
+ if (input.admin && forbidden.some((a) => sameAddr(a, input.admin))) {
1328
+ throw new ConfigError("Playmos must not be ADMIN_ROLE");
1329
+ }
1330
+ if (input.operator && forbidden.some((a) => sameAddr(a, input.operator))) {
1331
+ throw new ConfigError("Playmos must not be OPERATOR_ROLE");
1332
+ }
1333
+ const refundTimeout = toBig(input.refundTimeout, 604800n);
1334
+ if (refundTimeout < 3600n || refundTimeout > 7776000n) {
1335
+ throw new ConfigError("refundTimeout must be between 3600 (1h) and 7776000 (90d) seconds");
1336
+ }
1337
+ return {
1338
+ token: token.toLowerCase(),
1339
+ admin: studio,
1340
+ operator: studio,
1341
+ feeSink: sink,
1342
+ refundTimeout: refundTimeout.toString(),
1343
+ constructorArgs: encodeEpochPoolConstructorArgs({
1344
+ token: token.toLowerCase(),
1345
+ admin: studio,
1346
+ operator: studio,
1347
+ feeSink: sink,
1348
+ refundTimeout
1349
+ }),
1350
+ broadcast: false,
1351
+ constructor: "EpochPrizePool",
1352
+ studioHoldsAdmin: true,
1353
+ studioHoldsOperator: true,
1354
+ playmosIsAdmin: false,
1355
+ playmosIsOperator: false,
1356
+ via: "mock",
1357
+ mock: true
1358
+ };
1359
+ }
1360
+ function epochPoolProofMessage(terms) {
1361
+ return [
1362
+ "Playmos EpochPrizePool registration",
1363
+ `studio: ${terms.studioId}`,
1364
+ `pool: ${terms.poolAddress.toLowerCase()}`,
1365
+ `wallet: ${terms.studioWallet.toLowerCase()}`,
1366
+ `chainId: ${terms.chainId}`
1367
+ ].join("\n");
1368
+ }
1369
+ async function readWithdrawableMicro(deps, pool) {
1370
+ const read = deps.readView;
1371
+ const account = deps.walletAddress;
1372
+ if (!read || !account) return null;
1373
+ try {
1374
+ const raw = await read(
1375
+ pool,
1376
+ viem.encodeFunctionData({
1377
+ abi: epochPrizePoolViewAbi,
1378
+ functionName: "withdrawable",
1379
+ args: [await account()]
1380
+ })
1381
+ );
1382
+ return viem.decodeFunctionResult({
1383
+ abi: epochPrizePoolViewAbi,
1384
+ functionName: "withdrawable",
1385
+ data: raw
1386
+ });
1387
+ } catch {
1388
+ return null;
1389
+ }
1390
+ }
1391
+ function settlementTypedData(input) {
1392
+ const pool = requireAddr(input.pool, "pool");
1393
+ const series = requireSeries(input.series);
1394
+ const epochId = requirePastEpochId(input.epochId);
1395
+ if (!Array.isArray(input.winners) || !Array.isArray(input.amounts)) {
1396
+ throw new MissingFieldError("winners");
1397
+ }
1398
+ if (input.winners.length !== input.amounts.length) {
1399
+ throw new ConfigError("winners and amounts must be the same length");
1400
+ }
1401
+ return {
1402
+ domain: {
1403
+ name: "EpochPrizePool",
1404
+ version: "1",
1405
+ chainId: input.chainId,
1406
+ verifyingContract: pool
1407
+ },
1408
+ types: {
1409
+ Settlement: [
1410
+ { name: "series", type: "bytes32" },
1411
+ { name: "epochId", type: "uint256" },
1412
+ { name: "winners", type: "address[]" },
1413
+ { name: "amounts", type: "uint256[]" }
1414
+ ]
1415
+ },
1416
+ primaryType: "Settlement",
1417
+ message: {
1418
+ series: seriesToBytes32(series),
1419
+ epochId: BigInt(epochId),
1420
+ winners: input.winners.map((w, i) => requireAddrKeepCase(w, `winners[${i}]`)),
1421
+ amounts: input.amounts.map((a, i) => parseMicroString(a, `amounts[${i}]`))
1422
+ }
1423
+ };
1424
+ }
1425
+ function parseMicroString(raw, field) {
1426
+ if (typeof raw !== "string" || !/^(0|[1-9]\d*)$/.test(raw)) {
1427
+ throw new ConfigError(`${field} must be an integer micro-USDC string`, { field });
1428
+ }
1429
+ return BigInt(raw);
1430
+ }
1431
+ async function readEpochTerminal(deps, pool, series, epochId) {
1432
+ const read = deps.readView;
1433
+ if (!read) return null;
1434
+ try {
1435
+ const raw = await read(
1436
+ pool,
1437
+ viem.encodeFunctionData({
1438
+ abi: epochPrizePoolViewAbi,
1439
+ functionName: "getEpoch",
1440
+ args: [seriesToBytes32(series), BigInt(epochId)]
1441
+ })
1442
+ );
1443
+ const decoded = viem.decodeFunctionResult({
1444
+ abi: epochPrizePoolViewAbi,
1445
+ functionName: "getEpoch",
1446
+ data: raw
1447
+ });
1448
+ const termRaw = decoded && typeof decoded === "object" && "terminal" in decoded ? Number(decoded.terminal) : Number(decoded[4]);
1449
+ return terminalFromChain(termRaw);
1450
+ } catch {
1451
+ return null;
1452
+ }
1453
+ }
1454
+ function createEpochsApi(deps) {
1455
+ return {
1456
+ async currentId(input) {
1457
+ const series = requireSeries(input?.series);
1458
+ const cfg = deps.config();
1459
+ if (cfg.mock) {
1460
+ const genesis = toBig(input.genesis, 0n);
1461
+ const duration = toBig(input.epochDuration, 1n);
1462
+ const at = toBig(input.at, BigInt(Math.floor(Date.now() / 1e3)));
1463
+ const epochId = derivedEpochId(genesis, duration, at);
1464
+ return {
1465
+ series,
1466
+ epochId: epochId.toString(),
1467
+ via: "mock",
1468
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool ?? null,
1469
+ mock: true
1470
+ };
1471
+ }
1472
+ const path = `/epochs/current${qs({
1473
+ series,
1474
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool
1475
+ })}`;
1476
+ return deps.http().get(path);
1477
+ },
1478
+ async prize(input) {
1479
+ const series = requireSeries(input?.series);
1480
+ const cfg = deps.config();
1481
+ const epochId = epochPathId(input?.epochId);
1482
+ if (cfg.mock) {
1483
+ return pictureFromMicros({
1484
+ series,
1485
+ epochId: epochId === "current" ? "0" : epochId,
1486
+ poolMicro: 0n,
1487
+ incomingSeedMicro: 0n,
1488
+ outgoingSeedMicro: 0n,
1489
+ via: "mock",
1490
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool ?? null,
1491
+ mock: true
1492
+ });
1493
+ }
1494
+ const path = `/epochs/${encodeURIComponent(epochId)}/prize${qs({
1495
+ series,
1496
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool
1497
+ })}`;
1498
+ const res = await deps.http().get(path);
1499
+ return res.prize;
1500
+ },
1501
+ async get(input) {
1502
+ const series = requireSeries(input?.series);
1503
+ const cfg = deps.config();
1504
+ const epochId = epochPathId(input?.epochId);
1505
+ if (cfg.mock) {
1506
+ const prize = pictureFromMicros({
1507
+ series,
1508
+ epochId: epochId === "current" ? "0" : epochId,
1509
+ poolMicro: 0n,
1510
+ incomingSeedMicro: 0n,
1511
+ outgoingSeedMicro: 0n,
1512
+ via: "mock",
1513
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool ?? null,
1514
+ mock: true
1515
+ });
1516
+ return {
1517
+ ...prize,
1518
+ entryCount: "0",
1519
+ terminal: "none"
1520
+ };
1521
+ }
1522
+ const path = `/epochs/${encodeURIComponent(epochId)}${qs({
1523
+ series,
1524
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool
1525
+ })}`;
1526
+ return deps.http().get(path);
1527
+ },
1528
+ async getSeries(input) {
1529
+ const series = requireSeries(input?.series);
1530
+ const cfg = deps.config();
1531
+ if (cfg.mock) {
1532
+ return {
1533
+ series,
1534
+ created: true,
1535
+ genesis: "0",
1536
+ epochDuration: "1",
1537
+ entry: "0",
1538
+ feeBps: 1e3,
1539
+ poolBps: 6e3,
1540
+ seedBps: 3e3,
1541
+ via: "mock",
1542
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool ?? null,
1543
+ mock: true
1544
+ };
1545
+ }
1546
+ const path = `/epochs/series${qs({
1547
+ series,
1548
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool
1549
+ })}`;
1550
+ return deps.http().get(path);
1551
+ },
1552
+ async preparePool(input) {
1553
+ const studioWallet = requireAddr(input?.studioWallet, "studioWallet");
1554
+ const cfg = deps.config();
1555
+ const sink = PLAYMOS_FEE_SINK_DEFAULT;
1556
+ const token = (input.token ?? cfg.contracts?.usdc ?? "0x036cbd53842c5426634e7929541ec2318f3dcf7e").toLowerCase();
1557
+ if (input.playmosFeeSink && !sameAddr(input.playmosFeeSink, sink)) {
1558
+ throw new ConfigError("feeSink must equal the Playmos Sepolia treasury; refused before broadcast");
1559
+ }
1560
+ if (cfg.mock) {
1561
+ return prepareStudioPoolLocal({ ...input, studioWallet }, sink, token);
1562
+ }
1563
+ return deps.http().post("/epochs/pools/prepare", {
1564
+ studioWallet,
1565
+ feeSink: input.feeSink,
1566
+ admin: input.admin,
1567
+ operator: input.operator,
1568
+ refundTimeout: input.refundTimeout
1569
+ });
1570
+ },
1571
+ async registerPool(input) {
1572
+ const studioWallet = requireAddr(input?.studioWallet, "studioWallet");
1573
+ const poolAddress = requireAddr(input?.poolAddress, "poolAddress");
1574
+ const cfg = deps.config();
1575
+ if (cfg.mock) {
1576
+ const sink = (input.feeSink ?? PLAYMOS_FEE_SINK_DEFAULT).toLowerCase();
1577
+ const token = (cfg.contracts?.usdc ?? "0x036cbd53842c5426634e7929541ec2318f3dcf7e").toLowerCase();
1578
+ const prepared = prepareStudioPoolLocal({ studioWallet, feeSink: input.feeSink, admin: input.admin, operator: input.operator }, sink, token);
1579
+ return {
1580
+ poolAddress,
1581
+ studioWallet: prepared.admin,
1582
+ feeSink: prepared.feeSink,
1583
+ admin: prepared.admin,
1584
+ operator: prepared.operator,
1585
+ studioHoldsAdmin: true,
1586
+ studioHoldsOperator: true,
1587
+ playmosIsAdmin: false,
1588
+ playmosIsOperator: false,
1589
+ ownership: input.walletProof ? "confirmed" : "pending",
1590
+ owner: null,
1591
+ via: "mock",
1592
+ mock: true
1593
+ };
1594
+ }
1595
+ return deps.http().post("/epochs/pools", {
1596
+ studioWallet,
1597
+ poolAddress,
1598
+ feeSink: input.feeSink,
1599
+ admin: input.admin,
1600
+ operator: input.operator,
1601
+ txHash: input.txHash,
1602
+ walletProof: input.walletProof
1603
+ });
1604
+ },
1605
+ async createPool(input) {
1606
+ const prepared = await this.preparePool(input);
1607
+ const cfg = deps.config();
1608
+ if (cfg.mock) {
1609
+ const poolAddress = input.poolAddress ? requireAddr(input.poolAddress, "poolAddress") : `0x${prepared.constructorArgs.slice(2, 42).padEnd(40, "0")}`;
1610
+ return this.registerPool({
1611
+ studioWallet: prepared.admin,
1612
+ poolAddress,
1613
+ feeSink: prepared.feeSink,
1614
+ walletProof: input.walletProof
1615
+ });
1616
+ }
1617
+ if (!input.poolAddress) {
1618
+ throw new ConfigError(
1619
+ "createPool on the live path needs poolAddress after the studio wallet submits the constructor \u2014 Playmos does not broadcast"
1620
+ );
1621
+ }
1622
+ return this.registerPool({
1623
+ studioWallet: prepared.admin,
1624
+ poolAddress: input.poolAddress,
1625
+ feeSink: prepared.feeSink,
1626
+ txHash: input.txHash,
1627
+ walletProof: input.walletProof
1628
+ });
1629
+ },
1630
+ async settle(input) {
1631
+ const series = requireSeries(input?.series);
1632
+ if (!Array.isArray(input?.winners)) {
1633
+ throw new MissingFieldError("winners");
1634
+ }
1635
+ const epochId = epochPathId(input?.epochId);
1636
+ if (epochId === "current") {
1637
+ throw new ConfigError("epochs.settle requires a past epochId \u2014 Current is still taking entries");
1638
+ }
1639
+ const cfg = deps.config();
1640
+ if (!cfg.mock) {
1641
+ if (deps.assertSecretKey) deps.assertSecretKey("playmos.epochs.settle");
1642
+ else if (!String(cfg.apiKey ?? "").startsWith("sk_")) {
1643
+ throw new AuthError(
1644
+ "playmos.epochs.settle requires a secret (sk_) key \u2014 use sk_test_\u2026 / sk_live_\u2026 on the server. Publishable (pk_) keys cannot settle.",
1645
+ { surface: "playmos.epochs.settle", isSecret: false }
1646
+ );
1647
+ }
1648
+ }
1649
+ if (cfg.mock) {
1650
+ const empty = input.winners.length === 0;
1651
+ const podiumPayable = mockPodiumPayable(input.winners);
1652
+ return {
1653
+ series,
1654
+ epochId,
1655
+ status: empty ? "rolled" : "settled",
1656
+ txHash: "0x0000000000000000000000000000000000000000000000000000000000000001",
1657
+ winners: input.winners.map((w) => {
1658
+ const wallet = (typeof w === "string" ? w : w.wallet).toLowerCase();
1659
+ return { wallet, ...mockWinnerAmount(w) };
1660
+ }),
1661
+ ...podiumPayable ?? {},
1662
+ terminal: empty ? "rolled" : "settled",
1663
+ via: "mock",
1664
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool ?? null,
1665
+ mock: true
1666
+ };
1667
+ }
1668
+ const body = await deps.http().post(
1669
+ `/epochs/${encodeURIComponent(epochId)}/settle`,
1670
+ {
1671
+ series,
1672
+ winners: input.winners,
1673
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool
1674
+ },
1675
+ { acceptStatuses: [200, 202] }
1676
+ );
1677
+ return body.settle;
1678
+ },
1679
+ async enter(input) {
1680
+ const series = requireSeries(input?.series);
1681
+ const identity = requireIdentity(input?.identity);
1682
+ const cfg = deps.config();
1683
+ const seriesBytes32 = seriesToBytes32(series);
1684
+ const identityBytes32 = identityToBytes32(identity);
1685
+ if (cfg.mock) {
1686
+ const genesis = toBig(input.genesis, 0n);
1687
+ const duration = toBig(input.epochDuration, 1n);
1688
+ const at = toBig(input.at, BigInt(Math.floor(Date.now() / 1e3)));
1689
+ return {
1690
+ series,
1691
+ identity,
1692
+ epochId: derivedEpochId(genesis, duration, at).toString(),
1693
+ epochIdSource: "mock",
1694
+ seriesBytes32,
1695
+ identityBytes32,
1696
+ entry: formatMicroToUsd(C1_ENTER_SPLIT_MICRO.entry),
1697
+ entryMicro: C1_ENTER_SPLIT_MICRO.entry.toString(),
1698
+ status: "confirmed",
1699
+ txHash: MOCK_TX,
1700
+ identityEntryCount: "1",
1701
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool ?? null,
1702
+ usdc: cfg.contracts?.usdc ?? null,
1703
+ via: "mock",
1704
+ mock: true
1705
+ };
1706
+ }
1707
+ const epochPrizePool = input.epochPrizePool ?? cfg.contracts?.epochPrizePool;
1708
+ const plan = await deps.http().post("/epochs/enter", {
1709
+ series,
1710
+ identity,
1711
+ ...epochPrizePool ? { epochPrizePool } : {}
1712
+ });
1713
+ assertPinParity("series", seriesBytes32, plan.clientParams?.seriesBytes32);
1714
+ assertPinParity("identity", identityBytes32, plan.clientParams?.identityBytes32);
1715
+ const send = deps.sendEntry;
1716
+ if (!send) {
1717
+ throw new ConfigError(
1718
+ "epochs.enter needs a player wallet \u2014 pass `wallet` to the Playmos client. Entry money goes straight to the contract; Playmos never holds it. Building the calls yourself? Import `buildEpochEntryCalls`.",
1719
+ { field: "wallet" }
1720
+ );
1721
+ }
1722
+ const entryMicro = BigInt(plan.clientParams.entryMicro);
1723
+ const calls = buildEpochEntryCalls({
1724
+ usdc: plan.clientParams.usdc,
1725
+ epochPrizePool: plan.clientParams.epochPrizePool,
1726
+ series,
1727
+ identity,
1728
+ entryMicro
1729
+ });
1730
+ const sent = await send(calls, { paymasterUrl: plan.clientParams.paymasterUrl });
1731
+ const base = {
1732
+ series,
1733
+ identity,
1734
+ epochId: plan.entry.epochId,
1735
+ epochIdSource: "chain-clock",
1736
+ seriesBytes32,
1737
+ identityBytes32,
1738
+ entry: plan.entry.entry,
1739
+ entryMicro: plan.entry.entryMicro,
1740
+ status: sent.status === "FAILED" ? "failed" : "pending",
1741
+ txHash: sent.txHash,
1742
+ epochPrizePool: plan.clientParams.epochPrizePool,
1743
+ usdc: plan.clientParams.usdc,
1744
+ via: "service"
1745
+ };
1746
+ if (!sent.txHash) return base;
1747
+ try {
1748
+ const confirmed = await deps.http().post("/epochs/enter/confirm", {
1749
+ series,
1750
+ identity,
1751
+ txHash: sent.txHash,
1752
+ ...epochPrizePool ? { epochPrizePool } : {}
1753
+ });
1754
+ return {
1755
+ ...base,
1756
+ epochId: confirmed.entry.epochId,
1757
+ epochIdSource: confirmed.entry.epochIdSource,
1758
+ status: confirmed.entry.status,
1759
+ identityEntryCount: confirmed.entry.identityEntryCount
1760
+ };
1761
+ } catch {
1762
+ return base;
1763
+ }
1764
+ },
1765
+ async claimableRefund(input) {
1766
+ const series = requireSeries(input?.series);
1767
+ const payer = requireAddr(input?.payer, "payer");
1768
+ const epochId = requirePastEpochId(input?.epochId);
1769
+ const cfg = deps.config();
1770
+ const seriesBytes32 = seriesToBytes32(series);
1771
+ const epochPrizePool = input.epochPrizePool ?? cfg.contracts?.epochPrizePool ?? null;
1772
+ if (cfg.mock) {
1773
+ return {
1774
+ series,
1775
+ epochId,
1776
+ payer,
1777
+ claimable: "0.00",
1778
+ claimableMicro: "0",
1779
+ seriesBytes32,
1780
+ epochPrizePool,
1781
+ via: "mock",
1782
+ mock: true
1783
+ };
1784
+ }
1785
+ const pool = requireEpochPool(input, cfg);
1786
+ const data = viem.encodeFunctionData({
1787
+ abi: epochPrizePoolViewAbi,
1788
+ functionName: "claimableRefund",
1789
+ args: [seriesBytes32, BigInt(epochId), payer]
1790
+ });
1791
+ const read = deps.readView;
1792
+ if (!read) {
1793
+ throw new ConfigError(
1794
+ "epochs.claimableRefund needs a wallet or RPC to read EpochPrizePool \u2014 pass `wallet` to the Playmos client",
1795
+ { field: "wallet" }
1796
+ );
1797
+ }
1798
+ const raw = await read(pool, data);
1799
+ const amount = viem.decodeFunctionResult({
1800
+ abi: epochPrizePoolViewAbi,
1801
+ functionName: "claimableRefund",
1802
+ data: raw
1803
+ });
1804
+ return {
1805
+ series,
1806
+ epochId,
1807
+ payer,
1808
+ claimable: formatMicroToUsd(amount),
1809
+ claimableMicro: amount.toString(),
1810
+ seriesBytes32,
1811
+ epochPrizePool: pool,
1812
+ via: "chain"
1813
+ };
1814
+ },
1815
+ async claimRefund(input) {
1816
+ const series = requireSeries(input?.series);
1817
+ const payer = requireAddr(input?.payer, "payer");
1818
+ const epochId = requirePastEpochId(input?.epochId);
1819
+ const cfg = deps.config();
1820
+ const pool = requireEpochPool(input, cfg);
1821
+ if (cfg.mock) {
1822
+ return {
1823
+ series,
1824
+ epochId,
1825
+ payer,
1826
+ txHash: MOCK_TX,
1827
+ status: "confirmed",
1828
+ epochPrizePool: pool,
1829
+ via: "mock",
1830
+ mock: true
1831
+ };
1832
+ }
1833
+ const send = deps.sendEntry;
1834
+ if (!send) {
1835
+ throw new ConfigError(
1836
+ "epochs.claimRefund needs a player wallet \u2014 pass `wallet` to the Playmos client. The credit lands on `payer`; the connected wallet only signs.",
1837
+ { field: "wallet" }
1838
+ );
1839
+ }
1840
+ const call = buildEpochClaimRefundCall({
1841
+ epochPrizePool: pool,
1842
+ series,
1843
+ epochId: BigInt(epochId),
1844
+ payer
1845
+ });
1846
+ const sent = await send([call], {});
1847
+ return {
1848
+ series,
1849
+ epochId,
1850
+ payer,
1851
+ txHash: sent.txHash,
1852
+ status: walletStatus(sent.status),
1853
+ epochPrizePool: pool,
1854
+ via: "chain"
1855
+ };
1856
+ },
1857
+ async withdraw(input = {}) {
1858
+ const cfg = deps.config();
1859
+ const pool = requireEpochPool(input, cfg);
1860
+ if (cfg.mock) {
1861
+ return {
1862
+ epochPrizePool: pool,
1863
+ txHash: MOCK_TX,
1864
+ status: "confirmed",
1865
+ via: "mock",
1866
+ mock: true
1867
+ };
1868
+ }
1869
+ const send = deps.sendEntry;
1870
+ if (!send) {
1871
+ throw new ConfigError(
1872
+ "epochs.withdraw needs the payer wallet \u2014 pass `wallet` to the Playmos client. USDC is pulled to msg.sender on EpochPrizePool, not PrizePool.",
1873
+ { field: "wallet" }
1874
+ );
1875
+ }
1876
+ const creditedMicro = await readWithdrawableMicro(deps, pool);
1877
+ const call = buildEpochWithdrawCall(pool);
1878
+ const sent = await send([call], {});
1879
+ return {
1880
+ epochPrizePool: pool,
1881
+ ...creditedMicro === null ? {} : {
1882
+ amount: formatMicroToUsd(creditedMicro),
1883
+ amountMicro: creditedMicro.toString()
1884
+ },
1885
+ txHash: sent.txHash,
1886
+ status: walletStatus(sent.status),
1887
+ via: "chain"
1888
+ };
1889
+ },
1890
+ async getAttestation(input) {
1891
+ const series = requireSeries(input?.series);
1892
+ const epochId = requirePastEpochId(input?.epochId);
1893
+ const cfg = deps.config();
1894
+ if (cfg.mock) {
1895
+ const pool = input.epochPrizePool ?? cfg.contracts?.epochPrizePool;
1896
+ if (!pool) {
1897
+ throw new ConfigError("epochs.getAttestation needs contracts.epochPrizePool (or pass epochPrizePool)", {
1898
+ field: "epochPrizePool"
1899
+ });
1900
+ }
1901
+ return {
1902
+ series,
1903
+ epochId,
1904
+ winners: input.winners ?? [],
1905
+ amountsMicro: input.amountsMicro ?? [],
1906
+ signature: input.signature ?? `0x${"00".repeat(65)}`,
1907
+ epochPrizePool: requireAddr(pool, "epochPrizePool"),
1908
+ via: "mock",
1909
+ mock: true
1910
+ };
1911
+ }
1912
+ const path = `/epochs/${encodeURIComponent(epochId)}/attestation${qs({
1913
+ series,
1914
+ epochPrizePool: input.epochPrizePool ?? cfg.contracts?.epochPrizePool
1915
+ })}`;
1916
+ const res = await deps.http().get(path);
1917
+ const inner = res.attestation ?? res;
1918
+ if (!inner.series || !inner.winners || !inner.amountsMicro || !inner.signature || !inner.epochPrizePool) {
1919
+ throw new ConfigError("attestation response missing posted fields \u2014 refusing to invent a podium");
1920
+ }
1921
+ return {
1922
+ series: inner.series,
1923
+ epochId: String(inner.epochId ?? epochId),
1924
+ winners: inner.winners,
1925
+ amountsMicro: inner.amountsMicro,
1926
+ signature: inner.signature,
1927
+ epochPrizePool: inner.epochPrizePool,
1928
+ ...res.terminal !== void 0 ? { terminal: res.terminal } : {},
1929
+ ...res.dueAt !== void 0 ? { dueAt: res.dueAt } : {},
1930
+ via: res.via ?? "service"
1931
+ };
1932
+ },
1933
+ async executeSettlement(input) {
1934
+ const series = requireSeries(input?.series);
1935
+ const epochId = requirePastEpochId(input?.epochId);
1936
+ if (!Array.isArray(input?.winners)) throw new MissingFieldError("winners");
1937
+ if (!Array.isArray(input?.amounts)) throw new MissingFieldError("amounts");
1938
+ if (typeof input?.signature !== "string" || !/^0x[0-9a-fA-F]{130}$/.test(input.signature)) {
1939
+ throw new MissingFieldError("signature");
1940
+ }
1941
+ const winners = input.winners.map((w, i) => requireAddrKeepCase(w, `winners[${i}]`));
1942
+ const amountsMicro = input.amounts.map((a, i) => {
1943
+ parseMicroString(a, `amounts[${i}]`);
1944
+ return a;
1945
+ });
1946
+ const amounts = amountsMicro.map((a, i) => parseMicroString(a, `amounts[${i}]`));
1947
+ const cfg = deps.config();
1948
+ const pool = requireEpochPool(input, cfg);
1949
+ if (cfg.mock) {
1950
+ return {
1951
+ series,
1952
+ epochId,
1953
+ winners,
1954
+ amountsMicro,
1955
+ signature: input.signature,
1956
+ txHash: MOCK_TX,
1957
+ status: "confirmed",
1958
+ epochPrizePool: pool,
1959
+ via: "mock",
1960
+ mock: true
1961
+ };
1962
+ }
1963
+ const send = deps.sendEntry;
1964
+ if (!send) {
1965
+ throw new ConfigError(
1966
+ "epochs.executeSettlement needs a wallet \u2014 pass `wallet` to the Playmos client. The SDK relays the signed podium; it does not choose winners.",
1967
+ { field: "wallet" }
1968
+ );
1969
+ }
1970
+ const call = buildEpochExecuteSettlementCall({
1971
+ epochPrizePool: pool,
1972
+ series,
1973
+ epochId: BigInt(epochId),
1974
+ winners,
1975
+ amounts,
1976
+ signature: input.signature
1977
+ });
1978
+ let sent;
1979
+ try {
1980
+ sent = await send([call], {});
1981
+ } catch (e) {
1982
+ const msg = e?.message ?? String(e);
1983
+ throw new PaymentFailedError("EpochPrizePool.executeSignedSettlement failed.", { cause: msg });
1984
+ }
1985
+ const terminal = await readEpochTerminal(deps, pool, series, epochId);
1986
+ return {
1987
+ series,
1988
+ epochId,
1989
+ winners,
1990
+ amountsMicro,
1991
+ signature: input.signature,
1992
+ txHash: sent.txHash,
1993
+ status: walletStatus(sent.status),
1994
+ ...terminal === null ? {} : { terminal, settled: terminal === "settled" },
1995
+ epochPrizePool: pool,
1996
+ via: "chain"
1997
+ };
1998
+ }
1999
+ };
2000
+ }
2001
+ var C1_ENTER_SPLIT_MICRO = {
2002
+ entry: 1000000n,
2003
+ fee: 100000n,
2004
+ pool: 600000n,
2005
+ outgoingSeed: 300000n,
2006
+ incomingSeed: 0n
2007
+ };
2008
+
2009
+ // src/x402.ts
2010
+ var ADDRESS_RE3 = /^0x[0-9a-fA-F]{40}$/;
899
2011
  function requireAddress2(value, field) {
900
2012
  if (typeof value !== "string" || value.trim() === "") {
901
2013
  throw new MissingFieldError(field);
902
2014
  }
903
- if (!ADDRESS_RE2.test(value)) {
2015
+ if (!ADDRESS_RE3.test(value)) {
904
2016
  throw new ConfigError(`${field} must be a 0x-prefixed 20-byte address, got: ${JSON.stringify(value)}`, {
905
2017
  field,
906
2018
  value
@@ -1038,7 +2150,7 @@ function validateX402ChallengeInput(input) {
1038
2150
  }
1039
2151
 
1040
2152
  // src/client.ts
1041
- var ADDRESS_RE3 = /^0x[0-9a-fA-F]{40}$/;
2153
+ var ADDRESS_RE4 = /^0x[0-9a-fA-F]{40}$/;
1042
2154
  function mapAlreadyEntered(e) {
1043
2155
  const msg = e instanceof Error ? e.message : typeof e === "object" && e && "message" in e ? String(e.message) : String(e);
1044
2156
  const detail = e instanceof PaymentFailedError || e instanceof ApiError ? e.detail : void 0;
@@ -1086,7 +2198,7 @@ function requireAddressField(value, field) {
1086
2198
  if (typeof value !== "string" || value.trim() === "") {
1087
2199
  throw new MissingFieldError(field);
1088
2200
  }
1089
- if (!ADDRESS_RE3.test(value)) {
2201
+ if (!ADDRESS_RE4.test(value)) {
1090
2202
  throw new ConfigError(
1091
2203
  `${field} must be a 0x-prefixed 20-byte wallet address (Phase 1a transfers settle server-held wallets), got: ${JSON.stringify(value)}`,
1092
2204
  { field, value }
@@ -1125,6 +2237,56 @@ var Playmos = class {
1125
2237
  );
1126
2238
  }
1127
2239
  };
2240
+ /**
2241
+ * Rolling epochs — `currentId` / `prize` / `get` / `getSeries` (sdk#629),
2242
+ * `enter` (sdk#635 / S2), operator `settle` (sdk#639 / S3), the C3
2243
+ * refund pull (sdk#634), and E1b `getAttestation` / `executeSettlement`
2244
+ * (wallet-direct via the same `walletProvider()` funnel as `rounds.withdraw`).
2245
+ * Reads/settle go through the service. Refund claim, withdraw, and signed
2246
+ * execute are wallet-direct on EpochPrizePool — not PrizePool.
2247
+ * Nothing here opens a round.
2248
+ */
2249
+ this.epochs = createEpochsApi({
2250
+ http: () => this.http,
2251
+ config: () => this.config,
2252
+ assertSecretKey: (surface) => this.assertSecretKey(surface),
2253
+ sendEntry: async (calls, opts) => {
2254
+ const provider = this.walletProvider();
2255
+ if (this.config.gas?.mode === "player") {
2256
+ await assertEnoughGas(provider, await getAccount(provider));
2257
+ }
2258
+ const from = await getAccount(provider);
2259
+ const paymasterUrl = this.config.gas?.mode === "player" ? void 0 : this.config.gas?.paymasterUrl ?? opts.paymasterUrl;
2260
+ const { id } = await sendCalls(provider, from, this.env.chainId, calls, paymasterUrl);
2261
+ return waitForCalls(provider, id);
2262
+ },
2263
+ walletAddress: async () => getAccount(this.walletProvider()),
2264
+ readView: async (to, data) => {
2265
+ if (await walletAvailable(this.config.wallet, this.walletTimeoutPolicy())) {
2266
+ const provider = this.walletProvider();
2267
+ return await provider.request({
2268
+ method: "eth_call",
2269
+ params: [{ to, data }, "latest"]
2270
+ });
2271
+ }
2272
+ const rpc = this.env.network === "base" ? "https://mainnet.base.org" : "https://sepolia.base.org";
2273
+ const res = await fetch(rpc, {
2274
+ method: "POST",
2275
+ headers: { "content-type": "application/json" },
2276
+ body: JSON.stringify({
2277
+ jsonrpc: "2.0",
2278
+ id: 1,
2279
+ method: "eth_call",
2280
+ params: [{ to, data }, "latest"]
2281
+ })
2282
+ });
2283
+ const json = await res.json();
2284
+ if (!json.result) {
2285
+ throw new ApiError(`eth_call failed: ${json.error?.message ?? "no result"}`, { to });
2286
+ }
2287
+ return json.result;
2288
+ }
2289
+ });
1128
2290
  this.payouts = {
1129
2291
  /** Choose how the studio is paid: "usdc" (default) or "fiat" (Bridge). Secret key only (#264). */
1130
2292
  setMode: async (mode) => {
@@ -1290,6 +2452,8 @@ var Playmos = class {
1290
2452
  this.mockPotMicro = /* @__PURE__ */ new Map();
1291
2453
  /** Persisted settle winners for re-settle replay (#490 C2) — never re-invent pool-to-everyone. */
1292
2454
  this.mockSettleWinners = /* @__PURE__ */ new Map();
2455
+ /** L34 notices after mock settle — funded only with a push txHash. */
2456
+ this.mockPayoutNotices = /* @__PURE__ */ new Map();
1293
2457
  this.rounds = {
1294
2458
  open: async (input) => {
1295
2459
  if (!this.config.mock) this.assertSecretKey("playmos.rounds.open");
@@ -1455,6 +2619,16 @@ var Playmos = class {
1455
2619
  };
1456
2620
  this.mockRounds.set(input.roundId, settled);
1457
2621
  this.mockSettleWinners.set(input.roundId, winners);
2622
+ this.mockPayoutNotices.set(
2623
+ input.roundId,
2624
+ rows.filter((w) => w.micro > 0n).map((w) => ({
2625
+ roundId: input.roundId,
2626
+ wallet: w.wallet.toLowerCase(),
2627
+ amountMicro: w.micro.toString(),
2628
+ status: "claimable",
2629
+ reason: "prizepool_pull_credit"
2630
+ }))
2631
+ );
1458
2632
  for (const w of rows) {
1459
2633
  if (w.micro <= 0n) continue;
1460
2634
  const k = `${input.roundId}:${w.wallet.toLowerCase()}`;
@@ -1696,6 +2870,93 @@ var Playmos = class {
1696
2870
  }
1697
2871
  return body.active;
1698
2872
  },
2873
+ /**
2874
+ * L34 / sdk#610 — notifications for a settled round.
2875
+ * Each win is `funded` (push txHash) or `claimable` (withdraw fallback).
2876
+ * Never returns `funded` without a transfer txHash.
2877
+ */
2878
+ payoutNotices: async (input) => {
2879
+ requireField(input?.roundId, "roundId");
2880
+ if (this.config.mock) {
2881
+ const existing = this.mockRounds.get(input.roundId);
2882
+ if (!existing) {
2883
+ throw new ApiError(`unknown round: ${input.roundId}`, { status: 404, code: "not_found" });
2884
+ }
2885
+ let notices = this.mockPayoutNotices.get(input.roundId) ?? [];
2886
+ if (input.wallet) {
2887
+ if (!ADDRESS_RE4.test(input.wallet)) {
2888
+ throw new ConfigError("wallet must be a 0x-prefixed 20-byte address");
2889
+ }
2890
+ const want = input.wallet.toLowerCase();
2891
+ notices = notices.filter((n) => n.wallet === want);
2892
+ }
2893
+ for (const n of notices) {
2894
+ if (n.status === "funded" && !n.txHash) {
2895
+ throw new ApiError("cannot label funded without a transfer txHash", {
2896
+ status: 500,
2897
+ code: "payout_notice_invalid"
2898
+ });
2899
+ }
2900
+ }
2901
+ return { roundId: input.roundId, status: existing.status, notices };
2902
+ }
2903
+ const q = input.wallet ? `?wallet=${encodeURIComponent(input.wallet)}` : "";
2904
+ return this.http.get(
2905
+ `/rounds/${encodeURIComponent(input.roundId)}/payout-notices${q}`
2906
+ );
2907
+ },
2908
+ /**
2909
+ * Operator push-attempt after settle (L34). Mock: mark a winner funded only
2910
+ * when a real-shaped txHash is supplied; otherwise that row stays claimable.
2911
+ */
2912
+ pushWinnings: async (input) => {
2913
+ requireField(input?.roundId, "roundId");
2914
+ if (!this.config.mock) this.assertSecretKey("playmos.rounds.pushWinnings");
2915
+ if (this.config.mock) {
2916
+ const existing = this.mockRounds.get(input.roundId);
2917
+ if (!existing) {
2918
+ throw new ApiError(`unknown round: ${input.roundId}`, { status: 404, code: "not_found" });
2919
+ }
2920
+ if (existing.status !== "settled") {
2921
+ throw new ApiError(`round ${input.roundId} is not settled \u2014 push after the clock`, {
2922
+ status: 409,
2923
+ code: "conflict"
2924
+ });
2925
+ }
2926
+ const prior = this.mockPayoutNotices.get(input.roundId) ?? [];
2927
+ const byWallet = new Map(
2928
+ (input.pushes ?? []).map((p) => [p.wallet.toLowerCase(), p])
2929
+ );
2930
+ const TX_RE = /^0x[0-9a-fA-F]{64}$/;
2931
+ const ZERO = "0x" + "00".repeat(32);
2932
+ const notices = prior.map((n) => {
2933
+ const p = byWallet.get(n.wallet);
2934
+ if (p && !p.failed && p.txHash && TX_RE.test(p.txHash) && p.txHash.toLowerCase() !== ZERO) {
2935
+ return {
2936
+ ...n,
2937
+ status: "funded",
2938
+ txHash: p.txHash.toLowerCase(),
2939
+ reason: void 0
2940
+ };
2941
+ }
2942
+ if (p && (p.failed || !p.txHash || !TX_RE.test(p.txHash) || p.txHash.toLowerCase() === ZERO)) {
2943
+ return {
2944
+ ...n,
2945
+ status: "claimable",
2946
+ txHash: void 0,
2947
+ reason: p.failed ? "push_failed" : "push_missing_txHash"
2948
+ };
2949
+ }
2950
+ return n;
2951
+ });
2952
+ this.mockPayoutNotices.set(input.roundId, notices);
2953
+ return { roundId: input.roundId, status: existing.status, notices };
2954
+ }
2955
+ return this.http.post(
2956
+ `/rounds/${encodeURIComponent(input.roundId)}/push-winnings`,
2957
+ {}
2958
+ );
2959
+ },
1699
2960
  /**
1700
2961
  * Read a wallet's **claimable** prize balance for a round (issue #41).
1701
2962
  * Prefers the service chain read (`GET /v1/rounds/:id/prize?wallet=`); falls
@@ -1752,7 +3013,7 @@ var Playmos = class {
1752
3013
  const existing = this.mockRounds.get(input.roundId);
1753
3014
  if (existing?.prizePoolAddress) prizePool2 = existing.prizePoolAddress;
1754
3015
  }
1755
- if (!input.wallet || !ADDRESS_RE3.test(input.wallet)) {
3016
+ if (!input.wallet || !ADDRESS_RE4.test(input.wallet)) {
1756
3017
  throw new ConfigError(
1757
3018
  "mock rounds.withdraw requires wallet (0x\u2026) \u2014 live uses the connected provider; without wallet mock would pay the first non-zero credit to the wrong player (#495)"
1758
3019
  );
@@ -2363,7 +3624,7 @@ var Playmos = class {
2363
3624
  const { txHash } = await waitForCalls(provider, callsId);
2364
3625
  return this.settle(intent.payment.id, txHash);
2365
3626
  }
2366
- /** Playmos-owned skill-game entry (10%, 60/30/10 prize pool). Closes #343. */
3627
+ /** Skill-game prize-pool entry. Live sandbox / Playmos Lab uses 60/30/10. Studio contest take is 1% (not a live separate pool yet). Closes #343. */
2367
3628
  async enterRound(input) {
2368
3629
  const amountMicro = validateAmount(input.amount);
2369
3630
  requireField(input.gameId, "gameId");
@@ -2855,13 +4116,13 @@ function previewPoolSplit(amount) {
2855
4116
  }
2856
4117
 
2857
4118
  // src/settlement.ts
2858
- var ADDRESS_RE4 = /^0x[0-9a-fA-F]{40}$/;
4119
+ var ADDRESS_RE5 = /^0x[0-9a-fA-F]{40}$/;
2859
4120
  var DEFAULT_TTL_MS = 15 * 60 * 1e3;
2860
4121
  function requireAddress3(value, field) {
2861
4122
  if (typeof value !== "string" || value.trim() === "") {
2862
4123
  throw new MissingFieldError(field);
2863
4124
  }
2864
- if (!ADDRESS_RE4.test(value)) {
4125
+ if (!ADDRESS_RE5.test(value)) {
2865
4126
  throw new ConfigError(`${field} must be a 0x-prefixed 20-byte address, got: ${JSON.stringify(value)}`, {
2866
4127
  field,
2867
4128
  value
@@ -2950,6 +4211,7 @@ function isX402PayloadAuthorization(auth) {
2950
4211
  exports.AlreadyEnteredError = AlreadyEnteredError;
2951
4212
  exports.ApiError = ApiError;
2952
4213
  exports.AuthError = AuthError;
4214
+ exports.C1_ENTER_SPLIT_MICRO = C1_ENTER_SPLIT_MICRO;
2953
4215
  exports.CHAIN_ID = CHAIN_ID;
2954
4216
  exports.ConfigError = ConfigError;
2955
4217
  exports.DEFAULT_API_BASE_URL = DEFAULT_API_BASE_URL;
@@ -2958,23 +4220,35 @@ exports.InvalidAmountError = InvalidAmountError;
2958
4220
  exports.MICRO_PER_USDC = MICRO_PER_USDC;
2959
4221
  exports.MissingFieldError = MissingFieldError;
2960
4222
  exports.NothingToWithdrawError = NothingToWithdrawError;
4223
+ exports.PLAYMOS_FEE_SINK_DEFAULT = PLAYMOS_FEE_SINK_DEFAULT;
2961
4224
  exports.PaymentFailedError = PaymentFailedError;
2962
4225
  exports.PayoutError = PayoutError;
2963
4226
  exports.Playmos = Playmos;
2964
4227
  exports.PlaymosError = PlaymosError;
4228
+ exports.RETIRED_PLAYMOS_FEE_SINK = RETIRED_PLAYMOS_FEE_SINK;
2965
4229
  exports.USDC_ADDRESS = USDC_ADDRESS;
2966
4230
  exports.USDC_DECIMALS = USDC_DECIMALS;
2967
4231
  exports.WalletConnectionError = WalletConnectionError;
2968
4232
  exports.WalletTimeoutError = WalletTimeoutError;
4233
+ exports.buildEpochClaimRefundCall = buildEpochClaimRefundCall;
4234
+ exports.buildEpochEntryCalls = buildEpochEntryCalls;
4235
+ exports.buildEpochExecuteSettlementCall = buildEpochExecuteSettlementCall;
4236
+ exports.buildEpochWithdrawCall = buildEpochWithdrawCall;
2969
4237
  exports.clientRuntimeSignals = clientRuntimeSignals;
2970
4238
  exports.computeIapSplit = computeIapSplit;
2971
4239
  exports.computePayout = computePayout;
2972
4240
  exports.computePoolSplit = computePoolSplit;
4241
+ exports.createEpochsApi = createEpochsApi;
2973
4242
  exports.createPaymentRequirement = createPaymentRequirement;
2974
4243
  exports.createX402Challenge = createX402Challenge;
2975
4244
  exports.decodePaymentHeader = decodePaymentHeader;
4245
+ exports.derivedEpochId = derivedEpochId;
4246
+ exports.encodeEpochPoolConstructorArgs = encodeEpochPoolConstructorArgs;
2976
4247
  exports.encodePaymentHeader = encodePaymentHeader;
4248
+ exports.epochPayableMicro = epochPayableMicro;
4249
+ exports.epochPoolProofMessage = epochPoolProofMessage;
2977
4250
  exports.formatMicroToUsd = formatMicroToUsd;
4251
+ exports.identityToBytes32 = identityToBytes32;
2978
4252
  exports.isClientRuntime = isClientRuntime;
2979
4253
  exports.isWalletSignatureAuthorization = isWalletSignatureAuthorization;
2980
4254
  exports.isX402PayloadAuthorization = isX402PayloadAuthorization;
@@ -2982,6 +4256,7 @@ exports.networkToCaip2 = networkToCaip2;
2982
4256
  exports.parsePaymentRequirement = parsePaymentRequirement;
2983
4257
  exports.parseUsdToMicro = parseUsdToMicro;
2984
4258
  exports.prefixedId = prefixedId;
4259
+ exports.prepareStudioPoolLocal = prepareStudioPoolLocal;
2985
4260
  exports.previewEscrowFee = previewEscrowFee;
2986
4261
  exports.previewIapSplit = previewIapSplit;
2987
4262
  exports.previewMarketplaceSplit = previewMarketplaceSplit;
@@ -2989,6 +4264,8 @@ exports.previewPoolSplit = previewPoolSplit;
2989
4264
  exports.previewTransferSplit = previewTransferSplit;
2990
4265
  exports.resolveEnv = resolveEnv;
2991
4266
  exports.serializePaymentRequirement = serializePaymentRequirement;
4267
+ exports.seriesToBytes32 = seriesToBytes32;
4268
+ exports.settlementTypedData = settlementTypedData;
2992
4269
  exports.toX402PaymentRequired = toX402PaymentRequired;
2993
4270
  exports.ulid = ulid;
2994
4271
  exports.validateX402ChallengeInput = validateX402ChallengeInput;