@aephia/atlas-kit 0.8.0-next.23 → 0.8.0-next.25

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.
Files changed (34) hide show
  1. package/dist/claim-stakes/actions/index.d.ts.map +1 -1
  2. package/dist/claim-stakes/actions/index.js +8 -5
  3. package/dist/claim-stakes/actions/index.js.map +1 -1
  4. package/dist/combat/actions/index.d.ts +86 -0
  5. package/dist/combat/actions/index.d.ts.map +1 -1
  6. package/dist/combat/actions/index.js +387 -1
  7. package/dist/combat/actions/index.js.map +1 -1
  8. package/dist/internal/c4/discriminators.d.ts +3 -0
  9. package/dist/internal/c4/discriminators.d.ts.map +1 -1
  10. package/dist/internal/c4/discriminators.js +7 -1
  11. package/dist/internal/c4/discriminators.js.map +1 -1
  12. package/dist/internal/c4/runtime-bindings.d.ts +1 -1
  13. package/dist/internal/c4/runtime-bindings.d.ts.map +1 -1
  14. package/dist/internal/c4/runtime-bindings.js +1 -1
  15. package/dist/internal/c4/runtime-bindings.js.map +1 -1
  16. package/dist/internal/planning/authorization-adapter.d.ts +33 -0
  17. package/dist/internal/planning/authorization-adapter.d.ts.map +1 -1
  18. package/dist/internal/planning/authorization-adapter.js +52 -1
  19. package/dist/internal/planning/authorization-adapter.js.map +1 -1
  20. package/dist/internal/planning/reward-epoch.d.ts +1 -1
  21. package/dist/internal/planning/reward-epoch.d.ts.map +1 -1
  22. package/dist/internal/planning/reward-epoch.js +25 -3
  23. package/dist/internal/planning/reward-epoch.js.map +1 -1
  24. package/dist/internal/planning/starbase-repair-guard.d.ts +5 -0
  25. package/dist/internal/planning/starbase-repair-guard.d.ts.map +1 -1
  26. package/dist/internal/planning/starbase-repair-guard.js +38 -1
  27. package/dist/internal/planning/starbase-repair-guard.js.map +1 -1
  28. package/dist/internal/planning/starbase-system-guard.d.ts.map +1 -1
  29. package/dist/internal/planning/starbase-system-guard.js +12 -2
  30. package/dist/internal/planning/starbase-system-guard.js.map +1 -1
  31. package/dist/planning/plan-validation.d.ts.map +1 -1
  32. package/dist/planning/plan-validation.js +4 -1
  33. package/dist/planning/plan-validation.js.map +1 -1
  34. package/package.json +1 -1
@@ -16,8 +16,9 @@ import { characterAccountDefinition, findCharacterPda, } from '../../internal/c4
16
16
  import { deriveLoyaltyContributionAddress, deriveLoyaltyEpochAddress, loyaltyContributionAccountDefinition, loyaltyEpochAccountDefinition, } from '../../internal/c4/loyalty.js';
17
17
  import { atlasRewardConfigAccountDefinition, atlasRewardRegistryAccountDefinition, deriveAtlasRewardConfigAddress, deriveAtlasRewardRegistryAddress, } from '../../internal/c4/rewards.js';
18
18
  import { deriveStarSystemAddress, starSystemAccountDefinition, } from '../../internal/c4/world.js';
19
+ import { deriveStarbasePlayerAddress, starbasePlayerAccountDefinition, } from '../../internal/c4/starbase.js';
19
20
  import { requireGameAddress } from '../../internal/game-context.js';
20
- import { adaptApplyCombatStimulantInstruction, adaptAttackFleetInstruction, adaptAttackStarbaseInstruction, adaptRepairStarbaseInstruction, adaptRetrieveLootInstruction, readPlanAuthorization, } from '../../internal/planning/authorization-adapter.js';
21
+ import { adaptApplyCombatStimulantInstruction, adaptAttackFleetInstruction, adaptAttackStarbaseInstruction, adaptReloadFleetApInstruction, adaptRepairDockedFleetInstruction, adaptRepairIdleFleetInstruction, adaptRepairStarbaseInstruction, adaptRetrieveLootInstruction, readPlanAuthorization, } from '../../internal/planning/authorization-adapter.js';
21
22
  import { buildPlannerPlan } from '../../planning/plan-construction.js';
22
23
  import { readGameCombatConfiguration } from '../../registry/combat.js';
23
24
  import { CLOCK_ADDRESS, readClock, } from '../../internal/planning/faction-enrollment.js';
@@ -84,6 +85,26 @@ function validateRetrieveOptions(value) {
84
85
  function validateRepairOptions(value) {
85
86
  const options = readRecord(value, 'options');
86
87
  assertKeys(options, 'options', ['authorization'], ['maxRepairKits']);
88
+ return readRepairKitCap(options);
89
+ }
90
+ function validateFleetRepairOptions(value) {
91
+ const options = readRecord(value, 'options');
92
+ assertKeys(options, 'options', ['authorization'], ['maxRepairKits', 'target']);
93
+ const base = readRepairKitCap(options);
94
+ const { target } = options;
95
+ if (target === undefined)
96
+ return base;
97
+ const fleet = readRecord(target, 'options.target');
98
+ if (fleet.kind !== 'fleet' || !isAddress(String(fleet.address)))
99
+ invalid('options.target', target, 'a Fleet snapshot read through this context', 'Pass the target Fleet as read with getFleet, or omit target to repair the Fleet itself, before retrying.');
100
+ return { ...base, target: target };
101
+ }
102
+ function validateReloadOptions(value) {
103
+ const options = readRecord(value, 'options');
104
+ assertKeys(options, 'options', ['authorization']);
105
+ return { authorization: readPlanAuthorization(options.authorization) };
106
+ }
107
+ function readRepairKitCap(options) {
87
108
  const authorization = readPlanAuthorization(options.authorization);
88
109
  const { maxRepairKits } = options;
89
110
  if (maxRepairKits === undefined)
@@ -1271,6 +1292,371 @@ export async function planFleetRepairStarbase(ctx, fleet, target, input) {
1271
1292
  summary: `Repair the Starbase at ${system.name} with Fleet ${current.name}.`,
1272
1293
  });
1273
1294
  }
1295
+ /** When the game makes a reloaded Fleet's AP usable: after the missing AP
1296
+ * divided by the AP regen rate, in whole seconds rounded up, and never before
1297
+ * a reload already running ends. */
1298
+ function apUsableAt(current, now) {
1299
+ const missing = current.stats.combat.ap - current.ap;
1300
+ const at = now + BigInt(Math.ceil(missing / current.stats.combat.apRegenRate.value));
1301
+ return at > current.apReloadExpiresAt ? at : current.apReloadExpiresAt;
1302
+ }
1303
+ /** Reads, decodes and checks the owner's fresh canonical Fleet for a Fleet
1304
+ * action: configured Game, owning Profile, canonical address, and not rented
1305
+ * or listed for rent. */
1306
+ async function readOwnedFleet(ctx, fleet, profile, game, candidate, action) {
1307
+ const account = requireAccount(candidate, fleet.address, `Fleet ${fleet.address} is missing. Refresh Fleet discovery and retry the ${action}.`);
1308
+ const current = fleetAccountDefinition.decode(account, ctx.programs);
1309
+ const label = `Fleet ${current.name} (${fleet.address})`;
1310
+ if (current.game !== game ||
1311
+ current.ownerProfile !== profile ||
1312
+ (await deriveFleetAddress(ctx.programs, current)) !== fleet.address) {
1313
+ fail(`${label} is no longer the canonical Fleet of Profile ${profile} in configured Game ${game}. Refresh the Fleet and retry.`, fleet.address);
1314
+ }
1315
+ if (current.subProfile !== SYSTEM_PROGRAM) {
1316
+ fail(`${label} is ${describeFleetRental(ctx.programs, current.subProfile)}, so its owner cannot ${action === 'AP reload' ? 'reload' : 'repair'} it. End the rental, refresh the Fleet and retry.`, fleet.address);
1317
+ }
1318
+ return { account, current, label };
1319
+ }
1320
+ function requireSnapshotOwner(fleet, profile, game) {
1321
+ if (fleet.ownerProfile.address !== profile) {
1322
+ fail(`Fleet ${fleet.address} does not belong to authorization Profile ${profile}. Choose a Fleet owned by that Profile and retry.`, fleet.address);
1323
+ }
1324
+ if (fleet.game !== game) {
1325
+ fail(`Fleet ${fleet.address} belongs to Game ${fleet.game}, not configured Game ${game}. Refresh the Fleet through this context and retry.`, fleet.address);
1326
+ }
1327
+ }
1328
+ /** Plans one owned Fleet's ability power (AP) reload.
1329
+ *
1330
+ * The game sets the Fleet's stored AP to its maximum and makes it usable once
1331
+ * a reload delay has passed: the missing AP divided by the Fleet's AP regen
1332
+ * rate, rounded up to whole seconds. A reload never shortens a reload that is
1333
+ * already running. The planner requires a Fleet neither rented nor listed for
1334
+ * rent, Idle, Docked, subwarping or warping, with its required crew, and
1335
+ * missing AP; it states when the AP becomes usable from the state and Clock it
1336
+ * read. The Profile key needs the combat permission, which remains
1337
+ * chain-authoritative.
1338
+ *
1339
+ * @example
1340
+ * ```ts
1341
+ * declare const ctx: SageContext;
1342
+ * declare const fleet: FleetSnapshot;
1343
+ * declare const authorization: PlanAuthorization;
1344
+ * const plan = await planFleetReloadAp(ctx, fleet, { authorization });
1345
+ * console.log(plan.describe());
1346
+ * ```
1347
+ */
1348
+ export async function planFleetReloadAp(ctx, fleet, input) {
1349
+ const { authorization } = validateReloadOptions(input);
1350
+ const game = requireGameAddress(ctx);
1351
+ const { profile } = authorization;
1352
+ requireSnapshotOwner(fleet, profile, game);
1353
+ const [fleetCandidate, clock] = await readContextRawAccounts(ctx, [
1354
+ fleet.address,
1355
+ CLOCK_ADDRESS,
1356
+ ]);
1357
+ const { account, current, label } = await readOwnedFleet(ctx, fleet, profile, game, fleetCandidate, 'AP reload');
1358
+ const { kind } = current.state;
1359
+ if (kind !== 'idle' &&
1360
+ kind !== 'docked' &&
1361
+ kind !== 'subwarp' &&
1362
+ kind !== 'warp') {
1363
+ fail(`${label} is ${kind === 'unrecognized' ? `in game state ${current.state.variant}` : kind}; the game reloads AP only for an Idle, Docked, subwarping or warping Fleet. Return it to one of those states, refresh the Fleet and retry.`, fleet.address);
1364
+ }
1365
+ if (current.crewCount < current.stats.misc.requiredCrew) {
1366
+ fail(`${label} has ${String(current.crewCount)} crew but needs ${String(current.stats.misc.requiredCrew)} to reload AP. Load crew, refresh the Fleet and retry.`, fleet.address);
1367
+ }
1368
+ const max = current.stats.combat.ap;
1369
+ if (current.ap >= max) {
1370
+ fail(`${label} already holds its maximum of ${String(max)} AP, so a reload changes nothing.${current.apReloadExpiresAt > 0n ? ` It becomes usable at Unix time ${String(current.apReloadExpiresAt)}.` : ''}`, fleet.address);
1371
+ }
1372
+ if (current.stats.combat.apRegenRate.raw <= 0n) {
1373
+ fail(`${label} has no AP regen rate, so the game cannot size its reload. Add ships that regenerate AP and retry.`, fleet.address);
1374
+ }
1375
+ const now = readClock(requireAccount(clock, CLOCK_ADDRESS, 'The Clock sysvar is missing. Refresh chain time and retry the reload.'));
1376
+ const missing = max - current.ap;
1377
+ const usableAt = apUsableAt(current, now);
1378
+ const description = `Reload ${label}'s AP from ${String(current.ap)} to its maximum of ${String(max)}. The game makes the AP usable after reloading the ${String(missing)} missing AP at ${String(current.stats.combat.apRegenRate.value)} per second: about Unix time ${String(usableAt)} from the Clock read at planning, and never before a reload already running ends. Combat permission and the exact time remain chain-authoritative.`;
1379
+ return buildPlannerPlan(ctx.programs, {
1380
+ kind: 'combat.reload-fleet-ap',
1381
+ preconditions: [
1382
+ await accountStatePrecondition(account, `${label} keeps its state, crew, stats and AP.`),
1383
+ ],
1384
+ steps: [
1385
+ {
1386
+ describes: description,
1387
+ instruction: adaptReloadFleetApInstruction(ctx.programs, {
1388
+ authorization,
1389
+ fleet: fleet.address,
1390
+ game,
1391
+ }),
1392
+ signers: [authorization.authority],
1393
+ },
1394
+ ],
1395
+ summary: `Reload Fleet ${current.name}'s AP.`,
1396
+ });
1397
+ }
1398
+ const STARBASE_LEVEL_ORDER = [
1399
+ 'level-0',
1400
+ 'level-1',
1401
+ 'level-2',
1402
+ 'level-3',
1403
+ 'level-4',
1404
+ 'level-5',
1405
+ 'css',
1406
+ ];
1407
+ /** Hull points a repair queues and the whole kits it uses, as the game
1408
+ * computes them; `undefined` when it would restore less than one point. */
1409
+ function repairOutcome(input) {
1410
+ const perKit = input.cost * input.efficiency;
1411
+ const usable = Math.min(input.ability, Number(input.available));
1412
+ const hull = Math.min(input.missing, usable * perKit);
1413
+ if (Math.floor(hull) < 1)
1414
+ return undefined;
1415
+ return { hull, kits: Math.max(1, Math.ceil(hull / perKit - 1e-9)) };
1416
+ }
1417
+ /** Plans one Fleet hull repair: an Idle Fleet repairing itself or another Idle
1418
+ * Fleet of its faction in range, or a Docked Fleet repaired by its Starbase.
1419
+ *
1420
+ * Repair kits queue pending hull points on the repaired Fleet, which flow into
1421
+ * its hull over time. An Idle repair uses the repairing Fleet's kits, repair
1422
+ * ability and efficiency; a Docked repair uses the kits in the owner's
1423
+ * Starbase inventory and the Starbase level's repair ability and efficiency,
1424
+ * and needs a Starbase of the Fleet's faction at or above its repair level.
1425
+ * Either way the repaired Fleet's repair cost prices the hull points. The
1426
+ * planner requires a Fleet neither rented nor listed for rent, and a repaired
1427
+ * Fleet missing hull points beyond those already queued. It states how many
1428
+ * kits the repair uses and how many hull points it queues from the state it
1429
+ * read; both follow the Fleets when the transaction executes.
1430
+ *
1431
+ * The kits used can earn the Fleet's faction (MUD, ONI or Ustur) Loyalty
1432
+ * Points for the current reward epoch, so the Plan opens a missing Loyalty
1433
+ * epoch or contribution first, its rent paid by the authorization key's
1434
+ * wallet, as {@link planFleetRepairStarbase} does. Neither Fleet nor the
1435
+ * Starbase inventory grows. Key permissions remain chain-authoritative.
1436
+ *
1437
+ * @example
1438
+ * ```ts
1439
+ * declare const ctx: SageContext;
1440
+ * declare const fleet: FleetSnapshot;
1441
+ * declare const authorization: PlanAuthorization;
1442
+ * const plan = await planFleetRepair(ctx, fleet, { authorization });
1443
+ * console.log(plan.describe());
1444
+ * ```
1445
+ */
1446
+ export async function planFleetRepair(ctx, fleet, input) {
1447
+ const { authorization, maxRepairKits, target } = validateFleetRepairOptions(input);
1448
+ const game = requireGameAddress(ctx);
1449
+ const { profile } = authorization;
1450
+ requireSnapshotOwner(fleet, profile, game);
1451
+ if (target?.address === fleet.address) {
1452
+ fail(`Fleet ${fleet.address} cannot name itself as the repair target. Omit target to repair the Fleet itself.`, fleet.address);
1453
+ }
1454
+ const [combat, [fleetCandidate, clock, targetCandidate]] = await Promise.all([
1455
+ readGameCombatConfiguration(ctx),
1456
+ readContextRawAccounts(ctx, [
1457
+ fleet.address,
1458
+ CLOCK_ADDRESS,
1459
+ ...(target === undefined ? [] : [target.address]),
1460
+ ]),
1461
+ ]);
1462
+ const { account, current, label } = await readOwnedFleet(ctx, fleet, profile, game, fleetCandidate, 'repair');
1463
+ const kitCargo = combat.data.repairKitCargoId;
1464
+ const docked = current.state.kind === 'docked';
1465
+ if (docked && target !== undefined) {
1466
+ fail(`${label} is Docked; only an Idle Fleet repairs another Fleet. Omit target to have its Starbase repair it, or undock it first.`, fleet.address);
1467
+ }
1468
+ if (!docked && current.state.kind !== 'idle') {
1469
+ const remedy = IDLE_REMEDY[current.state.kind] ??
1470
+ 'Wait until the game returns it to Idle';
1471
+ fail(`${label} is ${current.state.kind === 'unrecognized' ? `in game state ${current.state.variant}` : current.state.kind}; the game repairs a Fleet that is Idle or Docked. ${remedy}, refresh the Fleet and retry.`, fleet.address);
1472
+ }
1473
+ const preconditions = [
1474
+ await accountStatePrecondition(account, `${label} keeps its state, location, crew, faction, stats, hull and repair kits.`),
1475
+ ];
1476
+ let repaired = current;
1477
+ let repairedLabel = label;
1478
+ let ability;
1479
+ let efficiency;
1480
+ let held;
1481
+ let source;
1482
+ let where = '';
1483
+ let dockedAccounts;
1484
+ if (current.state.kind === 'docked') {
1485
+ const { system: systemAddress, systemSeqId } = current.state;
1486
+ const character = await findCharacterPda(ctx.programs, profile, game);
1487
+ const playerAddress = await deriveStarbasePlayerAddress(ctx.programs, systemAddress, character);
1488
+ const [systemCandidate, playerCandidate] = await readContextRawAccounts(ctx, [systemAddress, playerAddress]);
1489
+ const system = starSystemAccountDefinition.decode(requireAccount(systemCandidate, systemAddress, `Star System ${systemAddress} is missing. Refresh it and retry the repair.`), ctx.programs);
1490
+ const { starbase } = system;
1491
+ if (starbase === undefined ||
1492
+ system.game !== game ||
1493
+ system.sequenceId !== systemSeqId) {
1494
+ fail(`${label} is docked at Star System ${system.name} (${systemAddress}), which no longer has the Starbase it docked at in configured Game ${game}. Refresh the Fleet and System and retry.`, systemAddress);
1495
+ }
1496
+ where = `the ${starbase.level} Starbase at ${system.name}`;
1497
+ if (current.faction !== starbase.owner) {
1498
+ fail(`${label} is ${current.faction}, but ${where} belongs to ${starbase.owner}; the game repairs a Docked Fleet only at a Starbase of its own faction. Dock at a ${current.faction} Starbase and retry.`, fleet.address);
1499
+ }
1500
+ if (STARBASE_LEVEL_ORDER.indexOf(starbase.level) <
1501
+ STARBASE_LEVEL_ORDER.indexOf(starbase.repairEnableLevel)) {
1502
+ fail(`${where} repairs Fleets only from ${starbase.repairEnableLevel}. Dock at a Starbase that has reached its repair level and retry.`, systemAddress);
1503
+ }
1504
+ const info = starbase.maxLevel.levels.find((entry) => entry.level === starbase.level)?.info;
1505
+ if (info === undefined) {
1506
+ fail(`${where} has no level information, so the game cannot repair Fleets there.`, systemAddress);
1507
+ }
1508
+ const playerAccount = requireAccount(playerCandidate, playerAddress, `Starbase Player ${playerAddress} is missing for Profile ${profile}. Register the Profile at ${where} and retry.`);
1509
+ const player = starbasePlayerAccountDefinition.decode(playerAccount, ctx.programs);
1510
+ if (player.playerProfile !== profile ||
1511
+ player.system !== systemAddress ||
1512
+ player.character !== character) {
1513
+ fail(`Starbase Player ${playerAddress} does not belong to Profile ${profile}'s Character ${character} at ${where}. Refresh it and retry.`, playerAddress);
1514
+ }
1515
+ if (player.sequenceId !== system.sequenceId) {
1516
+ fail(`Starbase Player ${playerAddress} belongs to Starbase generation ${String(player.sequenceId)}, but ${where} is at generation ${String(system.sequenceId)}; the game treats that registration and its inventory as destroyed. Recover the registration onto the current generation with planDestroyStarbasePlayer, move repair kits into its inventory, and replan the repair.`, playerAddress);
1517
+ }
1518
+ ability = info.repairAbility.value;
1519
+ efficiency = info.repairEfficiency.value;
1520
+ held =
1521
+ player.cargo.amounts.find(({ cargoId }) => cargoId === kitCargo)
1522
+ ?.amount ?? 0n;
1523
+ source = `the ${String(held)} repair kits in Profile ${profile}'s inventory at ${where}`;
1524
+ dockedAccounts = { system: systemAddress, starbasePlayer: playerAddress };
1525
+ preconditions.push(await accountStatePrecondition(playerAccount, `Starbase Player ${playerAddress} keeps its owner, Starbase generation and repair kits.`), {
1526
+ kind: 'starbase-system',
1527
+ address: systemAddress,
1528
+ game,
1529
+ starbaseSequenceId: system.sequenceId,
1530
+ describes: `Star System ${system.name} keeps its canonical Game identity, active Starbase and sequence ${String(system.sequenceId)}.`,
1531
+ });
1532
+ }
1533
+ else {
1534
+ if (current.crewCount < current.stats.misc.requiredCrew) {
1535
+ fail(`${label} has ${String(current.crewCount)} crew but needs ${String(current.stats.misc.requiredCrew)} to repair. Load crew, refresh the Fleet and retry.`, fleet.address);
1536
+ }
1537
+ ability = current.stats.combat.repairAbility.value;
1538
+ efficiency = current.stats.combat.repairEfficiency.value;
1539
+ held =
1540
+ current.cargoHold.amounts.find(({ cargoId }) => cargoId === kitCargo)
1541
+ ?.amount ?? 0n;
1542
+ source = `the ${String(held)} repair kits in ${label}'s cargo hold`;
1543
+ if (target !== undefined) {
1544
+ const targetAccount = requireAccount(targetCandidate, target.address, `Target Fleet ${target.address} is missing. Refresh it and retry the repair.`);
1545
+ const other = fleetAccountDefinition.decode(targetAccount, ctx.programs);
1546
+ repairedLabel = `Fleet ${other.name} (${target.address})`;
1547
+ if (other.game !== game ||
1548
+ (await deriveFleetAddress(ctx.programs, other)) !== target.address) {
1549
+ fail(`${repairedLabel} is not a canonical Fleet of configured Game ${game}. Refresh it and retry.`, target.address);
1550
+ }
1551
+ if (other.state.kind !== 'idle') {
1552
+ fail(`${repairedLabel} is ${other.state.kind === 'unrecognized' ? `in game state ${other.state.variant}` : other.state.kind}; the game repairs another Fleet only while it is Idle. Wait until it is Idle, refresh it and retry.`, target.address);
1553
+ }
1554
+ if (other.crewCount < other.stats.misc.requiredCrew) {
1555
+ fail(`${repairedLabel} has ${String(other.crewCount)} crew but needs ${String(other.stats.misc.requiredCrew)}, and the game repairs only a Fleet with its required crew.`, target.address);
1556
+ }
1557
+ if (other.faction !== current.faction) {
1558
+ fail(`${repairedLabel} is ${other.faction}, but ${label} is ${current.faction}; the game repairs only a Fleet of the same faction. Choose a ${current.faction} Fleet and retry.`, target.address);
1559
+ }
1560
+ const range = combat.data.interactionRange;
1561
+ const dx = current.locationRaw.x - other.locationRaw.x;
1562
+ const dy = current.locationRaw.y - other.locationRaw.y;
1563
+ if (squared(dx) + squared(dy) > squared(range.raw)) {
1564
+ const distance = Math.hypot(current.location.x - other.location.x, current.location.y - other.location.y);
1565
+ fail(`${label} is ${distance.toFixed(3)} from ${repairedLabel}, beyond the Game's interaction range of ${String(range.value)}. Move within range, refresh both Fleets and retry.`, target.address);
1566
+ }
1567
+ repaired = other;
1568
+ preconditions.push(await accountStatePrecondition(targetAccount, `${repairedLabel} keeps its state, location, crew, faction, stats and hull.`));
1569
+ }
1570
+ if (ability <= 0 || efficiency <= 0) {
1571
+ fail(`${label} has repair ability ${String(ability)} and repair efficiency ${String(efficiency)}; the game repairs only with both above zero. Add ships that can repair and retry.`, fleet.address);
1572
+ }
1573
+ }
1574
+ if (held <= 0n) {
1575
+ fail(docked
1576
+ ? `Profile ${profile} holds no repair kits (cargo ${String(kitCargo)}) at ${where}. Move repair kits into the Starbase inventory and retry.`
1577
+ : `${label} carries no repair kits (cargo ${String(kitCargo)}). Load repair kits into its cargo hold and retry.`, fleet.address);
1578
+ }
1579
+ const maxHp = repaired.stats.combat.hp;
1580
+ // Pending points flow into the hull without changing their sum, so the
1581
+ // stored points give what the game finds missing when it settles.
1582
+ const missing = maxHp - repaired.hp - repaired.pendingHp;
1583
+ if (missing <= 0) {
1584
+ fail(`${repairedLabel} has ${String(repaired.hp)} hull points and ${String(repaired.pendingHp)} queued for repair of its ${String(maxHp)} maximum, so nothing is missing. Choose a damaged Fleet.`, repaired === current ? fleet.address : target.address);
1585
+ }
1586
+ const cost = repaired.stats.combat.repairCost.value;
1587
+ const available = maxRepairKits === undefined || BigInt(maxRepairKits) > held
1588
+ ? held
1589
+ : BigInt(maxRepairKits);
1590
+ const outcome = cost > 0 && ability > 0 && efficiency > 0
1591
+ ? repairOutcome({ missing, cost, ability, efficiency, available })
1592
+ : undefined;
1593
+ if (outcome === undefined) {
1594
+ fail(`The repair would restore less than one hull point to ${repairedLabel}, and the game refuses a repair that restores nothing.${docked ? ` ${where} repairs with ability ${String(ability)}, efficiency ${String(efficiency)} at a repair cost of ${String(cost)}.` : ' Use a Fleet with more repair ability or kits.'}`, fleet.address);
1595
+ }
1596
+ const now = readClock(requireAccount(clock, CLOCK_ADDRESS, 'The Clock sysvar is missing. Refresh chain time and retry the repair.'));
1597
+ const reward = await resolveRewardContext(ctx, game, now, 'Fleet repairs');
1598
+ const rate = reward.config.repairKitLpRateRaw;
1599
+ const faction = factionValue(current.faction);
1600
+ const earns = rate > 0n && faction >= 1 && faction <= 3;
1601
+ const loyalty = await resolveLoyaltyEarning(ctx, {
1602
+ game,
1603
+ profile,
1604
+ funder: authorization.authority,
1605
+ faction,
1606
+ reward,
1607
+ earns,
1608
+ });
1609
+ const rewardAccounts = {
1610
+ rewardRegistry: reward.registry,
1611
+ rewardConfig: reward.rewardConfig,
1612
+ ...(loyalty.loyaltyEpoch === undefined
1613
+ ? {}
1614
+ : { loyaltyEpoch: loyalty.loyaltyEpoch }),
1615
+ ...(loyalty.loyaltyContribution === undefined
1616
+ ? {}
1617
+ : { loyaltyContribution: loyalty.loyaltyContribution }),
1618
+ ...(maxRepairKits === undefined ? {} : { maxRepairKits }),
1619
+ };
1620
+ const instruction = dockedAccounts === undefined
1621
+ ? adaptRepairIdleFleetInstruction(ctx.programs, {
1622
+ ...rewardAccounts,
1623
+ authorization,
1624
+ fleet: fleet.address,
1625
+ ...(target === undefined ? {} : { targetFleet: target.address }),
1626
+ game,
1627
+ })
1628
+ : adaptRepairDockedFleetInstruction(ctx.programs, {
1629
+ ...rewardAccounts,
1630
+ authorization,
1631
+ fleet: fleet.address,
1632
+ ...dockedAccounts,
1633
+ game,
1634
+ });
1635
+ const points = earns
1636
+ ? ` If the active reward configuration awards Loyalty Points for repairs, the kits used earn ${String(rate)} each in reward epoch ${String(reward.currentEpoch)}.`
1637
+ : '';
1638
+ const who = dockedAccounts !== undefined
1639
+ ? `${where} repairs ${label}`
1640
+ : target === undefined
1641
+ ? `${label} repairs itself`
1642
+ : `${label} repairs ${repairedLabel}`;
1643
+ const description = `${who}. It is missing ${String(missing)} of its ${String(maxHp)} hull points; the game uses about ${String(outcome.kits)} of ${source}${maxRepairKits === undefined ? '' : ` (capped at ${String(maxRepairKits)})`} to queue about ${String(Math.floor(outcome.hull))} hull points, which flow into the hull over time.${points} The kits used and hull points queued follow the Fleets when the transaction executes; key permissions remain chain-authoritative.`;
1644
+ return buildPlannerPlan(ctx.programs, {
1645
+ kind: dockedAccounts === undefined
1646
+ ? 'combat.repair-idle-fleet'
1647
+ : 'combat.repair-docked-fleet',
1648
+ preconditions: [loyalty.guard, ...preconditions, ...loyalty.preconditions],
1649
+ steps: [
1650
+ ...loyalty.steps,
1651
+ {
1652
+ describes: description,
1653
+ instruction,
1654
+ signers: [authorization.authority],
1655
+ },
1656
+ ],
1657
+ summary: `Repair Fleet ${repaired.name}.`,
1658
+ });
1659
+ }
1274
1660
  function lootSnapshotFingerprint(loot) {
1275
1661
  return [
1276
1662
  loot.address,