@aephia/atlas-kit 0.8.0-next.9 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/README.md +1 -1
  2. package/dist/claim-stakes/actions/index.d.ts +153 -0
  3. package/dist/claim-stakes/actions/index.d.ts.map +1 -1
  4. package/dist/claim-stakes/actions/index.js +560 -72
  5. package/dist/claim-stakes/actions/index.js.map +1 -1
  6. package/dist/claim-stakes/index.d.ts +1 -1
  7. package/dist/claim-stakes/index.d.ts.map +1 -1
  8. package/dist/claim-stakes/index.js +1 -1
  9. package/dist/claim-stakes/index.js.map +1 -1
  10. package/dist/client/contracts.d.ts +1 -1
  11. package/dist/client/contracts.d.ts.map +1 -1
  12. package/dist/client/deployments.d.ts +1 -1
  13. package/dist/client/deployments.js +1 -1
  14. package/dist/client/errors.d.ts +1 -1
  15. package/dist/client/errors.d.ts.map +1 -1
  16. package/dist/client/errors.js.map +1 -1
  17. package/dist/combat/actions/index.d.ts +137 -0
  18. package/dist/combat/actions/index.d.ts.map +1 -1
  19. package/dist/combat/actions/index.js +596 -1
  20. package/dist/combat/actions/index.js.map +1 -1
  21. package/dist/crafting/actions/habs.d.ts +366 -0
  22. package/dist/crafting/actions/habs.d.ts.map +1 -0
  23. package/dist/crafting/actions/habs.js +1030 -0
  24. package/dist/crafting/actions/habs.js.map +1 -0
  25. package/dist/crafting/actions/index.d.ts +14 -3
  26. package/dist/crafting/actions/index.d.ts.map +1 -1
  27. package/dist/crafting/actions/index.js +61 -25
  28. package/dist/crafting/actions/index.js.map +1 -1
  29. package/dist/crafting/index.d.ts +4 -1
  30. package/dist/crafting/index.d.ts.map +1 -1
  31. package/dist/crafting/index.js +1 -1
  32. package/dist/crafting/index.js.map +1 -1
  33. package/dist/fleets/actions/index.d.ts +10 -8
  34. package/dist/fleets/actions/index.d.ts.map +1 -1
  35. package/dist/fleets/actions/index.js +15 -13
  36. package/dist/fleets/actions/index.js.map +1 -1
  37. package/dist/identity/actions/daily-check-in.d.ts +57 -0
  38. package/dist/identity/actions/daily-check-in.d.ts.map +1 -0
  39. package/dist/identity/actions/daily-check-in.js +200 -0
  40. package/dist/identity/actions/daily-check-in.js.map +1 -0
  41. package/dist/identity/actions/index.d.ts +1 -0
  42. package/dist/identity/actions/index.d.ts.map +1 -1
  43. package/dist/identity/actions/index.js +1 -0
  44. package/dist/identity/actions/index.js.map +1 -1
  45. package/dist/identity/index.d.ts +169 -17
  46. package/dist/identity/index.d.ts.map +1 -1
  47. package/dist/identity/index.js +142 -9
  48. package/dist/identity/index.js.map +1 -1
  49. package/dist/internal/c4/career-xp.d.ts +113 -26
  50. package/dist/internal/c4/career-xp.d.ts.map +1 -1
  51. package/dist/internal/c4/career-xp.js +101 -38
  52. package/dist/internal/c4/career-xp.js.map +1 -1
  53. package/dist/internal/c4/character-registration.d.ts.map +1 -1
  54. package/dist/internal/c4/character-registration.js +3 -0
  55. package/dist/internal/c4/character-registration.js.map +1 -1
  56. package/dist/internal/c4/character.d.ts +68 -0
  57. package/dist/internal/c4/character.d.ts.map +1 -1
  58. package/dist/internal/c4/character.js +46 -2
  59. package/dist/internal/c4/character.js.map +1 -1
  60. package/dist/internal/c4/claim-stake.d.ts +8 -0
  61. package/dist/internal/c4/claim-stake.d.ts.map +1 -1
  62. package/dist/internal/c4/claim-stake.js +5 -0
  63. package/dist/internal/c4/claim-stake.js.map +1 -1
  64. package/dist/internal/c4/combat-storage.d.ts +4 -0
  65. package/dist/internal/c4/combat-storage.d.ts.map +1 -1
  66. package/dist/internal/c4/combat-storage.js +6 -1
  67. package/dist/internal/c4/combat-storage.js.map +1 -1
  68. package/dist/internal/c4/crafting-hab-storage.d.ts +42 -0
  69. package/dist/internal/c4/crafting-hab-storage.d.ts.map +1 -0
  70. package/dist/internal/c4/crafting-hab-storage.js +174 -0
  71. package/dist/internal/c4/crafting-hab-storage.js.map +1 -0
  72. package/dist/internal/c4/crafting-storage.d.ts +8 -0
  73. package/dist/internal/c4/crafting-storage.d.ts.map +1 -1
  74. package/dist/internal/c4/crafting-storage.js +18 -1
  75. package/dist/internal/c4/crafting-storage.js.map +1 -1
  76. package/dist/internal/c4/crafting.d.ts +8 -0
  77. package/dist/internal/c4/crafting.d.ts.map +1 -1
  78. package/dist/internal/c4/crafting.js +5 -0
  79. package/dist/internal/c4/crafting.js.map +1 -1
  80. package/dist/internal/c4/discriminators.d.ts +27 -0
  81. package/dist/internal/c4/discriminators.d.ts.map +1 -1
  82. package/dist/internal/c4/discriminators.js +55 -1
  83. package/dist/internal/c4/discriminators.js.map +1 -1
  84. package/dist/internal/c4/fleet-storage.d.ts +2 -1
  85. package/dist/internal/c4/fleet-storage.d.ts.map +1 -1
  86. package/dist/internal/c4/fleet-storage.js +14 -5
  87. package/dist/internal/c4/fleet-storage.js.map +1 -1
  88. package/dist/internal/c4/fleet.d.ts +33 -4
  89. package/dist/internal/c4/fleet.d.ts.map +1 -1
  90. package/dist/internal/c4/fleet.js +27 -2
  91. package/dist/internal/c4/fleet.js.map +1 -1
  92. package/dist/internal/c4/game.d.ts +33 -0
  93. package/dist/internal/c4/game.d.ts.map +1 -1
  94. package/dist/internal/c4/game.js +46 -0
  95. package/dist/internal/c4/game.js.map +1 -1
  96. package/dist/internal/c4/governance.d.ts +72 -0
  97. package/dist/internal/c4/governance.d.ts.map +1 -1
  98. package/dist/internal/c4/governance.js +108 -3
  99. package/dist/internal/c4/governance.js.map +1 -1
  100. package/dist/internal/c4/runtime-bindings.d.ts +1 -1
  101. package/dist/internal/c4/runtime-bindings.d.ts.map +1 -1
  102. package/dist/internal/c4/runtime-bindings.js +1 -1
  103. package/dist/internal/c4/runtime-bindings.js.map +1 -1
  104. package/dist/internal/c4/starbase-upgrade.d.ts +20 -0
  105. package/dist/internal/c4/starbase-upgrade.d.ts.map +1 -0
  106. package/dist/internal/c4/starbase-upgrade.js +44 -0
  107. package/dist/internal/c4/starbase-upgrade.js.map +1 -0
  108. package/dist/internal/c4/world.d.ts +3 -2
  109. package/dist/internal/c4/world.d.ts.map +1 -1
  110. package/dist/internal/c4/world.js +4 -18
  111. package/dist/internal/c4/world.js.map +1 -1
  112. package/dist/internal/planning/action-runtime.d.ts +3 -2
  113. package/dist/internal/planning/action-runtime.d.ts.map +1 -1
  114. package/dist/internal/planning/action-runtime.js +4 -3
  115. package/dist/internal/planning/action-runtime.js.map +1 -1
  116. package/dist/internal/planning/authorization-adapter.d.ts +363 -1
  117. package/dist/internal/planning/authorization-adapter.d.ts.map +1 -1
  118. package/dist/internal/planning/authorization-adapter.js +519 -1
  119. package/dist/internal/planning/authorization-adapter.js.map +1 -1
  120. package/dist/internal/planning/building-xp.d.ts +50 -0
  121. package/dist/internal/planning/building-xp.d.ts.map +1 -0
  122. package/dist/internal/planning/building-xp.js +166 -0
  123. package/dist/internal/planning/building-xp.js.map +1 -0
  124. package/dist/internal/planning/claim-stake-transfer-window.d.ts +18 -0
  125. package/dist/internal/planning/claim-stake-transfer-window.d.ts.map +1 -0
  126. package/dist/internal/planning/claim-stake-transfer-window.js +57 -0
  127. package/dist/internal/planning/claim-stake-transfer-window.js.map +1 -0
  128. package/dist/internal/planning/combat-storage-actions.d.ts +3 -2
  129. package/dist/internal/planning/combat-storage-actions.d.ts.map +1 -1
  130. package/dist/internal/planning/combat-storage-actions.js +26 -4
  131. package/dist/internal/planning/combat-storage-actions.js.map +1 -1
  132. package/dist/internal/planning/crafting-hab-storage-actions.d.ts +10 -0
  133. package/dist/internal/planning/crafting-hab-storage-actions.d.ts.map +1 -0
  134. package/dist/internal/planning/crafting-hab-storage-actions.js +46 -0
  135. package/dist/internal/planning/crafting-hab-storage-actions.js.map +1 -0
  136. package/dist/internal/planning/crafting-storage-actions.d.ts +5 -3
  137. package/dist/internal/planning/crafting-storage-actions.d.ts.map +1 -1
  138. package/dist/internal/planning/crafting-storage-actions.js +66 -4
  139. package/dist/internal/planning/crafting-storage-actions.js.map +1 -1
  140. package/dist/internal/planning/currency-cache-guard.d.ts.map +1 -1
  141. package/dist/internal/planning/currency-cache-guard.js +5 -1
  142. package/dist/internal/planning/currency-cache-guard.js.map +1 -1
  143. package/dist/internal/planning/daily-check-in.d.ts +71 -0
  144. package/dist/internal/planning/daily-check-in.d.ts.map +1 -0
  145. package/dist/internal/planning/daily-check-in.js +201 -0
  146. package/dist/internal/planning/daily-check-in.js.map +1 -0
  147. package/dist/internal/planning/democracy-history.d.ts +15 -0
  148. package/dist/internal/planning/democracy-history.d.ts.map +1 -1
  149. package/dist/internal/planning/democracy-history.js +23 -7
  150. package/dist/internal/planning/democracy-history.js.map +1 -1
  151. package/dist/internal/planning/democracy-storage-actions.d.ts +12 -0
  152. package/dist/internal/planning/democracy-storage-actions.d.ts.map +1 -0
  153. package/dist/internal/planning/democracy-storage-actions.js +81 -0
  154. package/dist/internal/planning/democracy-storage-actions.js.map +1 -0
  155. package/dist/internal/planning/fleet-state.js +1 -1
  156. package/dist/internal/planning/fleet-state.js.map +1 -1
  157. package/dist/internal/planning/loyalty-earning.d.ts +42 -0
  158. package/dist/internal/planning/loyalty-earning.d.ts.map +1 -0
  159. package/dist/internal/planning/loyalty-earning.js +143 -0
  160. package/dist/internal/planning/loyalty-earning.js.map +1 -0
  161. package/dist/internal/planning/placement-fee.d.ts +6 -0
  162. package/dist/internal/planning/placement-fee.d.ts.map +1 -0
  163. package/dist/internal/planning/placement-fee.js +9 -0
  164. package/dist/internal/planning/placement-fee.js.map +1 -0
  165. package/dist/internal/planning/plan-guards.d.ts.map +1 -1
  166. package/dist/internal/planning/plan-guards.js +11 -0
  167. package/dist/internal/planning/plan-guards.js.map +1 -1
  168. package/dist/internal/planning/profile-storage-funding-guard.d.ts +1 -1
  169. package/dist/internal/planning/profile-storage-funding-guard.d.ts.map +1 -1
  170. package/dist/internal/planning/profile-storage-funding-guard.js +53 -1
  171. package/dist/internal/planning/profile-storage-funding-guard.js.map +1 -1
  172. package/dist/internal/planning/rent-catalog.d.ts.map +1 -1
  173. package/dist/internal/planning/rent-catalog.js +37 -1
  174. package/dist/internal/planning/rent-catalog.js.map +1 -1
  175. package/dist/internal/planning/research-unlock.d.ts.map +1 -1
  176. package/dist/internal/planning/research-unlock.js.map +1 -1
  177. package/dist/internal/planning/reward-epoch.d.ts +44 -0
  178. package/dist/internal/planning/reward-epoch.d.ts.map +1 -0
  179. package/dist/internal/planning/reward-epoch.js +220 -0
  180. package/dist/internal/planning/reward-epoch.js.map +1 -0
  181. package/dist/internal/planning/runtime-guards.d.ts.map +1 -1
  182. package/dist/internal/planning/runtime-guards.js +92 -13
  183. package/dist/internal/planning/runtime-guards.js.map +1 -1
  184. package/dist/internal/planning/starbase-repair-guard.d.ts +12 -0
  185. package/dist/internal/planning/starbase-repair-guard.d.ts.map +1 -0
  186. package/dist/internal/planning/starbase-repair-guard.js +54 -0
  187. package/dist/internal/planning/starbase-repair-guard.js.map +1 -0
  188. package/dist/internal/planning/starbase-system-guard.d.ts.map +1 -1
  189. package/dist/internal/planning/starbase-system-guard.js +48 -3
  190. package/dist/internal/planning/starbase-system-guard.js.map +1 -1
  191. package/dist/internal/planning/starbase-upgrade-storage-actions.d.ts +7 -0
  192. package/dist/internal/planning/starbase-upgrade-storage-actions.d.ts.map +1 -0
  193. package/dist/internal/planning/starbase-upgrade-storage-actions.js +71 -0
  194. package/dist/internal/planning/starbase-upgrade-storage-actions.js.map +1 -0
  195. package/dist/internal/planning/starbase-upgrade-window.d.ts +22 -0
  196. package/dist/internal/planning/starbase-upgrade-window.d.ts.map +1 -0
  197. package/dist/internal/planning/starbase-upgrade-window.js +64 -0
  198. package/dist/internal/planning/starbase-upgrade-window.js.map +1 -0
  199. package/dist/internal/planning/storage-action-readers.d.ts.map +1 -1
  200. package/dist/internal/planning/storage-action-readers.js +36 -3
  201. package/dist/internal/planning/storage-action-readers.js.map +1 -1
  202. package/dist/internal/planning/storage-actions.d.ts +5 -1
  203. package/dist/internal/planning/storage-actions.d.ts.map +1 -1
  204. package/dist/internal/planning/storage-actions.js +8 -1
  205. package/dist/internal/planning/storage-actions.js.map +1 -1
  206. package/dist/mining/actions/index.js +1 -1
  207. package/dist/mining/actions/index.js.map +1 -1
  208. package/dist/planning/assembly.d.ts +2 -0
  209. package/dist/planning/assembly.d.ts.map +1 -1
  210. package/dist/planning/assembly.js +5 -1
  211. package/dist/planning/assembly.js.map +1 -1
  212. package/dist/planning/execution.d.ts.map +1 -1
  213. package/dist/planning/execution.js +132 -5
  214. package/dist/planning/execution.js.map +1 -1
  215. package/dist/planning/index.d.ts +75 -0
  216. package/dist/planning/index.d.ts.map +1 -1
  217. package/dist/planning/index.js +1 -0
  218. package/dist/planning/index.js.map +1 -1
  219. package/dist/planning/plan-validation.d.ts.map +1 -1
  220. package/dist/planning/plan-validation.js +27 -0
  221. package/dist/planning/plan-validation.js.map +1 -1
  222. package/dist/planning/selected-references.d.ts +83 -1
  223. package/dist/planning/selected-references.d.ts.map +1 -1
  224. package/dist/planning/selected-references.js +192 -2
  225. package/dist/planning/selected-references.js.map +1 -1
  226. package/dist/planning/simulation.d.ts.map +1 -1
  227. package/dist/planning/simulation.js +11 -3
  228. package/dist/planning/simulation.js.map +1 -1
  229. package/dist/starbases/actions/democracy.d.ts +205 -0
  230. package/dist/starbases/actions/democracy.d.ts.map +1 -0
  231. package/dist/starbases/actions/democracy.js +861 -0
  232. package/dist/starbases/actions/democracy.js.map +1 -0
  233. package/dist/starbases/actions/index.d.ts +2 -0
  234. package/dist/starbases/actions/index.d.ts.map +1 -1
  235. package/dist/starbases/actions/index.js +2 -0
  236. package/dist/starbases/actions/index.js.map +1 -1
  237. package/dist/starbases/actions/upgrades.d.ts +116 -0
  238. package/dist/starbases/actions/upgrades.d.ts.map +1 -0
  239. package/dist/starbases/actions/upgrades.js +474 -0
  240. package/dist/starbases/actions/upgrades.js.map +1 -0
  241. package/dist/starbases/governance.d.ts +75 -0
  242. package/dist/starbases/governance.d.ts.map +1 -1
  243. package/dist/starbases/governance.js +82 -1
  244. package/dist/starbases/governance.js.map +1 -1
  245. package/dist/starbases/index.d.ts +1 -1
  246. package/dist/starbases/index.d.ts.map +1 -1
  247. package/dist/starbases/index.js +1 -1
  248. package/dist/starbases/index.js.map +1 -1
  249. package/package.json +2 -2
@@ -16,15 +16,19 @@ 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, 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';
25
+ import { describeFleetRental } from '../../internal/planning/fleet-rental.js';
26
+ import { SYSTEM_PROGRAM } from '../../internal/system-program.js';
24
27
  import { resolveCargo, } from '../../registry/index.js';
25
28
  import { accountAbsentPrecondition, accountStatePrecondition, } from '../../internal/planning/account-state.js';
26
29
  import { stimulantStatId } from '../../internal/c4/stimulant.js';
27
30
  import { readCombatStorageAction } from '../../internal/planning/combat-storage-actions.js';
31
+ import { resolveLoyaltyEarning, resolveRewardContext, } from '../../internal/planning/loyalty-earning.js';
28
32
  import { RENT_ADDRESS } from '../../internal/planning/rent.js';
29
33
  import { planStorageFunding } from '../../internal/planning/storage-actions.js';
30
34
  function invalid(field, value, acceptedRange, remedy) {
@@ -78,6 +82,40 @@ function validateRetrieveOptions(value) {
78
82
  }
79
83
  return { atUnixSeconds: options.atUnixSeconds, authorization };
80
84
  }
85
+ function validateRepairOptions(value) {
86
+ const options = readRecord(value, 'options');
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) {
108
+ const authorization = readPlanAuthorization(options.authorization);
109
+ const { maxRepairKits } = options;
110
+ if (maxRepairKits === undefined)
111
+ return { authorization };
112
+ if (!Number.isSafeInteger(maxRepairKits) ||
113
+ maxRepairKits < 1 ||
114
+ maxRepairKits > 4_294_967_295) {
115
+ invalid('options.maxRepairKits', maxRepairKits, 'a positive integer of at most 4,294,967,295', 'Cap the repair kits with a positive whole number, or omit maxRepairKits to let the repair use every kit the Fleet carries, before retrying.');
116
+ }
117
+ return { authorization, maxRepairKits: maxRepairKits };
118
+ }
81
119
  function denseArray(value, field) {
82
120
  if (!Array.isArray(value)) {
83
121
  return invalid(field, value, 'a dense ordered array', `Provide ${field} as a dense ordered array before retrying.`);
@@ -1062,6 +1100,563 @@ export async function planFleetAttackStarbase(ctx, attacker, target, inputStance
1062
1100
  summary: `${description} ${runtime.description}`,
1063
1101
  });
1064
1102
  }
1103
+ /** The planner that ends each stored Fleet state, for a Fleet that must be
1104
+ * Idle before it repairs. */
1105
+ const IDLE_REMEDY = {
1106
+ docked: 'Undock it with planFleetUndock',
1107
+ warp: 'Settle its arrival with planFleetSettleArrival once the warp ends',
1108
+ subwarp: 'Settle its arrival with planFleetSettleArrival once the subwarp ends, or stop it with planFleetStopSubwarp',
1109
+ mining: 'Stop mining with planFleetStopMining',
1110
+ };
1111
+ function squared(value) {
1112
+ return value * value;
1113
+ }
1114
+ /** Plans one Starbase repair by an owned Idle Fleet: the game takes repair
1115
+ * kits from the Fleet's cargo hold and queues pending hull points on the
1116
+ * Starbase, which flow into its hull over time.
1117
+ *
1118
+ * The planner requires a Fleet neither rented nor listed for rent, stored Idle
1119
+ * with its required crew, of the Starbase owner's faction (an unaligned Fleet
1120
+ * repairs an unaligned Starbase), within the Game's interaction range of the
1121
+ * System, carrying repair kits and able to repair, and a Starbase missing hull
1122
+ * points beyond those already queued. It states how many kits the repair uses
1123
+ * and how many hull points it queues from the state it read; both follow the
1124
+ * Starbase and Fleet when the transaction executes.
1125
+ *
1126
+ * The kits used can earn the Fleet's faction (MUD, ONI or Ustur) Loyalty
1127
+ * Points for the current reward epoch, and the game then needs the faction's
1128
+ * Loyalty epoch and the Profile's Loyalty contribution; the Plan opens
1129
+ * whichever is missing first, its rent paid by the authorization key's wallet.
1130
+ * The game refuses the repair outside the current reward epoch while rewards
1131
+ * are enabled, and so does the planner. Whether the active configuration
1132
+ * awards Points for repairs, and key permissions, remain chain-authoritative.
1133
+ *
1134
+ * @example
1135
+ * ```ts
1136
+ * declare const ctx: SageContext;
1137
+ * declare const fleet: FleetSnapshot;
1138
+ * declare const target: StarSystemSnapshot;
1139
+ * declare const authorization: PlanAuthorization;
1140
+ * const plan = await planFleetRepairStarbase(ctx, fleet, target, {
1141
+ * authorization,
1142
+ * });
1143
+ * console.log(plan.describe());
1144
+ * ```
1145
+ */
1146
+ export async function planFleetRepairStarbase(ctx, fleet, target, input) {
1147
+ const { authorization, maxRepairKits } = validateRepairOptions(input);
1148
+ const game = requireGameAddress(ctx);
1149
+ const { profile } = authorization;
1150
+ if (fleet.ownerProfile.address !== profile) {
1151
+ fail(`Fleet ${fleet.address} does not belong to authorization Profile ${profile}. Choose a Fleet owned by that Profile and retry.`, fleet.address);
1152
+ }
1153
+ if (fleet.game !== game) {
1154
+ fail(`Fleet ${fleet.address} belongs to Game ${fleet.game}, not configured Game ${game}. Refresh the Fleet through this context and retry.`, fleet.address);
1155
+ }
1156
+ if (target.game !== game ||
1157
+ (await deriveStarSystemAddress(ctx.programs, game, target.systemId)) !==
1158
+ target.address) {
1159
+ fail(`Star System ${target.address} is not the canonical System of id ${String(target.systemId)} in configured Game ${game}. Refresh it through this context and retry.`, target.address);
1160
+ }
1161
+ const [combat, [fleetCandidate, systemCandidate, clock]] = await Promise.all([
1162
+ readGameCombatConfiguration(ctx),
1163
+ readContextRawAccounts(ctx, [fleet.address, target.address, CLOCK_ADDRESS]),
1164
+ ]);
1165
+ const fleetAccount = requireAccount(fleetCandidate, fleet.address, `Fleet ${fleet.address} is missing. Refresh Fleet discovery and retry the repair.`);
1166
+ const current = fleetAccountDefinition.decode(fleetAccount, ctx.programs);
1167
+ const label = `Fleet ${current.name} (${fleet.address})`;
1168
+ if (current.game !== game ||
1169
+ current.ownerProfile !== profile ||
1170
+ (await deriveFleetAddress(ctx.programs, current)) !== fleet.address) {
1171
+ fail(`${label} is no longer the canonical Fleet of Profile ${profile} in configured Game ${game}. Refresh the Fleet and retry.`, fleet.address);
1172
+ }
1173
+ // As for Fleet disband and ship assembly, Atlas Kit acts only with a Fleet
1174
+ // its owner holds, not one rented out or listed for rent.
1175
+ if (current.subProfile !== SYSTEM_PROGRAM) {
1176
+ fail(`${label} is ${describeFleetRental(ctx.programs, current.subProfile)}, so its owner cannot repair with it. End the rental, refresh the Fleet and retry.`, fleet.address);
1177
+ }
1178
+ if (current.state.kind !== 'idle') {
1179
+ const remedy = IDLE_REMEDY[current.state.kind] ??
1180
+ 'Wait until the game returns it to Idle';
1181
+ fail(`${label} is ${current.state.kind === 'unrecognized' ? `in game state ${current.state.variant}` : current.state.kind}, and Atlas Kit plans a repair only for a Fleet stored Idle. ${remedy}, refresh the Fleet and retry.`, fleet.address);
1182
+ }
1183
+ if (current.crewCount < current.stats.misc.requiredCrew) {
1184
+ 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);
1185
+ }
1186
+ const systemAccount = requireAccount(systemCandidate, target.address, `Star System ${target.address} is missing. Refresh it and retry the repair.`);
1187
+ const system = starSystemAccountDefinition.decode(systemAccount, ctx.programs);
1188
+ const { starbase } = system;
1189
+ if (starbase === undefined || system.game !== game) {
1190
+ fail(`Star System ${system.name} (${target.address}) has no Starbase in configured Game ${game}. Choose a System with a Starbase and retry.`, target.address);
1191
+ }
1192
+ const where = `the ${starbase.level} Starbase at ${system.name} (${target.address})`;
1193
+ if (current.faction !== starbase.owner) {
1194
+ fail(`${label} is ${current.faction}, but ${where} belongs to ${starbase.owner}; the game repairs a Starbase only with a Fleet of its own faction. Choose a ${starbase.owner} Fleet and retry.`, fleet.address);
1195
+ }
1196
+ const info = starbase.maxLevel.levels.find((entry) => entry.level === starbase.level)?.info;
1197
+ if (info === undefined || info.repairCost.raw <= 0n) {
1198
+ fail(`${where} has no repair cost at its level, so the game cannot repair it.`, target.address);
1199
+ }
1200
+ // Pending points flow into the hull without changing their sum, so the
1201
+ // stored points give what the game finds missing when it settles.
1202
+ const missing = info.hp - starbase.hp - starbase.pendingHp;
1203
+ if (missing <= 0) {
1204
+ fail(`${where} has ${String(starbase.hp)} hull points and ${String(starbase.pendingHp)} queued for repair of its ${String(info.hp)} maximum, so nothing is missing. Choose a damaged Starbase.`, target.address);
1205
+ }
1206
+ const { repairAbility, repairEfficiency } = current.stats.combat;
1207
+ if (repairAbility.raw <= 0n || repairEfficiency.raw <= 0n) {
1208
+ fail(`${label} has repair ability ${String(repairAbility.value)} and repair efficiency ${String(repairEfficiency.value)}; the game repairs only with both above zero. Add ships that can repair and retry.`, fleet.address);
1209
+ }
1210
+ const kitCargo = combat.data.repairKitCargoId;
1211
+ const held = current.cargoHold.amounts.find(({ cargoId }) => cargoId === kitCargo)
1212
+ ?.amount ?? 0n;
1213
+ if (held <= 0n) {
1214
+ fail(`${label} carries no repair kits (cargo ${String(kitCargo)}). Load repair kits into its cargo hold and retry.`, fleet.address);
1215
+ }
1216
+ const range = combat.data.interactionRange;
1217
+ const dx = current.locationRaw.x - system.coordinatesRaw.x;
1218
+ const dy = current.locationRaw.y - system.coordinatesRaw.y;
1219
+ if (squared(dx) + squared(dy) > squared(range.raw)) {
1220
+ const distance = Math.hypot(current.location.x - system.coordinates.x, current.location.y - system.coordinates.y);
1221
+ fail(`${label} is ${distance.toFixed(3)} from ${where}, beyond the Game's interaction range of ${String(range.value)}. Move the Fleet within range, refresh it and retry.`, fleet.address);
1222
+ }
1223
+ // The game spends at most the Fleet's repair ability in kits, and only the
1224
+ // kits the missing hull needs.
1225
+ const available = maxRepairKits === undefined || BigInt(maxRepairKits) > held
1226
+ ? held
1227
+ : BigInt(maxRepairKits);
1228
+ const cost = info.repairCost.value;
1229
+ const perKit = cost * repairEfficiency.value;
1230
+ const usable = Math.min(repairAbility.value, Number(available));
1231
+ const hull = Math.min(missing, usable * perKit);
1232
+ if (Math.floor(hull) < 1) {
1233
+ fail(`${label} would restore less than one hull point to ${where}, and the game refuses a repair that restores nothing. Use a Fleet with more repair ability or kits.`, fleet.address);
1234
+ }
1235
+ const kits = Math.max(1, Math.ceil(hull / perKit - 1e-9));
1236
+ const now = readClock(requireAccount(clock, CLOCK_ADDRESS, 'The Clock sysvar is missing. Refresh chain time and retry the repair.'));
1237
+ const reward = await resolveRewardContext(ctx, game, now, 'Starbase repairs');
1238
+ const rate = reward.config.repairKitLpRateRaw;
1239
+ const faction = factionValue(current.faction);
1240
+ const earns = rate > 0n && faction >= 1 && faction <= 3;
1241
+ const loyalty = await resolveLoyaltyEarning(ctx, {
1242
+ game,
1243
+ profile,
1244
+ funder: authorization.authority,
1245
+ faction,
1246
+ reward,
1247
+ earns,
1248
+ });
1249
+ const instruction = adaptRepairStarbaseInstruction(ctx.programs, {
1250
+ authorization,
1251
+ fleet: fleet.address,
1252
+ system: target.address,
1253
+ game,
1254
+ rewardRegistry: reward.registry,
1255
+ rewardConfig: reward.rewardConfig,
1256
+ ...(loyalty.loyaltyEpoch === undefined
1257
+ ? {}
1258
+ : { loyaltyEpoch: loyalty.loyaltyEpoch }),
1259
+ ...(loyalty.loyaltyContribution === undefined
1260
+ ? {}
1261
+ : { loyaltyContribution: loyalty.loyaltyContribution }),
1262
+ ...(maxRepairKits === undefined ? {} : { maxRepairKits }),
1263
+ });
1264
+ const storage = await planFleetStorage(ctx, instruction, [fleet.address], profile, 'Starbase repair');
1265
+ const points = earns
1266
+ ? ` If the active reward configuration awards Loyalty Points for repairs, the kits used earn ${String(rate)} each in reward epoch ${String(reward.currentEpoch)}.`
1267
+ : '';
1268
+ const description = `Repair ${where} with ${label}. The Starbase is missing ${String(missing)} of its ${String(info.hp)} hull points; the game uses about ${String(kits)} of the Fleet's ${String(held)} repair kits${maxRepairKits === undefined ? '' : ` (capped at ${String(maxRepairKits)})`} to queue about ${String(Math.floor(hull))} hull points, which flow into the hull over time.${points} The kits used and hull points queued follow the Starbase and Fleet when the transaction executes; key permissions remain chain-authoritative. ${storage.disclosure}`;
1269
+ return buildPlannerPlan(ctx.programs, {
1270
+ kind: 'combat.repair-starbase',
1271
+ preconditions: [
1272
+ loyalty.guard,
1273
+ await accountStatePrecondition(fleetAccount, `${label} stays Idle at its location with its crew, faction, stats and repair kits.`),
1274
+ {
1275
+ kind: 'starbase-system',
1276
+ address: target.address,
1277
+ game,
1278
+ starbaseSequenceId: system.sequenceId,
1279
+ describes: `Star System ${system.name} keeps its canonical Game identity, active Starbase and sequence ${String(system.sequenceId)}; its hull and other shared activity may change.`,
1280
+ },
1281
+ ...loyalty.preconditions,
1282
+ storage.guard,
1283
+ ],
1284
+ steps: [
1285
+ ...loyalty.steps,
1286
+ {
1287
+ describes: description,
1288
+ instruction,
1289
+ signers: [authorization.authority],
1290
+ },
1291
+ ],
1292
+ summary: `Repair the Starbase at ${system.name} with Fleet ${current.name}.`,
1293
+ });
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
+ }
1065
1660
  function lootSnapshotFingerprint(loot) {
1066
1661
  return [
1067
1662
  loot.address,