Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 | 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 67x 67x 1x 66x 62x 61x 1x 1x 62x 62x 330x 19x 19x 18x 18x 17x 17x 17x 17x 17x 51x 17x 18x 18x 18x 18x 18x 18x 1x 1x 17x 18x 18x 18x 80x 5x 5x 18x 18x 17x 17x 17x 17x 17x 2x 15x 15x 15x 17x 17x 17x 18x 17x 1x 29x 29x 29x 8x 21x 14x 14x 14x 14x 1x 13x 13x 1x 12x 13x 13x 9x 19x 19x 19x 17x 17x 17x 17x 16x 16x 16x 16x 16x 16x 16x 2x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 14x 14x 14x 14x 14x 14x 1x 1x 14x 14x 2x 2x 339x 2x 5x 5x 1x 1x 1x 2x 2x 337x 37x 37x 37x 37x 37x 91x 74x 37x 17x 17x 17x 51x 17x 34x 34x 337x 339x 339x 603x 201x 603x 201x 201x 201x 603x 402x 201x 201x 603x 201x 402x 892x 339x 339x 339x 339x 339x 362x 362x 339x 339x 339x 9x 29x 29x 29x 29x 29x 29x 4x 25x 23x 23x 23x 23x 1x 22x 22x 21x 21x 21x 19x 46x 19x 46x 19x 18x 45x 18x 18x 18x 18x 18x 18x 18x 11x 4x 3x 3x 3x 18x 339x 339x 339x 339x 339x 339x 5x 334x 18x 18x 18x 18x 18x 342x 18x 18x 24x 24x 18x 18x 24x 224x 24x 24x 24x 24x 18x 18x 18x 18x 18x 342x 1x 18x 18x 18x 309x 7x 6x 1x 18x 342x 18x 2x 2x 9x 16x 16x 16x 16x 16x 16x 2x 14x 1x 13x 1x 12x 11x 11x 11x 11x 11x 10x 1x 9x 8x 8x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 5x 6x 6x 6x 6x 2x 2x 2x 2x 2x 6x 6x 6x 6x 5x 6x 6x 1x 1x 9x 12x 12x 12x 12x 12x 12x 1x 11x 1x 10x 9x 9x 9x 9x 8x 7x 7x 2x 2x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 4x 4x 4x 4x 3x 4x 4x 1x 1x 9x 17x 17x 17x 17x 17x 17x 2x 15x 1x 14x 1x 13x 12x 11x 10x 10x 10x 9x 9x 9x 9x 9x 9x 3x 3x 3x 1x 6x 6x 7x 7x 7x 7x 7x 9x 9x 7x 6x 7x 7x 7x 7x 2x 2x 4x 4x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 1x 1x 9x 12x 12x 12x 12x 12x 11x 10x 9x 9x 9x 8x 7x 7x 2x 2x 5x 5x 5x 4x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 3x 1x 1x 9x 9x 9x 9x 9x 9x 3x 6x 5x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 9x 15x 15x 15x 15x 15x 2x 13x 12x 1x 1x 11x 11x 4x 4x 2x 2x 2x 2x 7x 7x 9x 9x 9x 9x 9x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 1x 1x 9x 4x 4x 4x 3x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 9x 5x 5x 5x 4x 4x 4x 3x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 9x 7x 7x 6x 6x 6x 6x 3x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 12x 12x 12x 11x 9x 9x 1x 1x 9x 5x 5x 5x 5x 5x 4x 1x 4x 4x 13x 4x 1x 1x 9x 4x 4x 4x 1x 3x 3x 2x 1x 1x 9x 3x 3x 2x 2x 1x 1x 9x 4x 4x 3x 3x 3x 1x 1x 9x 205x 205x 9x | /**
* Economy routes — daily rewards, gacha, gift sending, bean redemption, purchases.
*
* All operations use Firestore as the sole database.
*
* POST /api/economy/daily-reward → Claim daily login reward
* POST /api/economy/gacha → Pull gacha (1, 10, or 100)
* POST /api/economy/gift → Send gift from backpack
* POST /api/economy/gift-direct → Buy and send gift directly
* POST /api/economy/gift-batch → Send gifts to multiple recipients
* POST /api/economy/backpack-send → Send entire backpack
* POST /api/economy/redeem-beans → Redeem beans for coins
* POST /api/economy/purchase → Validate in-app purchase
* POST /api/economy/trial-claim → Claim Super Shy trial
* POST /api/economy/trial-activate → Activate Super Shy trial
* POST /api/economy/test-coins → Add test coins (dev)
* GET /api/economy/balance → Get coin/bean balance
* GET /api/economy/transactions → Get transaction history
* GET /api/users/:uniqueId/backpack → Get user's backpack
* GET /api/users/:uniqueId/gift-wall → Get user's gift wall
* GET /api/users/:uniqueId/gift-wall/:giftId/senders → Get gift wall senders
*/
const router = require('express').Router();
const { db, FieldValue } = require('../utils/firebase');
const { generateId, now, todayStr, yesterdayStr } = require('../utils/helpers');
const { requireAdmin } = require('../middleware/auth');
const log = require('../utils/log');
const { verifyProductPurchase, verifySubscription } = require('../utils/playStore');
// ─── Constants ────────────────────────────────────────────────────
const DEFAULT_ECONOMY_CONFIG = {
beanConversionRate: 0.6,
beanRedeemBonusThreshold: 2000,
beanRedeemBonusMultiplier: 1.1,
pullCosts: { 1: 10, 10: 100, 100: 1000 },
broadcastSendThreshold: 0,
broadcastWinThreshold: 5000,
dropRateExponent: 1.5,
pitySoftStart: 80,
pityHardLimit: 120,
pitySoftMaxShift: 0.15,
pityHighValueThreshold: 5000,
dailyBase: 50,
milestoneRewards: { 7: 100, 14: 200, 30: 500, 60: 1000, 90: 2000 },
};
// ─── Helpers ──────────────────────────────────────────────────────
// In-memory cache for economy config (avoids re-reading Firestore on every request)
let cachedEconomyConfig = null;
let economyConfigCachedAt = 0;
const ECONOMY_CONFIG_TTL = 60_000; // 1 minute
async function loadEconomyConfig() {
const currentTime = Date.now();
if (cachedEconomyConfig && currentTime - economyConfigCachedAt < ECONOMY_CONFIG_TTL) {
return cachedEconomyConfig;
}
const snap = await db.doc('config/economy').get();
if (snap.exists) {
cachedEconomyConfig = { ...DEFAULT_ECONOMY_CONFIG, ...snap.data() };
} else {
// Doc doesn't exist — write defaults so the Android SDK can read it
await db.doc('config/economy').set(DEFAULT_ECONOMY_CONFIG);
cachedEconomyConfig = { ...DEFAULT_ECONOMY_CONFIG };
}
economyConfigCachedAt = currentTime;
return cachedEconomyConfig;
}
/**
* Helper to read a user field with camelCase (new) or snake_case (legacy) fallback.
*/
function userField(user, camel, snake) {
return user[camel] ?? user[snake] ?? null;
}
/**
* Add a broadcast entry and trim to last 50.
*/
async function addBroadcast(data) {
const broadcastId = generateId();
await db.doc(`broadcasts/${broadcastId}`).set({
id: broadcastId,
type: data.type,
senderName: data.senderName,
senderPhotoUrl: data.senderPhotoUrl || null,
recipientName: data.recipientName || '',
giftName: data.giftName,
giftIconUrl: data.giftIconUrl || '',
giftCoinValue: data.giftCoinValue,
quantity: data.quantity || 1,
timestamp: now(),
});
// Trim old broadcasts (keep last 50) — query oldest beyond 50
const oldSnap = await db
.collection('broadcasts')
.orderBy('timestamp', 'desc')
.offset(50)
.limit(100)
.get();
if (!oldSnap.empty) {
// Chunk deletes into batches of 500
const docs = oldSnap.docs;
for (let i = 0; i < docs.length; i += 500) {
const batch = db.batch();
const chunk = docs.slice(i, i + 500);
for (const doc of chunk) {
batch.delete(doc.ref);
}
await batch.commit();
}
}
}
/**
* Write a gift to a user's gift wall (upsert receivedCount, update senders).
*/
async function updateGiftWall(recipientId, giftId, senderId, quantity) {
const wallSnap = await db.doc(`users/${recipientId}/giftWall/${giftId}`).get();
const wallDoc = wallSnap.exists ? wallSnap.data() : null;
const currentCount = wallDoc?.receivedCount || 0;
const senders = wallDoc?.senders || [];
// Update or add sender
const existingSender = senders.find((s) => s.senderId === senderId);
if (existingSender) {
existingSender.sendCount = (existingSender.sendCount || 0) + quantity;
existingSender.lastSentAt = now();
} else {
senders.push({ senderId, sendCount: quantity, lastSentAt: now() });
}
// Sort senders by count descending, keep top 50
senders.sort((a, b) => (b.sendCount || 0) - (a.sendCount || 0));
const trimmedSenders = senders.slice(0, 50);
await db.doc(`users/${recipientId}/giftWall/${giftId}`).set({
giftId,
receivedCount: currentCount + quantity,
senders: trimmedSenders,
});
}
/**
* Write a transaction record.
*/
async function writeTransaction(userId, txId, data) {
await db.doc(`users/${userId}/transactions/${txId}`).set({
id: txId,
...data,
timestamp: data.timestamp || now(),
});
}
/**
* Write a room gift message to Firestore.
*/
async function writeRoomGiftMessage(roomId, senderId, senderName, text, giftId, giftIconUrl) {
const msgId = generateId();
await db.doc(`rooms/${roomId}/messages/${msgId}`).set({
id: msgId,
roomId,
senderId,
senderName,
text,
type: 'GIFT',
giftId: giftId || null,
giftIconUrl: giftIconUrl || '',
createdAt: now(),
});
}
/**
* Incrementally update gift rankings when a gift is sent.
* Replaces the old hourly cron job with real-time updates.
*/
async function updateGiftRankings(recipientId, giftId, quantity) {
try {
const rankSnap = await db.doc(`giftRankings/${giftId}`).get();
const rankDoc = rankSnap.exists ? rankSnap.data() : {};
const rankings = rankDoc.rankings || [];
const totalSent = (rankDoc.totalSent || 0) + quantity;
// Find or add recipient in rankings
const existing = rankings.find((r) => r.userId === recipientId);
if (existing) {
existing.count = (existing.count || 0) + quantity;
} else {
// Get recipient display info
const userSnap = await db.doc(`users/${recipientId}`).get();
const user = userSnap.exists ? userSnap.data() : {};
rankings.push({
userId: recipientId,
count: quantity,
displayName: userField(user, 'displayName', 'display_name') || '',
profilePhotoUrl: userField(user, 'profilePhotoUrl', 'profile_photo_url') || '',
});
}
// Sort by count descending, keep top 100
rankings.sort((a, b) => (b.count || 0) - (a.count || 0));
const trimmed = rankings.slice(0, 100);
// Re-assign ranks
trimmed.forEach((r, i) => {
r.rank = i + 1;
});
await db.doc(`giftRankings/${giftId}`).set({
rankings: trimmed,
totalSent,
lastUpdated: now(),
});
} catch (err) {
log.error('economy', 'Failed to update gift rankings', { error: err.message });
}
}
// ─── Shared gift helpers ─────────────────────────────────────────
/** Check block relationship between sender and recipient. Returns error string or null. */
function checkBlockRelationship(sender, recipient, senderId, recipientId) {
const senderBlocked = (sender?.blockedUserIds || []).map(String);
const recipientBlocked = (recipient?.blockedUserIds || []).map(String);
if (senderBlocked.includes(String(recipientId)) || recipientBlocked.includes(String(senderId))) {
return 'Cannot send gifts to or from blocked users';
}
return null;
}
/** Compute daily reward from config and streak. */
function computeDailyReward(config, newStreak, isSuperShy) {
const milestoneRewards = config.milestoneRewards || {};
const rawReward = milestoneRewards[String(newStreak)];
const isMilestone = String(newStreak) in milestoneRewards;
if (rawReward && typeof rawReward === 'object' && rawReward.type === 'gift') {
return {
coinReward: 0,
giftReward: { giftId: rawReward.giftId, quantity: rawReward.quantity || 1 },
isMilestone,
};
}
let coinReward;
Iif (typeof rawReward === 'number') {
coinReward = rawReward;
} else if (rawReward?.amount) {
coinReward = rawReward.amount;
} else {
coinReward = config.dailyBase;
}
if (isSuperShy) coinReward = Math.ceil(coinReward * 1.1);
return { coinReward, giftReward: null, isMilestone };
}
// ─── Routes ───────────────────────────────────────────────────────
// ── Daily reward ──
router.post('/economy/daily-reward', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const config = await loadEconomyConfig();
const today = todayStr();
const yesterday = yesterdayStr();
const userSnap = await db.doc(`users/${uniqueId}`).get();
if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
const user = userSnap.data();
const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
const isSuperShy = userField(user, 'isSuperShy', 'is_super_shy') || false;
const loginStreak = userField(user, 'loginStreak', 'login_streak') || 0;
const lastLoginDate = userField(user, 'lastLoginDate', 'last_login_date');
const lastLoginRewardDate = userField(user, 'lastLoginRewardDate', 'last_login_reward_date');
if (lastLoginRewardDate === today) {
return res.status(409).json({ error: 'Already claimed today' });
}
const newStreak = lastLoginDate === yesterday ? loginStreak + 1 : 1;
const { coinReward, giftReward, isMilestone } = computeDailyReward(
config,
newStreak,
isSuperShy,
);
const newBalance = shyCoins + coinReward;
// Update user doc
const userUpdates = {
loginStreak: newStreak,
lastLoginDate: today,
lastLoginRewardDate: today,
};
if (coinReward > 0) userUpdates.shyCoins = newBalance;
await db.doc(`users/${uniqueId}`).update(userUpdates);
// Add gift to backpack if gift reward
if (giftReward) {
const bpSnap = await db.doc(`users/${uniqueId}/backpack/${giftReward.giftId}`).get();
const currentQty = bpSnap.exists ? bpSnap.data().quantity || 0 : 0;
await db.doc(`users/${uniqueId}/backpack/${giftReward.giftId}`).set({
giftId: giftReward.giftId,
quantity: currentQty + giftReward.quantity,
lastAcquired: now(),
});
}
// Transaction record
const txId = generateId();
const milestoneSuffix = isMilestone ? ' (milestone)' : '';
const details = giftReward
? `Day ${newStreak} (milestone) — ${giftReward.quantity}x ${giftReward.giftId}`
: `Day ${newStreak}${milestoneSuffix}`;
await writeTransaction(uniqueId, txId, {
type: 'DAILY_REWARD',
amount: giftReward ? giftReward.quantity : coinReward,
currency: giftReward ? 'GIFT' : 'COINS',
balanceAfter: newBalance,
details,
});
const result = { coinsAwarded: coinReward, newStreak, isMilestone, newBalance };
if (giftReward) {
result.giftId = giftReward.giftId;
result.giftQuantity = giftReward.quantity;
}
log.info('economy', 'Daily reward claimed', {
userId: uniqueId,
coinReward,
streak: newStreak,
});
res.json(result);
} catch (err) {
log.error('economy', 'POST /economy/daily-reward failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ─── Gacha helpers ───────────────────────────────────────────────
/** Apply hard or soft pity adjustments to weights. Returns true if hard pity was triggered. */
function applyPitySystem(weights, pity, config, winnableGifts, highValueThreshold) {
if (pity >= config.pityHardLimit) {
// Hard pity: zero out low-value gifts
for (let j = 0; j < winnableGifts.length; j++) {
if (winnableGifts[j].coinValue < highValueThreshold) weights[j] = 0;
}
if (weights.every((w) => w === 0)) {
// Guarantee the most expensive gift
let bestIdx = 0;
for (let j = 1; j < winnableGifts.length; j++) {
Eif (winnableGifts[j].coinValue > winnableGifts[bestIdx].coinValue) bestIdx = j;
}
for (let j = 0; j < weights.length; j++) weights[j] = j === bestIdx ? 1 : 0;
}
return true;
}
if (pity >= config.pitySoftStart) {
const progress = (pity - config.pitySoftStart) / (config.pityHardLimit - config.pitySoftStart);
const shift = config.pitySoftMaxShift * progress;
let lowTotal = 0,
highTotal = 0;
for (let j = 0; j < winnableGifts.length; j++) {
if (winnableGifts[j].coinValue >= highValueThreshold) highTotal += weights[j];
else lowTotal += weights[j];
}
if (lowTotal > 0 && highTotal > 0) {
const totalWeight = lowTotal + highTotal;
const shiftAmount = shift * totalWeight;
for (let j = 0; j < winnableGifts.length; j++) {
if (winnableGifts[j].coinValue >= highValueThreshold) {
weights[j] += shiftAmount * (weights[j] / highTotal);
} else {
weights[j] -= shiftAmount * (weights[j] / lowTotal);
Iif (weights[j] < 0) weights[j] = 0;
}
}
}
}
return false;
}
/** Apply luck-based weight adjustments (shift weight from cheapest to others). */
function applyLuckBoost(weights, luck, winnableGifts) {
const luckBoost = (luck / 100) * 0.05;
if (luckBoost <= 0) return;
const totalWeight = weights.reduce((s, w) => s + w, 0);
const shiftAmount = luckBoost * totalWeight;
const minValue = Math.min(...winnableGifts.map((g) => g.coinValue));
let cheapTotal = 0,
expensiveTotal = 0;
for (let j = 0; j < winnableGifts.length; j++) {
if (winnableGifts[j].coinValue === minValue) cheapTotal += weights[j];
else expensiveTotal += weights[j];
}
Iif (cheapTotal <= shiftAmount || expensiveTotal <= 0) return;
for (let j = 0; j < winnableGifts.length; j++) {
if (winnableGifts[j].coinValue === minValue) {
weights[j] -= shiftAmount * (weights[j] / cheapTotal);
} else {
weights[j] += shiftAmount * (weights[j] / expensiveTotal);
}
}
}
/** Roll a weighted random selection from the gift pool. Returns { gift, fallback }. */
function rollWeightedGift(weights, winnableGifts) {
const total = weights.reduce((s, w) => s + w, 0);
Iif (total <= 0) return { gift: winnableGifts[0], fallback: true };
const roll = Math.random() * total;
let cumulative = 0,
selectedIndex = 0;
for (let j = 0; j < weights.length; j++) {
cumulative += weights[j];
if (roll <= cumulative) {
selectedIndex = j;
break;
}
}
return { gift: winnableGifts[selectedIndex], fallback: false };
}
// ── Gacha ──
router.post('/economy/gacha', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const pullCount = body?.pullCount;
const expectedCost = body?.expectedCost;
if (![1, 10, 100].includes(pullCount)) {
return res.status(400).json({ error: 'pullCount must be 1, 10, or 100' });
}
const config = await loadEconomyConfig();
const pullCosts = config.pullCosts || { 1: 10, 10: 100, 100: 1000 };
const cost = pullCosts[String(pullCount)];
Iif (!cost) return res.status(400).json({ error: 'Invalid pull count' });
// Price validation
if (expectedCost !== null && expectedCost !== undefined && expectedCost !== cost) {
return res.json({
priceChanged: true,
currentPullCosts: pullCosts,
gifts: [],
coinsSpent: 0,
newBalance: 0,
newPityCounter: 0,
newLuckScore: 0,
});
}
const userSnap = await db.doc(`users/${uniqueId}`).get();
if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
const user = userSnap.data();
const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
if (shyCoins < cost) return res.status(402).json({ error: 'Insufficient coins' });
// Load winnable gifts
const giftsSnap = await db
.collection('gifts')
.where('showOnWheel', '==', true)
.orderBy('order')
.limit(16)
.get();
const allGifts = giftsSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
Iif (allGifts.length === 0) return res.status(500).json({ error: 'No winnable gifts' });
// Filter to gifts with coinValue > 0
const winnableGifts = allGifts.filter((g) => (g.coinValue || 0) > 0);
if (winnableGifts.length === 0) return res.status(500).json({ error: 'No winnable gifts' });
// Compute base weights
const exponent = config.dropRateExponent;
const baseWeights = winnableGifts.map((g) => 1 / Math.pow(g.coinValue, exponent));
let pity = userField(user, 'pityCounter', 'pity_counter') || 0;
let luck = userField(user, 'luckScore', 'luck_score') || 0;
const highValueThreshold = config.pityHighValueThreshold;
const results = [];
// Admin-guaranteed first pull
let guaranteedFirstPull = false;
const guaranteedGiftId = userField(
user,
'guaranteedNextPullGiftId',
'guaranteed_next_pull_gift_id',
);
if (guaranteedGiftId) {
const guaranteedGift = winnableGifts.find((g) => g.id === guaranteedGiftId);
if (guaranteedGift) {
results.push(guaranteedGift);
guaranteedFirstPull = true;
pity = guaranteedGift.coinValue >= highValueThreshold ? 0 : pity + 1;
}
}
for (let i = guaranteedFirstPull ? 1 : 0; i < pullCount; i++) {
const weights = [...baseWeights];
const hardPityTriggered = applyPitySystem(
weights,
pity,
config,
winnableGifts,
highValueThreshold,
);
applyLuckBoost(weights, luck, winnableGifts);
const { gift, fallback } = rollWeightedGift(weights, winnableGifts);
results.push(gift);
if (fallback || hardPityTriggered || gift.coinValue >= highValueThreshold) {
pity = hardPityTriggered || gift.coinValue >= highValueThreshold ? 0 : pity + 1;
} else {
pity = pity + 1;
}
}
if (pullCount === 100) luck = Math.min(100, luck + 2);
const newBalance = shyCoins - cost;
const timestamp = now();
// ── Aggregate duplicate gifts so each backpack doc is written once ──
const giftCounts = {};
for (const gift of results) {
giftCounts[gift.id] = (giftCounts[gift.id] || 0) + 1;
}
const uniqueGiftIds = Object.keys(giftCounts);
// Fetch existing backpack docs in parallel
const existingDocs = await Promise.all(
uniqueGiftIds.map(async (gid) => {
const snap = await db.doc(`users/${uniqueId}/backpack/${gid}`).get();
return snap.exists ? snap.data() : null;
}),
);
// Build batch writes for backpack + user update in one atomic operation
const batch = db.batch();
for (let i = 0; i < uniqueGiftIds.length; i++) {
const gid = uniqueGiftIds[i];
const gift = results.find((g) => g.id === gid);
const bpDoc = existingDocs[i];
const currentQty = bpDoc?.quantity || 0;
const expiresAt = gift.expiresAfterDays
? timestamp + gift.expiresAfterDays * 86400000
: bpDoc?.expiresAt || null;
batch.set(
db.doc(`users/${uniqueId}/backpack/${gid}`),
{
giftId: gid,
quantity: currentQty + giftCounts[gid],
lastAcquired: timestamp,
expiresAt,
giftName: gift.name,
coinValue: gift.coinValue,
iconUrl: gift.iconUrl || gift.icon_url || '',
},
{ merge: true },
);
}
// Include coin deduction in the same batch
batch.update(db.doc(`users/${uniqueId}`), {
shyCoins: newBalance,
pityCounter: pity,
luckScore: luck,
guaranteedNextPullGiftId: null,
});
// Execute atomically — all or nothing
await batch.commit();
// Transaction record (best-effort — coins already deducted)
try {
const gachaTxId = generateId();
await writeTransaction(uniqueId, gachaTxId, {
type: 'GACHA_PULL',
amount: -cost,
currency: 'COINS',
balanceAfter: newBalance,
pullCount,
details: results.map((g) => g.name).join(', '),
guaranteed: !!guaranteedFirstPull,
});
} catch (err) {
log.error('economy', 'Failed to write gacha transaction', { uniqueId, error: err.message });
}
// Broadcast qualifying wins (best-effort)
try {
const winThreshold = config.broadcastWinThreshold;
for (const gift of results) {
if (gift.coinValue >= winThreshold) {
await addBroadcast({
type: 'GACHA_WIN',
senderName: userField(user, 'displayName', 'display_name') || '',
senderPhotoUrl: userField(user, 'profilePhotoUrl', 'profile_photo_url'),
recipientName: '',
giftName: gift.name,
giftIconUrl: gift.iconUrl || gift.icon_url || '',
giftCoinValue: gift.coinValue,
});
break; // one broadcast per pull session
}
}
} catch (err) {
log.error('economy', 'Failed to broadcast gacha win', { uniqueId, error: err.message });
}
res.json({
gifts: results.map((g) => ({
giftId: g.id,
giftName: g.name,
coinValue: g.coinValue,
iconUrl: g.iconUrl || '',
})),
coinsSpent: cost,
newBalance,
newPityCounter: pity,
newLuckScore: luck,
currentPullCosts: pullCosts,
});
log.info('economy', `Gacha pull x${pullCount}`, { userId: uniqueId, cost, newBalance });
} catch (err) {
log.error('economy', 'POST /economy/gacha failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Send gift from backpack ──
router.post('/economy/gift', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const { recipientId, giftId } = body || {};
const quantity = Math.max(1, Math.min(9999, Number.parseInt(body?.quantity, 10) || 1));
if (!recipientId || !giftId)
return res.status(400).json({ error: 'recipientId and giftId required' });
if (giftId === 'super_shy_trial')
return res.status(400).json({ error: 'Trial items cannot be transferred' });
if (uniqueId === recipientId)
return res.status(400).json({ error: 'Cannot send gift to yourself' });
const [giftSnap, bpSnap, senderSnap, recipientSnap] = await Promise.all([
db.doc(`gifts/${giftId}`).get(),
db.doc(`users/${uniqueId}/backpack/${giftId}`).get(),
db.doc(`users/${uniqueId}`).get(),
db.doc(`users/${recipientId}`).get(),
]);
const gift = giftSnap.exists ? { id: giftSnap.id, ...giftSnap.data() } : null;
const bpItem = bpSnap.exists ? bpSnap.data() : null;
const sender = senderSnap.exists ? senderSnap.data() : null;
const recipient = recipientSnap.exists ? recipientSnap.data() : null;
if (!gift) return res.status(404).json({ error: 'Gift not found' });
if (!bpItem || (bpItem.quantity || 0) < quantity)
return res.status(402).json({ error: 'Insufficient items in backpack' });
if (!recipient) return res.status(404).json({ error: 'Recipient not found' });
const blockError = checkBlockRelationship(sender, recipient, uniqueId, recipientId);
if (blockError) {
log.warn('economy', 'Gift blocked: sender/recipient blocked', {
senderUniqueId: uniqueId,
recipientUniqueId: recipientId,
});
return res.status(403).json({ error: blockError });
}
const config = await loadEconomyConfig();
const coinValue = gift.coinValue || gift.coin_value || 0;
const beanReward = Math.floor(coinValue * config.beanConversionRate * quantity);
const senderCoins = userField(sender, 'shyCoins', 'shy_coins') || 0;
const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
const timestamp = now();
// Decrement backpack atomically via transaction to prevent race conditions
const bpRef = db.doc(`users/${uniqueId}/backpack/${giftId}`);
await db.runTransaction(async (t) => {
const snap = await t.get(bpRef);
const qty = snap.exists ? snap.data().quantity || 0 : 0;
Iif (qty < quantity) throw new Error('Insufficient items in backpack');
const newQty = qty - quantity;
if (newQty <= 0) {
t.delete(bpRef);
} else {
t.update(bpRef, { quantity: newQty });
}
});
// Update recipient gift wall
await updateGiftWall(recipientId, giftId, uniqueId, quantity);
// Credit beans (atomic increment to avoid race conditions)
await db.doc(`users/${recipientId}`).update({ shyBeans: FieldValue.increment(beanReward) });
// Room message if sender is in a room
const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
if (currentRoomId) {
const sName = userField(sender, 'displayName', 'display_name') || 'Someone';
const rName = userField(recipient, 'displayName', 'display_name') || 'Someone';
const qtyLabel = quantity > 1 ? `${quantity}x ` : '';
await writeRoomGiftMessage(
currentRoomId,
uniqueId,
sName,
`${sName} sent ${qtyLabel}${gift.name} to ${rName}`,
giftId,
gift.iconUrl || gift.icon_url || '',
);
// Update last gift event on room doc
await db.doc(`rooms/${currentRoomId}`).update({
lastGiftEvent: {
senderId: uniqueId,
senderName: sName,
recipientId,
recipientName: rName,
giftId,
giftName: gift.name,
coinValue,
quantity,
timestamp,
},
});
}
// Transaction records
const giftSentTxId = generateId();
const giftReceivedTxId = generateId();
await Promise.all([
writeTransaction(uniqueId, giftSentTxId, {
type: 'GIFT_SENT',
amount: -quantity,
currency: 'COINS',
balanceAfter: senderCoins,
giftId,
giftName: gift.name,
recipientId,
quantity,
timestamp,
}),
writeTransaction(recipientId, giftReceivedTxId, {
type: 'GIFT_RECEIVED',
amount: beanReward,
currency: 'BEANS',
balanceAfter: recipientBeans + beanReward,
giftId,
giftName: gift.name,
senderId: uniqueId,
quantity,
timestamp,
}),
]);
// Broadcast
if (coinValue >= config.broadcastSendThreshold) {
await addBroadcast({
type: 'GIFT_SEND',
senderName: userField(sender, 'displayName', 'display_name') || '',
senderPhotoUrl: null,
recipientName: userField(recipient, 'displayName', 'display_name') || '',
giftName: gift.name,
giftIconUrl: gift.iconUrl || gift.icon_url || '',
giftCoinValue: coinValue,
quantity,
});
}
// Update gift rankings incrementally
await updateGiftRankings(recipientId, giftId, quantity);
res.json({ success: true, beanReward, giftName: gift.name, quantity });
} catch (err) {
log.error('economy', 'POST /economy/gift failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Send gift directly (buy + send) ──
router.post('/economy/gift-direct', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const { recipientId, giftId } = body || {};
const quantity = Math.max(1, Math.min(9999, Number.parseInt(body?.quantity, 10) || 1));
if (!recipientId || !giftId)
return res.status(400).json({ error: 'recipientId and giftId required' });
if (uniqueId === recipientId)
return res.status(400).json({ error: 'Cannot send gift to yourself' });
const [giftSnap, senderSnap, recipientSnap] = await Promise.all([
db.doc(`gifts/${giftId}`).get(),
db.doc(`users/${uniqueId}`).get(),
db.doc(`users/${recipientId}`).get(),
]);
const gift = giftSnap.exists ? { id: giftSnap.id, ...giftSnap.data() } : null;
const sender = senderSnap.exists ? senderSnap.data() : null;
const recipient = recipientSnap.exists ? recipientSnap.data() : null;
if (!gift) return res.status(404).json({ error: 'Gift not found' });
if (!recipient) return res.status(404).json({ error: 'Recipient not found' });
const blockError = checkBlockRelationship(sender, recipient, uniqueId, recipientId);
if (blockError) {
log.warn('economy', 'Gift blocked: sender/recipient blocked', {
senderUniqueId: uniqueId,
recipientUniqueId: recipientId,
});
return res.status(403).json({ error: blockError });
}
const coinValue = gift.coinValue || gift.coin_value || 0;
const totalCost = coinValue * quantity;
const senderCoins = userField(sender, 'shyCoins', 'shy_coins') || 0;
if (senderCoins < totalCost) return res.status(402).json({ error: 'Insufficient coins' });
const config = await loadEconomyConfig();
const beanReward = Math.floor(coinValue * config.beanConversionRate * quantity);
const newSenderCoins = senderCoins - totalCost;
const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
const timestamp = now();
// Deduct coins (atomic)
await db.doc(`users/${uniqueId}`).update({ shyCoins: FieldValue.increment(-totalCost) });
// Gift wall
await updateGiftWall(recipientId, giftId, uniqueId, quantity);
// Beans (atomic)
await db.doc(`users/${recipientId}`).update({ shyBeans: FieldValue.increment(beanReward) });
// Room message
const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
if (currentRoomId) {
const sName = userField(sender, 'displayName', 'display_name') || 'Someone';
const rName = userField(recipient, 'displayName', 'display_name') || 'Someone';
const qtyLabel = quantity > 1 ? `${quantity}x ` : '';
await writeRoomGiftMessage(
currentRoomId,
uniqueId,
sName,
`${sName} sent ${qtyLabel}${gift.name} to ${rName}`,
giftId,
gift.iconUrl || gift.icon_url || '',
);
}
// Transactions
const directSentTxId = generateId();
const directReceivedTxId = generateId();
await Promise.all([
writeTransaction(uniqueId, directSentTxId, {
type: 'GIFT_SENT',
amount: -totalCost,
currency: 'COINS',
balanceAfter: newSenderCoins,
giftId,
giftName: gift.name,
recipientId,
quantity,
details: `Sent ${quantity > 1 ? quantity + 'x ' : ''}${gift.name} directly (${totalCost} coins)`,
timestamp,
}),
writeTransaction(recipientId, directReceivedTxId, {
type: 'GIFT_RECEIVED',
amount: beanReward,
currency: 'BEANS',
balanceAfter: recipientBeans + beanReward,
giftId,
giftName: gift.name,
senderId: uniqueId,
quantity,
timestamp,
}),
]);
if (coinValue >= config.broadcastSendThreshold) {
await addBroadcast({
type: 'GIFT_SEND',
senderName: userField(sender, 'displayName', 'display_name') || '',
recipientName: userField(recipient, 'displayName', 'display_name') || '',
giftName: gift.name,
giftIconUrl: gift.iconUrl || gift.icon_url || '',
giftCoinValue: coinValue,
quantity,
});
}
// Update gift rankings incrementally
await updateGiftRankings(recipientId, giftId, quantity);
res.json({ success: true, beanReward, giftName: gift.name, coinsSpent: totalCost, quantity });
} catch (err) {
log.error('economy', 'POST /economy/gift-direct failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Send gifts to multiple recipients (batch) ──
router.post('/economy/gift-batch', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const { recipientIds, giftId, fromBackpack } = body || {};
const quantity = Math.max(1, Math.min(9999, Number.parseInt(body?.quantity, 10) || 1));
if (!recipientIds || !Array.isArray(recipientIds) || recipientIds.length === 0 || !giftId) {
return res.status(400).json({ error: 'recipientIds array and giftId required' });
}
if (giftId === 'super_shy_trial')
return res.status(400).json({ error: 'Trial items cannot be transferred' });
if (recipientIds.includes(uniqueId))
return res.status(400).json({ error: 'Cannot send gift to yourself' });
if (recipientIds.length > 50) return res.status(400).json({ error: 'Max 50 recipients' });
const giftSnap = await db.doc(`gifts/${giftId}`).get();
if (!giftSnap.exists) return res.status(404).json({ error: 'Gift not found' });
const gift = { id: giftSnap.id, ...giftSnap.data() };
const senderSnap = await db.doc(`users/${uniqueId}`).get();
if (!senderSnap.exists) return res.status(404).json({ error: 'Sender not found' });
const sender = senderSnap.data();
const coinValue = gift.coinValue || gift.coin_value || 0;
const totalQty = quantity * recipientIds.length;
const senderCoins = userField(sender, 'shyCoins', 'shy_coins') || 0;
let bpItem = null;
if (fromBackpack) {
const bpSnap = await db.doc(`users/${uniqueId}/backpack/${giftId}`).get();
bpItem = bpSnap.exists ? bpSnap.data() : null;
if (!bpItem || (bpItem.quantity || 0) < totalQty)
return res.status(402).json({ error: 'Insufficient items in backpack' });
} else {
const totalCost = coinValue * totalQty;
if (senderCoins < totalCost) return res.status(402).json({ error: 'Insufficient coins' });
}
const config = await loadEconomyConfig();
const timestamp = now();
// Debit sender and credit all recipients in a single transaction
// to prevent partial failure (sender debited but recipients not credited)
const bpRef = fromBackpack ? db.doc(`users/${uniqueId}/backpack/${giftId}`) : null;
const senderRef = db.doc(`users/${uniqueId}`);
const totalCost = coinValue * totalQty;
// Validate recipient docs exist before starting
const recipientSnaps = await Promise.all(recipientIds.map((id) => db.doc(`users/${id}`).get()));
const validRecipients = recipientIds.filter((_, i) => recipientSnaps[i].exists);
if (validRecipients.length === 0) return res.status(404).json({ error: 'No valid recipients' });
// Check block relationships — UK OSA requires blocking prevents ALL contact
for (let i = 0; i < recipientIds.length; i++) {
Iif (!recipientSnaps[i].exists) continue;
const recipientData = recipientSnaps[i].data();
const blockError = checkBlockRelationship(sender, recipientData, uniqueId, recipientIds[i]);
if (blockError) {
log.warn('economy', 'Gift blocked: sender/recipient blocked', {
senderUniqueId: uniqueId,
recipientUniqueId: recipientIds[i],
});
return res.status(403).json({ error: blockError });
}
}
// Atomic debit via transaction
await db.runTransaction(async (t) => {
if (fromBackpack) {
const snap = await t.get(bpRef);
const qty = snap.exists ? snap.data().quantity || 0 : 0;
Iif (qty < totalQty) throw new Error('Insufficient items in backpack');
const newQty = qty - totalQty;
if (newQty <= 0) {
t.delete(bpRef);
} else {
t.update(bpRef, { quantity: newQty });
}
} else {
const snap = await t.get(senderRef);
const coins = snap.exists ? userField(snap.data(), 'shyCoins', 'shy_coins') || 0 : 0;
Iif (coins < totalCost) throw new Error('Insufficient coins');
t.update(senderRef, { shyCoins: FieldValue.increment(-totalCost) });
}
});
// Credit recipients (idempotent operations — safe outside transaction)
for (let i = 0; i < recipientIds.length; i++) {
const recipientId = recipientIds[i];
Iif (!recipientSnaps[i].exists) continue;
const recipient = recipientSnaps[i].data();
const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
const beanReward = Math.floor(coinValue * config.beanConversionRate * quantity);
// Gift wall + beans (atomic) + transaction
await updateGiftWall(recipientId, giftId, uniqueId, quantity);
await updateGiftRankings(recipientId, giftId, quantity);
await db.doc(`users/${recipientId}`).update({ shyBeans: FieldValue.increment(beanReward) });
const recipientTxId = generateId();
await writeTransaction(recipientId, recipientTxId, {
type: 'GIFT_RECEIVED',
amount: beanReward,
currency: 'BEANS',
balanceAfter: recipientBeans + beanReward,
giftId,
giftName: gift.name,
senderId: uniqueId,
quantity,
timestamp,
});
}
// Sender transaction
const source = fromBackpack ? 'backpack' : 'direct';
const batchSenderTxId = generateId();
await writeTransaction(uniqueId, batchSenderTxId, {
type: 'GIFT_SENT',
amount: fromBackpack ? 0 : -(coinValue * totalQty),
currency: 'COINS',
balanceAfter: fromBackpack ? senderCoins : senderCoins - coinValue * totalQty,
giftId,
giftName: gift.name,
quantity,
details: `Batch ${source}: ${totalQty}x ${gift.name} to ${recipientIds.length} users`,
timestamp,
});
// Room message
const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
if (currentRoomId) {
const sName = userField(sender, 'displayName', 'display_name') || 'Someone';
await writeRoomGiftMessage(
currentRoomId,
uniqueId,
sName,
`${sName} sent ${totalQty}x ${gift.name} to ${recipientIds.length} people`,
giftId,
gift.iconUrl || gift.icon_url || '',
);
}
// Broadcast
Eif (coinValue >= config.broadcastSendThreshold) {
await addBroadcast({
type: 'GIFT_SEND',
senderName: userField(sender, 'displayName', 'display_name') || '',
recipientName: `${recipientIds.length} people`,
giftName: gift.name,
giftIconUrl: gift.iconUrl || gift.icon_url || '',
giftCoinValue: coinValue,
quantity: totalQty,
});
}
res.json({
success: true,
giftName: gift.name,
totalSent: totalQty,
recipientCount: recipientIds.length,
});
} catch (err) {
log.error('economy', 'POST /economy/gift-batch failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Send entire backpack ──
router.post('/economy/backpack-send', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const { recipientId } = body || {};
if (!recipientId) return res.status(400).json({ error: 'recipientId required' });
if (uniqueId === recipientId) return res.status(400).json({ error: 'Cannot send to yourself' });
const [senderSnap, recipientSnap] = await Promise.all([
db.doc(`users/${uniqueId}`).get(),
db.doc(`users/${recipientId}`).get(),
]);
const sender = senderSnap.exists ? senderSnap.data() : null;
const recipient = recipientSnap.exists ? recipientSnap.data() : null;
if (!sender) return res.status(404).json({ error: 'Sender not found' });
if (!recipient) return res.status(404).json({ error: 'Recipient not found' });
const blockError = checkBlockRelationship(sender, recipient, uniqueId, recipientId);
if (blockError) {
log.warn('economy', 'Gift blocked: sender/recipient blocked', {
senderUniqueId: uniqueId,
recipientUniqueId: recipientId,
});
return res.status(403).json({ error: blockError });
}
// Get backpack items (excluding trial items)
const backpackSnap = await db.collection(`users/${uniqueId}/backpack`).get();
const backpackItems = backpackSnap.docs.map((d) => ({ id: d.id, ...d.data() }));
const sendableItems = backpackItems.filter(
(item) => item.giftId !== 'super_shy_trial' && (item.quantity || 0) > 0,
);
if (sendableItems.length === 0) return res.status(400).json({ error: 'Backpack is empty' });
// For each backpack item, we need gift metadata. If denormalized on the bp doc, use it.
// Otherwise, look up the gift.
const config = await loadEconomyConfig();
const timestamp = now();
let totalItemsSent = 0;
let totalBeanReward = 0;
for (const item of sendableItems) {
const qty = item.quantity || 0;
totalItemsSent += qty;
// Get coin value from backpack doc or gift catalog
let coinVal = item.coinValue;
if (coinVal === null || coinVal === undefined) {
const giftDocSnap = await db.doc(`gifts/${item.giftId}`).get();
coinVal = giftDocSnap.exists ? giftDocSnap.data().coinValue || 0 : 0;
}
const beanReward = Math.floor(coinVal * config.beanConversionRate * qty);
totalBeanReward += beanReward;
// Gift wall + rankings
await updateGiftWall(recipientId, item.giftId, uniqueId, qty);
await updateGiftRankings(recipientId, item.giftId, qty);
}
// Credit beans (atomic)
await db
.doc(`users/${recipientId}`)
.update({ shyBeans: FieldValue.increment(totalBeanReward) });
// Clear sender's backpack (except trial items) — chunk into batches of 500
for (let i = 0; i < sendableItems.length; i += 500) {
const batch = db.batch();
const chunk = sendableItems.slice(i, i + 500);
for (const item of chunk) {
batch.delete(db.doc(`users/${uniqueId}/backpack/${item.giftId}`));
}
await batch.commit();
}
// Transactions
const senderCoins = userField(sender, 'shyCoins', 'shy_coins') || 0;
const recipientBeans = userField(recipient, 'shyBeans', 'shy_beans') || 0;
const bpSentTxId = generateId();
const bpReceivedTxId = generateId();
const senderName = userField(sender, 'displayName', 'display_name') || 'user';
const recipientName = userField(recipient, 'displayName', 'display_name') || 'user';
await Promise.all([
writeTransaction(uniqueId, bpSentTxId, {
type: 'BACKPACK_SENT',
amount: 0,
currency: 'ITEMS',
balanceAfter: senderCoins,
totalItemsSent,
details: `Sent entire backpack (${totalItemsSent} items) to ${recipientName}`,
timestamp,
}),
writeTransaction(recipientId, bpReceivedTxId, {
type: 'BACKPACK_RECEIVED',
amount: totalBeanReward,
currency: 'BEANS',
balanceAfter: recipientBeans + totalBeanReward,
totalItemsReceived: totalItemsSent,
details: `Received entire backpack (${totalItemsSent} items) from ${senderName}`,
timestamp,
}),
]);
// Room message
const currentRoomId = userField(sender, 'currentRoomId', 'current_room_id');
if (currentRoomId) {
await writeRoomGiftMessage(
currentRoomId,
uniqueId,
senderName,
`${senderName} sent their entire backpack (${totalItemsSent} items) to ${recipientName}`,
null,
'',
);
}
res.json({ success: true, totalItemsSent, totalBeanReward });
} catch (err) {
log.error('economy', 'POST /economy/backpack-send failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Redeem beans ──
router.post('/economy/redeem-beans', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const amount = body?.amount;
if (!amount || typeof amount !== 'number' || amount < 1) {
return res.status(400).json({ error: 'amount must be a positive number' });
}
const userSnap = await db.doc(`users/${uniqueId}`).get();
if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
const user = userSnap.data();
const shyBeans = userField(user, 'shyBeans', 'shy_beans') || 0;
const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
if (shyBeans < amount) return res.status(402).json({ error: 'Insufficient beans' });
const config = await loadEconomyConfig();
const hasBonus = amount >= config.beanRedeemBonusThreshold;
const coins = hasBonus ? Math.floor(amount * config.beanRedeemBonusMultiplier) : amount;
const newBeans = shyBeans - amount;
const newCoins = shyCoins + coins;
await db.doc(`users/${uniqueId}`).update({
shyBeans: FieldValue.increment(-amount),
shyCoins: FieldValue.increment(coins),
});
const bonusPct = Math.round((config.beanRedeemBonusMultiplier - 1) * 100);
const redeemTxId = generateId();
await writeTransaction(uniqueId, redeemTxId, {
type: 'BEAN_REDEEM',
amount: coins,
currency: 'COINS',
balanceAfter: newCoins,
details: hasBonus
? `Redeemed ${amount} beans (${bonusPct}% bonus)`
: `Redeemed ${amount} beans`,
});
res.json({ coinsReceived: coins, newCoinBalance: newCoins, newBeanBalance: newBeans });
} catch (err) {
log.error('economy', 'POST /economy/redeem-beans failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Validate purchase ──
router.post('/economy/purchase', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const body = req.body;
const { productId, purchaseToken, isSubscription } = body || {};
if (!productId || !purchaseToken)
return res.status(400).json({ error: 'productId and purchaseToken required' });
// Check for duplicate purchase token to prevent replay attacks
const existingSnap = await db
.collection('purchaseReceipts')
.where('purchaseToken', '==', purchaseToken)
.limit(1)
.get();
if (!existingSnap.empty) {
log.warn('economy', 'Duplicate purchase token rejected', { userId: uniqueId, productId });
return res.status(409).json({ error: 'Purchase already processed' });
}
// Verify purchase with Google Play
const packageName = 'com.shyden.shytalk';
let verification;
if (process.env.NODE_ENV === 'production') {
try {
if (isSubscription) {
verification = await verifySubscription(packageName, productId, purchaseToken);
} else {
verification = await verifyProductPurchase(packageName, productId, purchaseToken);
}
} catch (verifyErr) {
log.warn('economy', 'Purchase verification rejected', {
userId: uniqueId,
productId,
isSubscription: !!isSubscription,
error: verifyErr.message,
});
return res.status(403).json({ error: 'Purchase verification failed' });
}
} else {
log.warn('economy', 'Skipping purchase verification in non-production environment', {
userId: uniqueId,
productId,
isSubscription: !!isSubscription,
});
verification = { orderId: 'dev-unverified' };
}
const orderId = verification.orderId || verification.latestOrderId || null;
// Store receipt for audit trail
const receiptId = generateId();
await db.doc(`purchaseReceipts/${receiptId}`).set({
userId: uniqueId,
productId,
purchaseToken,
isSubscription: !!isSubscription,
createdAt: now(),
verified: true,
orderId,
});
const timestamp = now();
if (isSubscription) {
const tierMap = {
super_shy_monthly: { tier: 'monthly', days: 30 },
super_shy_yearly: { tier: 'yearly', days: 365 },
super_shy_lifetime: { tier: 'lifetime', days: null },
};
const sub = tierMap[productId];
if (!sub) return res.status(400).json({ error: 'Unknown subscription product' });
const expiry = sub.days ? timestamp + sub.days * 86400000 : null;
await db.doc(`users/${uniqueId}`).update({
isSuperShy: true,
superShyExpiry: expiry,
superShyTier: sub.tier,
});
const subTxId = generateId();
await writeTransaction(uniqueId, subTxId, {
type: 'SUBSCRIPTION',
amount: 0,
currency: 'COINS',
balanceAfter: 0,
details: `Super Shy ${sub.tier}`,
timestamp,
});
return res.json({ success: true, tier: sub.tier });
}
// Coin package
const pkgSnap = await db
.collection('coinPackages')
.where('productId', '==', productId)
.limit(1)
.get();
const pkg = pkgSnap.empty ? null : { id: pkgSnap.docs[0].id, ...pkgSnap.docs[0].data() };
if (!pkg) return res.status(404).json({ error: 'Unknown coin package' });
const totalCoins = (pkg.coins || 0) + (pkg.bonusCoins || 0);
const userSnap = await db.doc(`users/${uniqueId}`).get();
if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
const user = userSnap.data();
const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
await db.doc(`users/${uniqueId}`).update({ shyCoins: FieldValue.increment(totalCoins) });
const newBalance = shyCoins + totalCoins;
const purchaseTxId = generateId();
await writeTransaction(uniqueId, purchaseTxId, {
type: 'PURCHASE',
amount: totalCoins,
currency: 'COINS',
balanceAfter: newBalance,
details: `${pkg.coins} + ${pkg.bonusCoins || 0} bonus coins`,
timestamp,
});
res.json({ success: true, coinsAdded: totalCoins, newBalance });
} catch (err) {
log.error('economy', 'POST /economy/purchase failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Super Shy trial claim ──
router.post('/economy/trial-claim', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const userSnap = await db.doc(`users/${uniqueId}`).get();
if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
const user = userSnap.data();
const hasClaimed = userField(user, 'hasClaimedSuperShyTrial', 'has_claimed_super_shy_trial');
if (hasClaimed) return res.status(409).json({ error: 'Trial already claimed' });
const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
await db.doc(`users/${uniqueId}`).update({ hasClaimedSuperShyTrial: true });
// Add trial item to backpack
await db.doc(`users/${uniqueId}/backpack/super_shy_trial`).set({
giftId: 'super_shy_trial',
quantity: 1,
giftName: 'Super Shy Trial',
});
const trialClaimTxId = generateId();
await writeTransaction(uniqueId, trialClaimTxId, {
type: 'TRIAL_CLAIM',
amount: 0,
currency: 'COINS',
balanceAfter: shyCoins,
details: 'Claimed 30 days of Super Shy',
});
res.json({ success: true });
} catch (err) {
log.error('economy', 'POST /economy/trial-claim failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Super Shy trial activate ──
router.post('/economy/trial-activate', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const [userSnap, bpSnap] = await Promise.all([
db.doc(`users/${uniqueId}`).get(),
db.doc(`users/${uniqueId}/backpack/super_shy_trial`).get(),
]);
const user = userSnap.exists ? userSnap.data() : null;
const bpItem = bpSnap.exists ? bpSnap.data() : null;
if (!user) return res.status(404).json({ error: 'User not found' });
if (!bpItem || (bpItem.quantity || 0) < 1)
return res.status(402).json({ error: 'No trial item in backpack' });
const timestamp = now();
const thirtyDays = 30 * 24 * 60 * 60 * 1000;
const currentExpiry = userField(user, 'superShyExpiry', 'super_shy_expiry') || 0;
const baseTime = Math.max(currentExpiry, timestamp);
const newExpiry = baseTime + thirtyDays;
const currentTier = userField(user, 'superShyTier', 'super_shy_tier');
const newTier = currentTier && currentTier !== 'trial' ? currentTier : 'trial';
// Remove trial from backpack and activate
await db.doc(`users/${uniqueId}/backpack/super_shy_trial`).delete();
await db.doc(`users/${uniqueId}`).update({
isSuperShy: true,
superShyExpiry: newExpiry,
superShyTier: newTier,
});
const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
const trialActivateTxId = generateId();
await writeTransaction(uniqueId, trialActivateTxId, {
type: 'TRIAL_ACTIVATE',
amount: 0,
currency: 'COINS',
balanceAfter: shyCoins,
details: 'Activated 30 days of Super Shy',
timestamp,
});
res.json({ success: true, newTier, newExpiry });
} catch (err) {
log.error('economy', 'POST /economy/trial-activate failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Test coins (admin only) ──
router.post('/economy/test-coins', async (req, res) => {
try {
if (requireAdmin(req, res)) return;
const uniqueId = req.auth.uniqueId;
const body = req.body;
const amount = body?.amount;
if (!amount || typeof amount !== 'number' || amount <= 0 || amount > 100000) {
return res.status(400).json({ error: 'amount must be 1-100000' });
}
const userSnap = await db.doc(`users/${uniqueId}`).get();
if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
const user = userSnap.data();
const shyCoins = userField(user, 'shyCoins', 'shy_coins') || 0;
await db.doc(`users/${uniqueId}`).update({ shyCoins: FieldValue.increment(amount) });
const newBalance = shyCoins + amount;
const testTxId = generateId();
await writeTransaction(uniqueId, testTxId, {
type: 'PURCHASE',
amount,
currency: 'COINS',
balanceAfter: newBalance,
details: `Test purchase (+${amount} coins)`,
});
res.json({ success: true, coinsAdded: amount, newBalance });
} catch (err) {
log.error('economy', 'POST /economy/test-coins failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Balance ──
router.get('/economy/balance', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const userSnap = await db.doc(`users/${uniqueId}`).get();
if (!userSnap.exists) return res.status(404).json({ error: 'User not found' });
const user = userSnap.data();
res.json({
coins: userField(user, 'shyCoins', 'shy_coins') || 0,
beans: userField(user, 'shyBeans', 'shy_beans') || 0,
});
} catch (err) {
log.error('economy', 'GET /economy/balance failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Transactions ──
router.get('/economy/transactions', async (req, res) => {
try {
const uniqueId = req.auth.uniqueId;
const limit = Math.min(Number.parseInt(req.query.limit, 10) || 50, 200);
const filterType = req.query.type;
let query = db.collection(`users/${uniqueId}/transactions`);
if (filterType) {
query = query.where('type', '==', filterType);
}
query = query.orderBy('timestamp', 'desc').limit(limit);
const snap = await query.get();
const results = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
res.json(results);
} catch (err) {
log.error('economy', 'GET /economy/transactions failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Backpack ──
router.get('/users/:uniqueId/backpack', async (req, res) => {
try {
const isAdmin = req.auth.token?.admin;
if (String(req.auth.uniqueId) !== req.params.uniqueId && !isAdmin) {
return res.status(403).json({ error: "Cannot access another user's backpack" });
}
const snap = await db.collection(`users/${req.params.uniqueId}/backpack`).get();
const results = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
res.json(results);
} catch (err) {
log.error('economy', 'GET /users/:uniqueId/backpack failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Gift wall ──
router.get('/users/:uniqueId/gift-wall', async (req, res) => {
try {
const snap = await db.collection(`users/${req.params.uniqueId}/giftWall`).get();
const results = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
res.json(results);
} catch (err) {
log.error('economy', 'GET /users/:uniqueId/gift-wall failed', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ── Gift wall senders ──
router.get('/users/:uniqueId/gift-wall/:giftId/senders', async (req, res) => {
try {
const docSnap = await db
.doc(`users/${req.params.uniqueId}/giftWall/${req.params.giftId}`)
.get();
const senders = docSnap.exists ? docSnap.data().senders || [] : [];
// Sort by sendCount descending
senders.sort((a, b) => (b.sendCount || 0) - (a.sendCount || 0));
res.json(senders);
} catch (err) {
log.error('economy', 'GET /users/:uniqueId/gift-wall/:giftId/senders failed', {
error: err.message,
});
res.status(500).json({ error: 'Internal server error' });
}
});
// Test helper to reset in-memory config cache
router._resetConfigCache = () => {
cachedEconomyConfig = null;
economyConfigCachedAt = 0;
};
module.exports = router;
|