@aephia/atlas-kit 0.8.0-next.2 → 0.8.0-next.20

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 (181) hide show
  1. package/dist/claim-stakes/actions/index.d.ts +2 -1
  2. package/dist/claim-stakes/actions/index.d.ts.map +1 -1
  3. package/dist/claim-stakes/actions/index.js +10 -11
  4. package/dist/claim-stakes/actions/index.js.map +1 -1
  5. package/dist/client/contracts.d.ts +1 -1
  6. package/dist/client/contracts.d.ts.map +1 -1
  7. package/dist/client/deployments.d.ts +1 -1
  8. package/dist/client/deployments.js +1 -1
  9. package/dist/client/errors.d.ts +1 -1
  10. package/dist/client/errors.d.ts.map +1 -1
  11. package/dist/client/errors.js.map +1 -1
  12. package/dist/combat/actions/index.d.ts.map +1 -1
  13. package/dist/combat/actions/index.js +6 -0
  14. package/dist/combat/actions/index.js.map +1 -1
  15. package/dist/crafting/actions/habs.d.ts +319 -0
  16. package/dist/crafting/actions/habs.d.ts.map +1 -0
  17. package/dist/crafting/actions/habs.js +931 -0
  18. package/dist/crafting/actions/habs.js.map +1 -0
  19. package/dist/crafting/actions/index.d.ts +22 -9
  20. package/dist/crafting/actions/index.d.ts.map +1 -1
  21. package/dist/crafting/actions/index.js +68 -20
  22. package/dist/crafting/actions/index.js.map +1 -1
  23. package/dist/crafting/index.d.ts +21 -2
  24. package/dist/crafting/index.d.ts.map +1 -1
  25. package/dist/crafting/index.js +5 -1
  26. package/dist/crafting/index.js.map +1 -1
  27. package/dist/fleets/actions/index.d.ts +10 -8
  28. package/dist/fleets/actions/index.d.ts.map +1 -1
  29. package/dist/fleets/actions/index.js +15 -13
  30. package/dist/fleets/actions/index.js.map +1 -1
  31. package/dist/identity/index.d.ts +169 -17
  32. package/dist/identity/index.d.ts.map +1 -1
  33. package/dist/identity/index.js +142 -9
  34. package/dist/identity/index.js.map +1 -1
  35. package/dist/internal/c4/career-xp.d.ts +113 -26
  36. package/dist/internal/c4/career-xp.d.ts.map +1 -1
  37. package/dist/internal/c4/career-xp.js +101 -38
  38. package/dist/internal/c4/career-xp.js.map +1 -1
  39. package/dist/internal/c4/character-registration.d.ts.map +1 -1
  40. package/dist/internal/c4/character-registration.js +3 -0
  41. package/dist/internal/c4/character-registration.js.map +1 -1
  42. package/dist/internal/c4/character.d.ts +68 -0
  43. package/dist/internal/c4/character.d.ts.map +1 -1
  44. package/dist/internal/c4/character.js +46 -2
  45. package/dist/internal/c4/character.js.map +1 -1
  46. package/dist/internal/c4/claim-stake.d.ts +0 -1
  47. package/dist/internal/c4/claim-stake.d.ts.map +1 -1
  48. package/dist/internal/c4/claim-stake.js +23 -1
  49. package/dist/internal/c4/claim-stake.js.map +1 -1
  50. package/dist/internal/c4/crafting-hab-storage.d.ts +38 -0
  51. package/dist/internal/c4/crafting-hab-storage.d.ts.map +1 -0
  52. package/dist/internal/c4/crafting-hab-storage.js +164 -0
  53. package/dist/internal/c4/crafting-hab-storage.js.map +1 -0
  54. package/dist/internal/c4/crafting.d.ts +3 -1
  55. package/dist/internal/c4/crafting.d.ts.map +1 -1
  56. package/dist/internal/c4/crafting.js.map +1 -1
  57. package/dist/internal/c4/discriminators.d.ts +25 -0
  58. package/dist/internal/c4/discriminators.d.ts.map +1 -1
  59. package/dist/internal/c4/discriminators.js +51 -1
  60. package/dist/internal/c4/discriminators.js.map +1 -1
  61. package/dist/internal/c4/fleet-storage.d.ts +2 -1
  62. package/dist/internal/c4/fleet-storage.d.ts.map +1 -1
  63. package/dist/internal/c4/fleet-storage.js +14 -5
  64. package/dist/internal/c4/fleet-storage.js.map +1 -1
  65. package/dist/internal/c4/fleet.d.ts +49 -0
  66. package/dist/internal/c4/fleet.d.ts.map +1 -1
  67. package/dist/internal/c4/fleet.js +88 -5
  68. package/dist/internal/c4/fleet.js.map +1 -1
  69. package/dist/internal/c4/game.d.ts +12 -0
  70. package/dist/internal/c4/game.d.ts.map +1 -1
  71. package/dist/internal/c4/game.js +17 -0
  72. package/dist/internal/c4/game.js.map +1 -1
  73. package/dist/internal/c4/governance.d.ts +313 -0
  74. package/dist/internal/c4/governance.d.ts.map +1 -0
  75. package/dist/internal/c4/governance.js +471 -0
  76. package/dist/internal/c4/governance.js.map +1 -0
  77. package/dist/internal/c4/runtime-bindings.d.ts +1 -1
  78. package/dist/internal/c4/runtime-bindings.d.ts.map +1 -1
  79. package/dist/internal/c4/runtime-bindings.js +1 -1
  80. package/dist/internal/c4/runtime-bindings.js.map +1 -1
  81. package/dist/internal/c4/world.d.ts +3 -2
  82. package/dist/internal/c4/world.d.ts.map +1 -1
  83. package/dist/internal/c4/world.js +4 -18
  84. package/dist/internal/c4/world.js.map +1 -1
  85. package/dist/internal/crafting-process-state.d.ts +16 -3
  86. package/dist/internal/crafting-process-state.d.ts.map +1 -1
  87. package/dist/internal/crafting-process-state.js +44 -0
  88. package/dist/internal/crafting-process-state.js.map +1 -1
  89. package/dist/internal/fleet.d.ts.map +1 -1
  90. package/dist/internal/fleet.js +1 -0
  91. package/dist/internal/fleet.js.map +1 -1
  92. package/dist/internal/planning/authorization-adapter.d.ts +210 -1
  93. package/dist/internal/planning/authorization-adapter.d.ts.map +1 -1
  94. package/dist/internal/planning/authorization-adapter.js +298 -1
  95. package/dist/internal/planning/authorization-adapter.js.map +1 -1
  96. package/dist/internal/planning/crafting-hab-storage-actions.d.ts +10 -0
  97. package/dist/internal/planning/crafting-hab-storage-actions.d.ts.map +1 -0
  98. package/dist/internal/planning/crafting-hab-storage-actions.js +46 -0
  99. package/dist/internal/planning/crafting-hab-storage-actions.js.map +1 -0
  100. package/dist/internal/planning/democracy-storage-actions.d.ts +12 -0
  101. package/dist/internal/planning/democracy-storage-actions.d.ts.map +1 -0
  102. package/dist/internal/planning/democracy-storage-actions.js +81 -0
  103. package/dist/internal/planning/democracy-storage-actions.js.map +1 -0
  104. package/dist/internal/planning/fleet-state.d.ts.map +1 -1
  105. package/dist/internal/planning/fleet-state.js +1 -0
  106. package/dist/internal/planning/fleet-state.js.map +1 -1
  107. package/dist/internal/planning/governance-storage-actions.d.ts +9 -0
  108. package/dist/internal/planning/governance-storage-actions.d.ts.map +1 -0
  109. package/dist/internal/planning/governance-storage-actions.js +89 -0
  110. package/dist/internal/planning/governance-storage-actions.js.map +1 -0
  111. package/dist/internal/planning/placement-fee.d.ts +6 -0
  112. package/dist/internal/planning/placement-fee.d.ts.map +1 -0
  113. package/dist/internal/planning/placement-fee.js +9 -0
  114. package/dist/internal/planning/placement-fee.js.map +1 -0
  115. package/dist/internal/planning/profile-storage-funding-guard.d.ts +1 -1
  116. package/dist/internal/planning/profile-storage-funding-guard.d.ts.map +1 -1
  117. package/dist/internal/planning/profile-storage-funding-guard.js +44 -1
  118. package/dist/internal/planning/profile-storage-funding-guard.js.map +1 -1
  119. package/dist/internal/planning/research-unlock.d.ts.map +1 -1
  120. package/dist/internal/planning/research-unlock.js.map +1 -1
  121. package/dist/internal/planning/runtime-guards.d.ts.map +1 -1
  122. package/dist/internal/planning/runtime-guards.js +30 -2
  123. package/dist/internal/planning/runtime-guards.js.map +1 -1
  124. package/dist/internal/planning/storage-action-readers.d.ts.map +1 -1
  125. package/dist/internal/planning/storage-action-readers.js +16 -0
  126. package/dist/internal/planning/storage-action-readers.js.map +1 -1
  127. package/dist/mining/actions/index.d.ts +6 -1
  128. package/dist/mining/actions/index.d.ts.map +1 -1
  129. package/dist/mining/actions/index.js +14 -1
  130. package/dist/mining/actions/index.js.map +1 -1
  131. package/dist/mining/exit-fuel.d.ts +47 -0
  132. package/dist/mining/exit-fuel.d.ts.map +1 -0
  133. package/dist/mining/exit-fuel.js +47 -0
  134. package/dist/mining/exit-fuel.js.map +1 -0
  135. package/dist/mining/index.d.ts +1 -0
  136. package/dist/mining/index.d.ts.map +1 -1
  137. package/dist/mining/index.js +1 -0
  138. package/dist/mining/index.js.map +1 -1
  139. package/dist/mining/profile.d.ts +2 -1
  140. package/dist/mining/profile.d.ts.map +1 -1
  141. package/dist/mining/profile.js +2 -1
  142. package/dist/mining/profile.js.map +1 -1
  143. package/dist/planning/assembly.d.ts +2 -0
  144. package/dist/planning/assembly.d.ts.map +1 -1
  145. package/dist/planning/assembly.js +5 -1
  146. package/dist/planning/assembly.js.map +1 -1
  147. package/dist/planning/execution.d.ts.map +1 -1
  148. package/dist/planning/execution.js +20 -4
  149. package/dist/planning/execution.js.map +1 -1
  150. package/dist/planning/index.d.ts +1 -0
  151. package/dist/planning/index.d.ts.map +1 -1
  152. package/dist/planning/index.js +1 -0
  153. package/dist/planning/index.js.map +1 -1
  154. package/dist/planning/selected-references.d.ts +83 -1
  155. package/dist/planning/selected-references.d.ts.map +1 -1
  156. package/dist/planning/selected-references.js +192 -2
  157. package/dist/planning/selected-references.js.map +1 -1
  158. package/dist/planning/simulation.d.ts.map +1 -1
  159. package/dist/planning/simulation.js +11 -3
  160. package/dist/planning/simulation.js.map +1 -1
  161. package/dist/starbases/actions/democracy.d.ts +205 -0
  162. package/dist/starbases/actions/democracy.d.ts.map +1 -0
  163. package/dist/starbases/actions/democracy.js +861 -0
  164. package/dist/starbases/actions/democracy.js.map +1 -0
  165. package/dist/starbases/actions/governance.d.ts +78 -0
  166. package/dist/starbases/actions/governance.d.ts.map +1 -0
  167. package/dist/starbases/actions/governance.js +382 -0
  168. package/dist/starbases/actions/governance.js.map +1 -0
  169. package/dist/starbases/actions/index.d.ts +2 -1
  170. package/dist/starbases/actions/index.d.ts.map +1 -1
  171. package/dist/starbases/actions/index.js +2 -0
  172. package/dist/starbases/actions/index.js.map +1 -1
  173. package/dist/starbases/governance.d.ts +445 -0
  174. package/dist/starbases/governance.d.ts.map +1 -0
  175. package/dist/starbases/governance.js +503 -0
  176. package/dist/starbases/governance.js.map +1 -0
  177. package/dist/starbases/index.d.ts +1 -0
  178. package/dist/starbases/index.d.ts.map +1 -1
  179. package/dist/starbases/index.js +1 -0
  180. package/dist/starbases/index.js.map +1 -1
  181. package/package.json +2 -2
@@ -0,0 +1,861 @@
1
+ import { isAddress } from '@solana/kit';
2
+ import { InvalidActionInputError, SageSdkError } from '../../client/errors.js';
3
+ import { readContextRawAccounts } from '../../client/reconciliation.js';
4
+ import { findCharacterPda } from '../../internal/c4/character.js';
5
+ import { factionValue } from '../../internal/c4/faction.js';
6
+ import { democracyAllocationAccountDefinition, democracyAllocationHistoryAccountDefinition, democracyBackingAccountDefinition, democracyCurveAccountDefinition, democracyGenerationHistoryAccountDefinition, democracyHistoryDayAccountDefinition, democracyHistoryPolicyAccountDefinition, democracyHousingMapAccountDefinition, democracyIdentityAccountDefinition, democracyProfileRouteAccountDefinition, democracyRequirementsAccountDefinition, democracyRootAccountDefinition, democracySystemHistoryAccountDefinition, deriveAllocationAddress, deriveAllocationHistoryAddress, deriveBackingAddress, deriveCurveAddress, deriveHistoryDayAddress, deriveHousingMapAddress, deriveProfileRouteAddress, deriveRequirementsAddress, deriveRootAddress, deriveSettlementAddress, governanceModuleStatusAccountDefinition, } from '../../internal/c4/governance.js';
7
+ import { deriveDemocracySystemHistoryAddress, deriveGovernanceModuleStatusAddress, } from '../../internal/c4/pda.js';
8
+ import { starbasePlayerAccountDefinition, } from '../../internal/c4/starbase.js';
9
+ import { starSystemAccountDefinition } from '../../internal/c4/world.js';
10
+ import { requireGameAddress } from '../../internal/game-context.js';
11
+ import { accountAbsentPrecondition, accountStatePrecondition, } from '../../internal/planning/account-state.js';
12
+ import { adaptDepositDemocracyBackingInstruction, adaptInitDemocracyAllocationInstruction, adaptReleaseDemocracyBackingInstruction, adaptRequestDemocracyAllocationInstruction, adaptSettleDemocracyAllocationInstruction, readPlanAuthorization, } from '../../internal/planning/authorization-adapter.js';
13
+ import { readDemocracyStorageAction } from '../../internal/planning/democracy-storage-actions.js';
14
+ import { CLOCK_ADDRESS, readClock, } from '../../internal/planning/faction-enrollment.js';
15
+ import { RENT_ADDRESS } from '../../internal/planning/rent.js';
16
+ import { planStorageFunding } from '../../internal/planning/storage-actions.js';
17
+ import { buildPlannerPlan } from '../../planning/plan-construction.js';
18
+ const SECONDS_PER_DAY = 86400n;
19
+ const REQUIREMENTS_EPOCH_SECONDS = 604800n;
20
+ const U32_MAX = 4_294_967_295;
21
+ const U64_MAX = 18446744073709551615n;
22
+ const BPS = 10_000;
23
+ const FACTIONS = ['', 'MUD', 'ONI', 'Ustur'];
24
+ const HOUSING_SLOTS = 18;
25
+ function fail(message, address) {
26
+ throw new SageSdkError('ACTION_PRECONDITION_FAILED', message, { address });
27
+ }
28
+ function invalid(field, value, accepted, remedy) {
29
+ throw new InvalidActionInputError(field, value, accepted, remedy);
30
+ }
31
+ function readOptions(value, required, optional = []) {
32
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
33
+ return invalid('options', value, 'a plain object', 'Provide the documented options object before retrying.');
34
+ const options = value;
35
+ const missing = required.find((key) => !Object.hasOwn(options, key));
36
+ const unexpected = Object.keys(options).find((key) => !required.includes(key) && !optional.includes(key));
37
+ if (missing !== undefined || unexpected !== undefined)
38
+ invalid('options', missing === undefined ? unexpected : `missing ${missing}`, `the fields ${[...required, ...optional].join(', ')}`, 'Remove unknown fields and provide every required option before retrying.');
39
+ return options;
40
+ }
41
+ function present(raw, address, message) {
42
+ if (raw === undefined || raw.executable)
43
+ return fail(message, address);
44
+ return raw;
45
+ }
46
+ function idleCrew(player) {
47
+ return player.totalCrew - player.busyCrew;
48
+ }
49
+ /** Reads the Profile's Democracy identity and root, and the System's
50
+ * history, Governance Module status and chain time. */
51
+ async function readPosition(ctx, system, profile, label) {
52
+ const game = requireGameAddress(ctx);
53
+ const [routeAddress, [historyAddress], [moduleStatus]] = await Promise.all([
54
+ deriveProfileRouteAddress(ctx.programs, game, profile),
55
+ deriveDemocracySystemHistoryAddress(ctx.programs, system),
56
+ deriveGovernanceModuleStatusAddress(ctx.programs, game, system),
57
+ ]);
58
+ const [routeCandidate, historyCandidate, statusCandidate, clock] = await readContextRawAccounts(ctx, [
59
+ routeAddress,
60
+ historyAddress,
61
+ moduleStatus,
62
+ CLOCK_ADDRESS,
63
+ ]);
64
+ const route = present(routeCandidate, routeAddress, `Profile ${profile} has not joined Democracy, so it cannot ${label}. Join Democracy through the game's onboarding, which the game operator co-signs, and retry.`);
65
+ const routeData = democracyProfileRouteAccountDefinition.decode(route, ctx.programs);
66
+ if (routeData.game !== game || routeData.profile !== profile)
67
+ fail(`Democracy route ${routeAddress} contradicts Profile ${profile} or the configured Game. Refresh the governance accounts and retry.`, routeAddress);
68
+ const rootAddress = await deriveRootAddress(ctx.programs, routeData.identity);
69
+ const [identityCandidate, rootCandidate] = await readContextRawAccounts(ctx, [
70
+ routeData.identity,
71
+ rootAddress,
72
+ ]);
73
+ const identity = present(identityCandidate, routeData.identity, `Democracy identity ${routeData.identity} is missing. Refresh the governance accounts and retry.`);
74
+ const identityData = democracyIdentityAccountDefinition.decode(identity, ctx.programs);
75
+ if (identityData.game !== game)
76
+ fail(`Democracy identity ${routeData.identity} belongs to another Game. Verify the configured Game and retry.`, routeData.identity);
77
+ if (identityData.status !== 'active')
78
+ fail(`Democracy identity ${routeData.identity} is ${identityData.status}; only an active identity can ${label}. Finish joining Democracy and retry.`, routeData.identity);
79
+ if (identityData.authorizingProfile !== profile)
80
+ fail(`Democracy identity ${routeData.identity} acts through Profile ${identityData.authorizingProfile}, not ${profile}. Authorize with that Profile and retry.`, routeData.identity);
81
+ const root = present(rootCandidate, rootAddress, `Democracy root ${rootAddress} is missing. Refresh the governance accounts and retry.`);
82
+ const rootData = democracyRootAccountDefinition.decode(root, ctx.programs);
83
+ if (rootData.game !== game || rootData.identity !== routeData.identity)
84
+ fail(`Democracy root ${rootAddress} contradicts its identity or the configured Game. Refresh the governance accounts and retry.`, rootAddress);
85
+ const history = present(historyCandidate, historyAddress, `Star System ${system} has no Democracy history, so it has no Democracy to ${label} in. Choose a governed System and retry.`);
86
+ const historyData = democracySystemHistoryAccountDefinition.decode(history, ctx.programs);
87
+ if (historyData.game !== game || historyData.system !== system)
88
+ fail(`Democracy history ${historyAddress} contradicts Star System ${system} or the configured Game. Refresh the governance accounts and retry.`, historyAddress);
89
+ const status = statusCandidate === undefined
90
+ ? undefined
91
+ : governanceModuleStatusAccountDefinition.decode(statusCandidate, ctx.programs);
92
+ const moduleInstalled = status !== undefined &&
93
+ status.game === game &&
94
+ status.system === system &&
95
+ status.generationNumber === historyData.generationNumber &&
96
+ status.starbaseSequenceId === historyData.starbaseSequenceId &&
97
+ status.controllerFactionId === historyData.controllerFactionId;
98
+ const now = readClock(present(clock, CLOCK_ADDRESS, 'The Clock sysvar is missing. Refresh chain time and retry.'));
99
+ return {
100
+ game,
101
+ system,
102
+ profile,
103
+ identity,
104
+ identityData,
105
+ root,
106
+ rootData,
107
+ history,
108
+ historyData,
109
+ moduleStatus,
110
+ moduleInstalled,
111
+ now,
112
+ today: now / SECONDS_PER_DAY,
113
+ };
114
+ }
115
+ /** Refuses unless the System's Democracy is open today in its current,
116
+ * enabled, controlled generation with an installed Governance Module. */
117
+ function requireLive(position, generation, label) {
118
+ const { historyData, system, today } = position;
119
+ if (historyData.openDay !== today)
120
+ fail(`Star System ${system}'s Democracy history is still open on UTC day ${historyData.openDay}, before today (${today}), so the game refuses Democracy actions there until the earlier days are closed. Anyone can close them; retry once the history reaches today.`, position.history.address);
121
+ if (!historyData.enabled ||
122
+ !generation.enabled ||
123
+ historyData.controllerFactionId === 0)
124
+ fail(`Star System ${system} has no controlling faction with Democracy enabled, so no one can ${label} there. Choose another System and retry.`, system);
125
+ if (!position.moduleInstalled)
126
+ fail(`Star System ${system} has no Governance Module installed for its current controller and generation, so the game refuses to ${label} there. Build and install the module first, or choose a System that has one, and retry.`, position.moduleStatus);
127
+ }
128
+ async function readAllocation(ctx, snapshot, profile, label) {
129
+ const position = await readPosition(ctx, snapshot.system.address, profile, label);
130
+ if (snapshot.identity !== position.identity.address)
131
+ fail(`Democracy allocation ${snapshot.address} belongs to identity ${snapshot.identity}, not Profile ${profile}'s identity ${position.identity.address}. Use the owning Profile and retry.`, snapshot.address);
132
+ const expected = await deriveAllocationAddress(ctx.programs, position.root.address, snapshot.generation);
133
+ if (expected !== snapshot.address)
134
+ fail(`Democracy allocation ${snapshot.address} is not the identity's allocation in generation ${snapshot.generation}. Refresh it and retry.`, snapshot.address);
135
+ const recordAddress = await deriveAllocationHistoryAddress(ctx.programs, snapshot.address);
136
+ const [allocationCandidate, recordCandidate, generationCandidate] = await readContextRawAccounts(ctx, [
137
+ snapshot.address,
138
+ recordAddress,
139
+ snapshot.generation,
140
+ ]);
141
+ const allocation = present(allocationCandidate, snapshot.address, `Democracy allocation ${snapshot.address} is missing. Refresh it and retry.`);
142
+ const allocationData = democracyAllocationAccountDefinition.decode(allocation, ctx.programs);
143
+ const record = present(recordCandidate, recordAddress, `The vote and reward record of Democracy allocation ${snapshot.address} is missing. Refresh it and retry.`);
144
+ const recordData = democracyAllocationHistoryAccountDefinition.decode(record, ctx.programs);
145
+ const generation = present(generationCandidate, snapshot.generation, `Democracy generation ${snapshot.generation} is missing. Refresh the allocation and retry.`);
146
+ const generationData = democracyGenerationHistoryAccountDefinition.decode(generation, ctx.programs);
147
+ if (allocationData.game !== position.game ||
148
+ allocationData.root !== position.root.address ||
149
+ allocationData.system !== position.system ||
150
+ allocationData.generation !== snapshot.generation ||
151
+ recordData.allocation !== snapshot.address ||
152
+ recordData.identity !== position.identity.address ||
153
+ recordData.generation !== snapshot.generation ||
154
+ recordData.allocationRevision !== allocationData.revision ||
155
+ generationData.system !== position.system ||
156
+ generationData.game !== position.game ||
157
+ generationData.starbaseSequenceId !== allocationData.starbaseSequenceId)
158
+ fail(`Democracy allocation ${snapshot.address} contradicts its identity, System, generation or record. Refresh the governance accounts and retry.`, snapshot.address);
159
+ if (allocationData.status === 'closed')
160
+ fail(`Democracy allocation ${snapshot.address} is closed and accepts no more actions.`, snapshot.address);
161
+ return {
162
+ ...position,
163
+ generation,
164
+ generationData,
165
+ allocation,
166
+ allocationData,
167
+ record,
168
+ recordData,
169
+ accounts: {
170
+ game: position.game,
171
+ identity: position.identity.address,
172
+ root: position.root.address,
173
+ allocation: snapshot.address,
174
+ allocationHistory: recordAddress,
175
+ generation: snapshot.generation,
176
+ },
177
+ };
178
+ }
179
+ function revisions(allocation) {
180
+ return {
181
+ authorization: allocation.identityData.authorizationRevision,
182
+ root: allocation.rootData.revision,
183
+ allocation: allocation.allocationData.revision,
184
+ };
185
+ }
186
+ /** Requires the allocation's System generation to be the System's current
187
+ * one. */
188
+ function requireCurrentGeneration(allocation, label) {
189
+ if (allocation.historyData.generation !== allocation.accounts.generation ||
190
+ allocation.generationData.retired)
191
+ fail(`Democracy allocation ${allocation.accounts.allocation} belongs to an earlier generation of Star System ${allocation.system}, so it cannot ${label}. Atlas Kit does not plan winding it down yet; settle it in the game client, then release its backing.`, allocation.accounts.allocation);
192
+ }
193
+ async function positionPreconditions(allocation) {
194
+ return Promise.all([
195
+ accountStatePrecondition(allocation.allocation, `Democracy allocation ${allocation.accounts.allocation} stays at revision ${allocation.allocationData.revision}.`),
196
+ accountStatePrecondition(allocation.record, `Its vote and reward record stays unchanged.`),
197
+ accountStatePrecondition(allocation.root, `Democracy root ${allocation.root.address} stays at revision ${allocation.rootData.revision}.`),
198
+ ]);
199
+ }
200
+ /** Reads the authorization Profile's current Starbase Player in a System and
201
+ * requires it to belong to the System's controlling faction. */
202
+ async function readStarbasePlayer(ctx, position, snapshot, sequenceId) {
203
+ if (snapshot.playerProfile.address !== position.profile ||
204
+ snapshot.system.address !== position.system)
205
+ fail(`Starbase Player ${snapshot.address} belongs to Profile ${snapshot.playerProfile.address} at Star System ${snapshot.system.address}, not Profile ${position.profile} at ${position.system}. Use the authorization Profile's Starbase Player in the allocation's System and retry.`, snapshot.address);
206
+ const character = await findCharacterPda(ctx.programs, position.profile, position.game);
207
+ const [candidate] = await readContextRawAccounts(ctx, [snapshot.address]);
208
+ const raw = present(candidate, snapshot.address, `Starbase Player ${snapshot.address} is missing. Register at the Starbase and retry.`);
209
+ const data = starbasePlayerAccountDefinition.decode(raw, ctx.programs);
210
+ if (data.playerProfile !== position.profile ||
211
+ data.system !== position.system ||
212
+ data.character !== character)
213
+ fail(`Starbase Player ${snapshot.address} no longer matches Profile ${position.profile}, its Character or Star System ${position.system}. Refresh it and retry.`, snapshot.address);
214
+ if (data.sequenceId !== sequenceId)
215
+ fail(`Starbase Player ${snapshot.address} belongs to an earlier Starbase at Star System ${position.system}. Register at the current Starbase and retry.`, snapshot.address);
216
+ const faction = factionValue(data.faction);
217
+ const controller = position.historyData.controllerFactionId;
218
+ if (faction !== controller)
219
+ fail(`Starbase Player ${snapshot.address} is ${faction === 0 ? 'unaligned' : FACTIONS[faction]}, but ${FACTIONS[controller]} controls Star System ${position.system}; only the controlling faction can back voting power there.`, snapshot.address);
220
+ return { raw, data };
221
+ }
222
+ /** Plans opening a Democracy allocation in a System's current generation:
223
+ * the record that holds the Profile's voting power, backing and vote there.
224
+ *
225
+ * An allocation starts with no voting power; deposit backing, then request
226
+ * voting power. The Profile pays the allocation's and its record's rent.
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * declare const ctx: SageContext;
231
+ * declare const governance: StarbaseGovernanceSnapshot;
232
+ * declare const authorization: PlanAuthorization;
233
+ * const plan = await planOpenDemocracyAllocation(ctx, governance, {
234
+ * authorization,
235
+ * });
236
+ * console.log(plan.describe());
237
+ * ```
238
+ */
239
+ export async function planOpenDemocracyAllocation(ctx, governance, input) {
240
+ const options = readOptions(input, ['authorization']);
241
+ const authorization = readPlanAuthorization(options.authorization);
242
+ const system = governance.system.address;
243
+ const position = await readPosition(ctx, system, authorization.profile, 'open an allocation');
244
+ const generationAddress = position.historyData.generation;
245
+ if (generationAddress === undefined)
246
+ return fail(`Star System ${system} has no current Democracy generation. Retry once a faction controls it.`, system);
247
+ const [allocationAddress, [generationCandidate, profileCandidate, rent]] = await Promise.all([
248
+ deriveAllocationAddress(ctx.programs, position.root.address, generationAddress),
249
+ readContextRawAccounts(ctx, [
250
+ generationAddress,
251
+ authorization.profile,
252
+ RENT_ADDRESS,
253
+ ]),
254
+ ]);
255
+ const generation = present(generationCandidate, generationAddress, `Democracy generation ${generationAddress} is missing. Refresh the governance accounts and retry.`);
256
+ const generationData = democracyGenerationHistoryAccountDefinition.decode(generation, ctx.programs);
257
+ if (generationData.system !== system ||
258
+ generationData.generationNumber !== position.historyData.generationNumber)
259
+ fail(`Democracy generation ${generationAddress} contradicts Star System ${system}'s history. Refresh the governance accounts and retry.`, generationAddress);
260
+ requireLive(position, generationData, 'open an allocation');
261
+ const [recordAddress, [existing]] = await Promise.all([
262
+ deriveAllocationHistoryAddress(ctx.programs, allocationAddress),
263
+ readContextRawAccounts(ctx, [allocationAddress]),
264
+ ]);
265
+ if (existing !== undefined)
266
+ fail(`Profile ${authorization.profile} already has Democracy allocation ${allocationAddress} in Star System ${system}'s current generation. Use it instead.`, allocationAddress);
267
+ const instruction = adaptInitDemocracyAllocationInstruction(ctx.programs, {
268
+ authorization,
269
+ game: position.game,
270
+ identity: position.identity.address,
271
+ root: position.root.address,
272
+ history: position.history.address,
273
+ generation: generationAddress,
274
+ allocation: allocationAddress,
275
+ allocationHistory: recordAddress,
276
+ moduleStatus: position.moduleStatus,
277
+ expectedAuthorizationRevision: position.identityData.authorizationRevision,
278
+ expectedRootRevision: position.rootData.revision,
279
+ });
280
+ const accounts = new Map([
281
+ [authorization.profile, profileCandidate],
282
+ [RENT_ADDRESS, rent],
283
+ ]);
284
+ const funding = planStorageFunding(ctx.programs, {
285
+ action: readDemocracyStorageAction(ctx.programs, instruction, accounts),
286
+ accounts,
287
+ label: 'Democracy allocation',
288
+ });
289
+ const description = `Open Democracy allocation ${allocationAddress} for Profile ${authorization.profile} in Star System ${system}'s generation ${position.historyData.generationNumber}, with no voting power yet. ${funding.disclosure} Key permissions remain chain-authoritative.`;
290
+ return buildPlannerPlan(ctx.programs, {
291
+ kind: 'starbases.open-democracy-allocation',
292
+ preconditions: [
293
+ accountAbsentPrecondition(allocationAddress, `Profile ${authorization.profile} still has no allocation in this generation.`),
294
+ await accountStatePrecondition(position.root, `Democracy root ${position.root.address} stays at revision ${position.rootData.revision}.`),
295
+ funding.guard,
296
+ ],
297
+ steps: [
298
+ {
299
+ describes: description,
300
+ instruction,
301
+ signers: [authorization.authority],
302
+ },
303
+ ],
304
+ summary: description,
305
+ });
306
+ }
307
+ /** Plans depositing idle crew and CSS Housing from the Profile's Starbase
308
+ * Player as backing for a Democracy allocation.
309
+ *
310
+ * Backing stays locked until it is released, which the game allows only once
311
+ * the allocation holds no voting power. Deposits are refused while a voting
312
+ * power request waits to settle. Only housing of the System's controlling
313
+ * faction can back voting power. The Profile pays the backing record's rent.
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * declare const ctx: SageContext;
318
+ * declare const allocation: DemocracyAllocationSnapshot;
319
+ * declare const starbasePlayer: StarbasePlayerSnapshot;
320
+ * declare const authorization: PlanAuthorization;
321
+ * const plan = await planDepositDemocracyBacking(ctx, allocation, {
322
+ * authorization,
323
+ * starbasePlayer,
324
+ * crew: 10,
325
+ * housing: [{ cargoId: 50001, quantity: 1n }],
326
+ * });
327
+ * ```
328
+ */
329
+ export async function planDepositDemocracyBacking(ctx, allocationSnapshot, input) {
330
+ const options = readOptions(input, [
331
+ 'authorization',
332
+ 'starbasePlayer',
333
+ 'crew',
334
+ 'housing',
335
+ ]);
336
+ const authorization = readPlanAuthorization(options.authorization);
337
+ const { crew, housing } = options;
338
+ if (!Number.isSafeInteger(crew) ||
339
+ crew < 0 ||
340
+ crew > U32_MAX)
341
+ invalid('crew', crew, 'an integer from 0 to 4,294,967,295', 'Provide the number of idle crew to assign before retrying.');
342
+ if (!Array.isArray(housing))
343
+ invalid('housing', housing, 'an array of { cargoId, quantity }', 'Provide the CSS Housing to deposit, or an empty array, before retrying.');
344
+ const rows = housing.map((row, index) => {
345
+ const entry = row;
346
+ if (entry === null ||
347
+ typeof entry !== 'object' ||
348
+ !Number.isSafeInteger(entry.cargoId) ||
349
+ typeof entry.quantity !== 'bigint' ||
350
+ entry.quantity <= 0n ||
351
+ entry.quantity > U64_MAX)
352
+ invalid(`housing[${String(index)}]`, row, 'a cargo id and a positive u64 bigint quantity', 'List each CSS Housing item once with the units to deposit, then retry.');
353
+ return { cargoId: entry.cargoId, quantity: entry.quantity };
354
+ });
355
+ if (new Set(rows.map((row) => row.cargoId)).size !== rows.length)
356
+ invalid('housing', housing, 'each cargo id at most once', 'Combine the quantities of each CSS Housing item, then retry.');
357
+ if (crew === 0 && rows.length === 0)
358
+ invalid('crew', crew, 'some crew or housing to deposit', 'Deposit at least one crew member or one CSS Housing unit, then retry.');
359
+ const allocation = await readAllocation(ctx, allocationSnapshot, authorization.profile, 'deposit backing');
360
+ requireCurrentGeneration(allocation, 'take new backing');
361
+ requireLive(allocation, allocation.generationData, 'deposit backing');
362
+ const data = allocation.allocationData;
363
+ if (data.status === 'pending')
364
+ fail(`Democracy allocation ${allocation.accounts.allocation} has a voting power request waiting to settle, so the game refuses new backing until it settles. Settle it and retry.`, allocation.accounts.allocation);
365
+ const player = await readStarbasePlayer(ctx, allocation, options.starbasePlayer, data.starbaseSequenceId);
366
+ const [systemCandidate] = await readContextRawAccounts(ctx, [
367
+ allocation.system,
368
+ ]);
369
+ const systemRaw = present(systemCandidate, allocation.system, `Star System ${allocation.system} is missing. Refresh it and retry.`);
370
+ const systemData = starSystemAccountDefinition.decode(systemRaw, ctx.programs);
371
+ if (systemData.starbase === undefined ||
372
+ systemData.sequenceId !== data.starbaseSequenceId)
373
+ fail(`Star System ${allocation.system}'s Starbase changed since this allocation was opened, so it takes no new backing.`, allocation.system);
374
+ if (crew > idleCrew(player.data))
375
+ fail(`Starbase Player ${player.raw.address} has ${idleCrew(player.data)} idle crew, fewer than the ${String(crew)} to deposit. Deposit fewer crew or wait for busy crew to return, then retry.`, player.raw.address);
376
+ const quantities = Array(HOUSING_SLOTS).fill(0n);
377
+ let housingMap;
378
+ if (rows.length > 0) {
379
+ housingMap = (await readRequirements(ctx, allocation)).housingMap;
380
+ const controller = allocation.historyData.controllerFactionId;
381
+ for (const row of rows) {
382
+ const entry = housingMap.entries.find((e) => e.cargoId === row.cargoId);
383
+ if (entry === undefined)
384
+ invalid('housing', row.cargoId, `a CSS Housing cargo id: ${housingMap.entries.map((e) => e.cargoId).join(', ')}`, 'Deposit only CSS Housing items, then retry.');
385
+ if (factionValue(entry.faction) !== controller)
386
+ fail(`Cargo ${String(row.cargoId)} is ${FACTIONS[factionValue(entry.faction)]} housing, but ${FACTIONS[controller]} controls Star System ${allocation.system}; only the controlling faction's housing can back voting power there.`, player.raw.address);
387
+ const held = player.data.cargo.amounts.find((a) => a.cargoId === row.cargoId)
388
+ ?.amount ?? 0n;
389
+ if (held < row.quantity)
390
+ fail(`Starbase Player ${player.raw.address} holds ${held} of cargo ${String(row.cargoId)}, fewer than the ${row.quantity} to deposit. Bring more to the Starbase or deposit less, then retry.`, player.raw.address);
391
+ quantities[entry.slot] = row.quantity;
392
+ }
393
+ }
394
+ const [routeAddress, backingAddress] = await Promise.all([
395
+ deriveProfileRouteAddress(ctx.programs, allocation.game, authorization.profile),
396
+ deriveBackingAddress(ctx.programs, allocation.accounts.allocation, data.backingRevision + 1n),
397
+ ]);
398
+ const [existing, profileCandidate, rent] = await readContextRawAccounts(ctx, [
399
+ backingAddress,
400
+ authorization.profile,
401
+ RENT_ADDRESS,
402
+ ]);
403
+ if (existing !== undefined)
404
+ fail(`A backing already exists at deposit revision ${data.backingRevision + 1n}; another deposit landed first. Refresh the allocation and retry.`, backingAddress);
405
+ const instruction = adaptDepositDemocracyBackingInstruction(ctx.programs, {
406
+ authorization,
407
+ source: authorization,
408
+ position: allocation.accounts,
409
+ revisions: revisions(allocation),
410
+ expectedBackingRevision: data.backingRevision,
411
+ history: allocation.history.address,
412
+ route: routeAddress,
413
+ system: allocation.system,
414
+ starbasePlayer: player.raw.address,
415
+ backing: backingAddress,
416
+ moduleStatus: allocation.moduleStatus,
417
+ crew: crew,
418
+ housingQuantities: quantities,
419
+ });
420
+ const accounts = new Map([
421
+ [authorization.profile, profileCandidate],
422
+ [RENT_ADDRESS, rent],
423
+ ]);
424
+ const funding = planStorageFunding(ctx.programs, {
425
+ action: readDemocracyStorageAction(ctx.programs, instruction, accounts),
426
+ accounts,
427
+ label: 'Democracy backing',
428
+ });
429
+ const housingText = rows.length === 0
430
+ ? 'no housing'
431
+ : rows
432
+ .map((row) => `${row.quantity} of cargo ${String(row.cargoId)}`)
433
+ .join(', ');
434
+ const description = `Deposit ${String(crew)} crew and ${housingText} from Starbase Player ${player.raw.address} as backing ${backingAddress} for Democracy allocation ${allocation.accounts.allocation}. The game takes the housing and keeps the crew busy until the backing is released, which it allows only once the allocation holds no voting power. ${funding.disclosure} Key permissions remain chain-authoritative.`;
435
+ return buildPlannerPlan(ctx.programs, {
436
+ kind: 'starbases.deposit-democracy-backing',
437
+ preconditions: [
438
+ ...(await positionPreconditions(allocation)),
439
+ await accountStatePrecondition(player.raw, `Starbase Player ${player.raw.address} keeps its crew, cargo and Starbase.`),
440
+ accountAbsentPrecondition(backingAddress, `No backing exists yet at deposit revision ${data.backingRevision + 1n}.`),
441
+ funding.guard,
442
+ ],
443
+ steps: [
444
+ {
445
+ describes: description,
446
+ instruction,
447
+ signers: [authorization.authority],
448
+ },
449
+ ],
450
+ summary: description,
451
+ });
452
+ }
453
+ async function readRequirements(ctx, position, versions) {
454
+ const registry = await deriveRequirementsAddress(ctx.programs, position.game);
455
+ const [candidate] = await readContextRawAccounts(ctx, [registry]);
456
+ const registryRaw = present(candidate, registry, 'The Game has published no Democracy backing requirements, so no voting power can be backed. Retry once the game publishes them.');
457
+ const data = democracyRequirementsAccountDefinition.decode(registryRaw, ctx.programs);
458
+ if (data.game !== position.game)
459
+ fail(`Democracy requirements ${registry} belong to another Game. Verify the configured Game and retry.`, registry);
460
+ const advanced = data.pendingCurveVersion !== undefined &&
461
+ data.pendingHousingMapVersion !== undefined &&
462
+ data.pendingEffectiveEpoch <= position.now / REQUIREMENTS_EPOCH_SECONDS;
463
+ const curveVersion = versions?.curve ??
464
+ (advanced ? data.pendingCurveVersion : data.activeCurveVersion);
465
+ const mapVersion = versions?.housingMap ??
466
+ (advanced ? data.pendingHousingMapVersion : data.activeHousingMapVersion);
467
+ if (curveVersion === undefined || mapVersion === undefined)
468
+ fail('The Game has no active Democracy backing requirements, so no voting power can be backed. Retry once the game publishes them.', registry);
469
+ const [curveAddress, housingMapAddress] = await Promise.all([
470
+ deriveCurveAddress(ctx.programs, position.game, curveVersion),
471
+ deriveHousingMapAddress(ctx.programs, position.game, mapVersion),
472
+ ]);
473
+ const [curveCandidate, mapCandidate] = await readContextRawAccounts(ctx, [
474
+ curveAddress,
475
+ housingMapAddress,
476
+ ]);
477
+ const curve = democracyCurveAccountDefinition.decode(present(curveCandidate, curveAddress, `Democracy crew curve version ${String(curveVersion)} is missing. Refresh the requirements and retry.`), ctx.programs);
478
+ const housingMap = democracyHousingMapAccountDefinition.decode(present(mapCandidate, housingMapAddress, `Democracy housing map version ${String(mapVersion)} is missing. Refresh the requirements and retry.`), ctx.programs);
479
+ if (curve.game !== position.game || housingMap.game !== position.game)
480
+ fail('Democracy backing requirements belong to another Game. Verify the configured Game and retry.', curveAddress);
481
+ if (curve.curveVersion !== curveVersion)
482
+ fail(`Democracy crew curve ${curveAddress} stores version ${String(curve.curveVersion)}, not the version ${String(curveVersion)} it was read for. Refresh the requirements and retry.`, curveAddress);
483
+ if (housingMap.mapVersion !== mapVersion)
484
+ fail(`Democracy housing map ${housingMapAddress} stores version ${String(housingMap.mapVersion)}, not the version ${String(mapVersion)} it was read for. Refresh the requirements and retry.`, housingMapAddress);
485
+ return {
486
+ registry,
487
+ registryRaw,
488
+ curve,
489
+ curveAddress,
490
+ housingMap,
491
+ housingMapAddress,
492
+ };
493
+ }
494
+ /** Refuses unless the allocation's backing covers `votingPower` under these
495
+ * requirements. Above the curve's linear range the game applies a premium
496
+ * Atlas Kit does not compute, so only the game decides there. */
497
+ function requireBacking(allocation, requirements, votingPower, label) {
498
+ const { curve, housingMap } = requirements;
499
+ if (votingPower > curve.maximumVotingPower)
500
+ fail(`Democracy backing covers at most ${curve.maximumVotingPower} voting power, less than the ${votingPower} ${label}.`, requirements.curveAddress);
501
+ if (votingPower > curve.votingPowerThreshold)
502
+ return;
503
+ const crew = (votingPower + curve.votingPowerPerCrew - 1n) / curve.votingPowerPerCrew;
504
+ const controller = allocation.historyData.controllerFactionId;
505
+ const capacity = housingMap.entries
506
+ .filter((entry) => factionValue(entry.faction) === controller)
507
+ .reduce((sum, entry) => sum +
508
+ allocation.allocationData.housingQuantities[entry.slot] *
509
+ entry.capacityPerUnit, 0n);
510
+ if (allocation.allocationData.crew < crew || capacity < crew)
511
+ fail(`${votingPower} voting power ${label} needs ${crew} crew, housed by CSS Housing of the controlling faction; allocation ${allocation.accounts.allocation} is backed by ${allocation.allocationData.crew} crew and housing for ${capacity}. Deposit more backing or request less, then retry.`, allocation.accounts.allocation);
512
+ }
513
+ function voteValue(value) {
514
+ if (value === undefined)
515
+ return undefined;
516
+ if (value === null || typeof value !== 'object')
517
+ return null;
518
+ const vote = value;
519
+ const keys = [
520
+ 'craftingPremiumBps',
521
+ 'localMarketPremiumBps',
522
+ 'localTreasuryShareBps',
523
+ 'dailyPayoutRateBps',
524
+ ];
525
+ if (!keys.every((key) => Number.isSafeInteger(vote[key]) &&
526
+ vote[key] >= 0 &&
527
+ vote[key] <= 65_535))
528
+ return null;
529
+ return {
530
+ craftingPremiumBps: vote.craftingPremiumBps,
531
+ localMarketPremiumBps: vote.localMarketPremiumBps,
532
+ localTreasuryShareBps: vote.localTreasuryShareBps,
533
+ dailyPayoutRateBps: vote.dailyPayoutRateBps,
534
+ };
535
+ }
536
+ function sameVote(left, right) {
537
+ return (left === right ||
538
+ (left !== undefined &&
539
+ right !== undefined &&
540
+ left.craftingPremiumBps === right.craftingPremiumBps &&
541
+ left.localMarketPremiumBps === right.localMarketPremiumBps &&
542
+ left.localTreasuryShareBps === right.localTreasuryShareBps &&
543
+ left.dailyPayoutRateBps === right.dailyPayoutRateBps));
544
+ }
545
+ /** Refuses a vote outside the System's vote rules. A new or changed vote must
546
+ * use each parameter's step; the standing vote may keep an older value. */
547
+ function requireVote(policy, vote, unchanged) {
548
+ const ranges = policy.voteRanges;
549
+ for (const key of [
550
+ 'craftingPremiumBps',
551
+ 'localMarketPremiumBps',
552
+ 'localTreasuryShareBps',
553
+ 'dailyPayoutRateBps',
554
+ ]) {
555
+ const range = ranges[key];
556
+ const value = vote[key];
557
+ const maximum = key === 'localTreasuryShareBps'
558
+ ? Math.min(range.maximumBps, BPS - policy.minimumDaoShareBps)
559
+ : range.maximumBps;
560
+ const origin = key === 'craftingPremiumBps' ? range.minimumBps : 0;
561
+ if (value < range.minimumBps ||
562
+ value > maximum ||
563
+ (!unchanged &&
564
+ range.stepBps > 0 &&
565
+ (value - origin) % range.stepBps !== 0))
566
+ invalid(`vote.${key}`, value, `${range.minimumBps} to ${maximum} bps in steps of ${range.stepBps}`, 'Vote with a value from the System vote rules (`governance.voteRules`), then retry.');
567
+ }
568
+ }
569
+ /** Plans requesting a Democracy allocation's voting power and standing vote.
570
+ *
571
+ * Positive voting power needs the Profile's Starbase Player in the System, in
572
+ * its controlling faction, and enough deposited backing: under the curve's
573
+ * linear range, one crew per `votingPowerPerCrew`, housed by CSS Housing of
574
+ * that faction. A change usually takes effect the next UTC day and then needs
575
+ * a settlement. Zero voting power withdraws it and may only keep or clear the
576
+ * standing vote. Reward amounts and the exact settlement day remain
577
+ * chain-authoritative.
578
+ *
579
+ * @example
580
+ * ```ts
581
+ * declare const ctx: SageContext;
582
+ * declare const allocation: DemocracyAllocationSnapshot;
583
+ * declare const starbasePlayer: StarbasePlayerSnapshot;
584
+ * declare const authorization: PlanAuthorization;
585
+ * const plan = await planRequestDemocracyVotingPower(ctx, allocation, {
586
+ * authorization,
587
+ * starbasePlayer,
588
+ * votingPower: 40_000n,
589
+ * vote: undefined,
590
+ * });
591
+ * ```
592
+ */
593
+ export async function planRequestDemocracyVotingPower(ctx, allocationSnapshot, input) {
594
+ const options = readOptions(input, ['authorization', 'votingPower', 'vote'], ['starbasePlayer']);
595
+ const authorization = readPlanAuthorization(options.authorization);
596
+ const votingPower = options.votingPower;
597
+ if (typeof votingPower !== 'bigint' ||
598
+ votingPower < 0n ||
599
+ votingPower > U64_MAX)
600
+ invalid('votingPower', votingPower, 'a u64 bigint', 'Provide the voting power to hold, or 0n to withdraw it, then retry.');
601
+ const vote = voteValue(options.vote);
602
+ if (vote === null)
603
+ invalid('vote', options.vote, 'four basis-point parameters, or undefined to abstain', 'Provide craftingPremiumBps, localMarketPremiumBps, localTreasuryShareBps and dailyPayoutRateBps, or undefined, then retry.');
604
+ const target = votingPower;
605
+ const allocation = await readAllocation(ctx, allocationSnapshot, authorization.profile, 'request voting power');
606
+ requireCurrentGeneration(allocation, 'request voting power');
607
+ const { historyData, today } = allocation;
608
+ if (historyData.openDay !== today)
609
+ fail(`Star System ${allocation.system}'s Democracy history is still open on UTC day ${historyData.openDay}, before today (${today}), so the game refuses Democracy actions there until the earlier days are closed. Anyone can close them; retry once the history reaches today.`, allocation.history.address);
610
+ const data = allocation.allocationData;
611
+ const record = allocation.recordData;
612
+ if (record.requestedFromDay !== 0n && record.requestedFromDay <= today)
613
+ fail(`The voting power requested for allocation ${allocation.accounts.allocation} took effect on UTC day ${record.requestedFromDay}; settle it before requesting again.`, allocation.accounts.allocation);
614
+ const budget = allocation.rootData.votingPowerBudget -
615
+ allocation.rootData.reservedVotingPower +
616
+ data.reservedVotingPower;
617
+ if (target > budget)
618
+ fail(`Democracy identity ${allocation.identity.address} has ${budget} voting power available for this allocation, less than the ${target} requested. Withdraw voting power elsewhere or request less, then retry.`, allocation.root.address);
619
+ const [policyCandidate] = await readContextRawAccounts(ctx, [
620
+ historyData.policy,
621
+ ]);
622
+ const policy = democracyHistoryPolicyAccountDefinition.decode(present(policyCandidate, historyData.policy, `Democracy vote rules ${historyData.policy} are missing. Refresh the governance accounts and retry.`), ctx.programs);
623
+ const standing = record.vote;
624
+ const unchanged = sameVote(standing, vote ?? undefined);
625
+ let requirements;
626
+ const extra = [];
627
+ if (target > 0n) {
628
+ if (vote)
629
+ requireVote(policy, vote, unchanged);
630
+ requireLive(allocation, allocation.generationData, 'hold voting power');
631
+ if (options.starbasePlayer === undefined)
632
+ invalid('starbasePlayer', undefined, "the Profile's Starbase Player in the allocation's System", 'Positive voting power needs a Starbase Player there; pass it and retry.');
633
+ const player = await readStarbasePlayer(ctx, allocation, options.starbasePlayer, data.starbaseSequenceId);
634
+ const current = await readRequirements(ctx, allocation);
635
+ requireBacking(allocation, current, target, 'requested');
636
+ let active;
637
+ if (data.activeVotingPower > 0n) {
638
+ active = await readRequirements(ctx, allocation, {
639
+ curve: data.activeCurveVersion,
640
+ housingMap: data.activeHousingMapVersion,
641
+ });
642
+ requireBacking(allocation, active, data.activeVotingPower, 'held now under the requirements it was backed with');
643
+ }
644
+ requirements = {
645
+ starbasePlayer: player.raw.address,
646
+ registry: current.registry,
647
+ curve: current.curveAddress,
648
+ housingMap: current.housingMapAddress,
649
+ ...(active === undefined
650
+ ? {}
651
+ : {
652
+ activeCurve: active.curveAddress,
653
+ activeHousingMap: active.housingMapAddress,
654
+ }),
655
+ };
656
+ extra.push(await accountStatePrecondition(player.raw, `Starbase Player ${player.raw.address} stays in the controlling faction at the current Starbase.`));
657
+ }
658
+ else if (!unchanged && vote !== undefined) {
659
+ invalid('vote', options.vote, 'undefined or the standing vote when withdrawing voting power', 'Withdrawing voting power can keep or clear the standing vote but not cast a new one; pass undefined or the current vote and retry.');
660
+ }
661
+ const instruction = adaptRequestDemocracyAllocationInstruction(ctx.programs, {
662
+ authorization,
663
+ position: allocation.accounts,
664
+ revisions: revisions(allocation),
665
+ expectedBackingRevision: data.backingRevision,
666
+ history: allocation.history.address,
667
+ policy: historyData.policy,
668
+ moduleStatus: allocation.moduleStatus,
669
+ targetVotingPower: target,
670
+ vote: vote === undefined
671
+ ? undefined
672
+ : {
673
+ craftingFeeBps: vote.craftingPremiumBps,
674
+ localMarketFeeBps: vote.localMarketPremiumBps,
675
+ localTreasuryShareBps: vote.localTreasuryShareBps,
676
+ treasuryDistributionBps: vote.dailyPayoutRateBps,
677
+ },
678
+ ...(requirements === undefined ? {} : { requirements }),
679
+ });
680
+ const voteText = vote === undefined
681
+ ? 'abstaining'
682
+ : `voting crafting premium ${vote.craftingPremiumBps}, Local Market premium ${vote.localMarketPremiumBps}, local treasury share ${vote.localTreasuryShareBps} and daily payout rate ${vote.dailyPayoutRateBps} bps`;
683
+ const description = `Request ${target} voting power for Democracy allocation ${allocation.accounts.allocation} (now ${data.activeVotingPower}), ${voteText}. The change usually takes effect on the next UTC day and then needs a settlement; withdrawn voting power keeps its backing locked until then. Reward amounts remain chain-authoritative.`;
684
+ return buildPlannerPlan(ctx.programs, {
685
+ kind: 'starbases.request-democracy-voting-power',
686
+ preconditions: [...(await positionPreconditions(allocation)), ...extra],
687
+ steps: [
688
+ {
689
+ describes: description,
690
+ instruction,
691
+ signers: [authorization.authority],
692
+ },
693
+ ],
694
+ summary: description,
695
+ });
696
+ }
697
+ /** Plans settling a Democracy allocation's requested voting power once it
698
+ * has taken effect: the allocation then holds it as voting power. Winding
699
+ * down an allocation whose generation retired is not planned yet.
700
+ *
701
+ * Anyone may settle; the funder wallet signs and pays the settlement
702
+ * receipt's rent. Reward accounting remains chain-authoritative.
703
+ *
704
+ * @example
705
+ * ```ts
706
+ * declare const ctx: SageContext;
707
+ * declare const allocation: DemocracyAllocationSnapshot;
708
+ * declare const funder: Address;
709
+ * const plan = await planSettleDemocracyAllocation(ctx, allocation, { funder });
710
+ * ```
711
+ */
712
+ export async function planSettleDemocracyAllocation(ctx, allocationSnapshot, input) {
713
+ const options = readOptions(input, ['funder']);
714
+ if (typeof options.funder !== 'string' || !isAddress(options.funder))
715
+ invalid('funder', options.funder, 'one valid z.ink/Solana wallet address', 'Provide the wallet that signs and pays the settlement receipt, then retry.');
716
+ const funder = options.funder;
717
+ // The allocation's own identity reads it; settlement needs no
718
+ // authorization from that Profile.
719
+ const [identityCandidate] = await readContextRawAccounts(ctx, [
720
+ allocationSnapshot.identity,
721
+ ]);
722
+ const identity = democracyIdentityAccountDefinition.decode(present(identityCandidate, allocationSnapshot.identity, `Democracy identity ${allocationSnapshot.identity} is missing. Refresh the allocation and retry.`), ctx.programs);
723
+ const allocation = await readAllocation(ctx, allocationSnapshot, identity.authorizingProfile, 'settle');
724
+ const data = allocation.allocationData;
725
+ const record = allocation.recordData;
726
+ const generation = allocation.generationData;
727
+ if (generation.retired)
728
+ fail(`Democracy allocation ${allocation.accounts.allocation} belongs to a generation that retired when Star System ${allocation.system} changed hands. Atlas Kit does not plan its wind-down yet; settle it in the game client.`, allocation.accounts.generation);
729
+ requireCurrentGeneration(allocation, 'settle');
730
+ if (allocation.historyData.openDay !== allocation.today)
731
+ fail(`Star System ${allocation.system}'s Democracy history is still open on UTC day ${allocation.historyData.openDay}, before today (${allocation.today}). Anyone can close the earlier days; retry once the history reaches today.`, allocation.history.address);
732
+ if (data.status !== 'pending')
733
+ fail(`Democracy allocation ${allocation.accounts.allocation} has no voting power request to settle.`, allocation.accounts.allocation);
734
+ if (data.effectiveDay > generation.openDay)
735
+ fail(`The voting power requested for allocation ${allocation.accounts.allocation} takes effect on UTC day ${data.effectiveDay}; settle it from that day.`, allocation.accounts.allocation);
736
+ const pendingDay = record.requestedFromDay;
737
+ const needsBoundary = pendingDay !== 0n;
738
+ let boundary;
739
+ const extra = [];
740
+ if (needsBoundary) {
741
+ boundary = await deriveHistoryDayAddress(ctx.programs, allocation.system, pendingDay - 1n);
742
+ const [candidate] = await readContextRawAccounts(ctx, [boundary]);
743
+ const day = democracyHistoryDayAccountDefinition.decode(present(candidate, boundary, `Star System ${allocation.system}'s Democracy history day ${pendingDay - 1n} is not closed yet, and settlement reads it. Anyone can close it; retry once it is.`), ctx.programs);
744
+ if (day.system !== allocation.system || day.day !== pendingDay - 1n)
745
+ fail(`Democracy history day ${boundary} contradicts Star System ${allocation.system}. Refresh the governance accounts and retry.`, boundary);
746
+ }
747
+ const settlement = await deriveSettlementAddress(ctx.programs, allocation.accounts.allocation, data.revision);
748
+ const [existing] = await readContextRawAccounts(ctx, [settlement]);
749
+ if (existing !== undefined)
750
+ fail(`Democracy allocation ${allocation.accounts.allocation} is already settled at revision ${data.revision}. Refresh it and retry.`, settlement);
751
+ extra.push(accountAbsentPrecondition(settlement, `Allocation revision ${data.revision} is still unsettled.`));
752
+ const instruction = adaptSettleDemocracyAllocationInstruction(ctx.programs, {
753
+ funder,
754
+ position: allocation.accounts,
755
+ history: allocation.history.address,
756
+ boundary,
757
+ settlement,
758
+ expectedRootRevision: allocation.rootData.revision,
759
+ expectedAllocationRevision: data.revision,
760
+ });
761
+ const description = `Settle Democracy allocation ${allocation.accounts.allocation}: it then holds the ${data.requestedVotingPower} voting power requested from UTC day ${data.effectiveDay}. Wallet ${funder} signs and pays the settlement receipt's rent; reward accounting remains chain-authoritative.`;
762
+ return buildPlannerPlan(ctx.programs, {
763
+ kind: 'starbases.settle-democracy-allocation',
764
+ preconditions: [...(await positionPreconditions(allocation)), ...extra],
765
+ steps: [{ describes: description, instruction, signers: [funder] }],
766
+ summary: description,
767
+ });
768
+ }
769
+ /** Plans releasing one Democracy backing deposit: the game frees its crew
770
+ * and returns its housing to the Starbase Player, or, once the Starbase it was
771
+ * deposited at is gone, the housing that respawns to its respawning cargo.
772
+ *
773
+ * The game releases backing only while the allocation holds no voting power
774
+ * and has nothing waiting to settle: request zero voting power and settle
775
+ * first. The Profile pays for any cargo line the housing reopens.
776
+ *
777
+ * @example
778
+ * ```ts
779
+ * declare const ctx: SageContext;
780
+ * declare const allocation: DemocracyAllocationSnapshot;
781
+ * declare const authorization: PlanAuthorization;
782
+ * const plan = await planReleaseDemocracyBacking(ctx, allocation, {
783
+ * authorization,
784
+ * backing: allocation.backings[0]!.address,
785
+ * });
786
+ * ```
787
+ */
788
+ export async function planReleaseDemocracyBacking(ctx, allocationSnapshot, input) {
789
+ const options = readOptions(input, ['authorization', 'backing']);
790
+ const authorization = readPlanAuthorization(options.authorization);
791
+ if (typeof options.backing !== 'string' || !isAddress(options.backing))
792
+ invalid('backing', options.backing, 'one backing address from allocation.backings', 'Choose a live backing of the allocation, then retry.');
793
+ const backingAddress = options.backing;
794
+ const allocation = await readAllocation(ctx, allocationSnapshot, authorization.profile, 'release backing');
795
+ const data = allocation.allocationData;
796
+ if (!(data.status === 'staging' || data.status === 'settled') ||
797
+ data.activeVotingPower !== 0n ||
798
+ data.requestedVotingPower !== 0n ||
799
+ data.reservedVotingPower !== 0n)
800
+ fail(`Democracy allocation ${allocation.accounts.allocation} still holds or waits for voting power, so the game keeps its backing locked. Request zero voting power, settle it, and retry.`, allocation.accounts.allocation);
801
+ const [backingCandidate] = await readContextRawAccounts(ctx, [
802
+ backingAddress,
803
+ ]);
804
+ const backingRaw = present(backingCandidate, backingAddress, `Democracy backing ${backingAddress} is missing. Refresh the allocation and retry.`);
805
+ const backing = democracyBackingAccountDefinition.decode(backingRaw, ctx.programs);
806
+ const expected = await deriveBackingAddress(ctx.programs, allocation.accounts.allocation, backing.depositRevision);
807
+ if (backing.allocation !== allocation.accounts.allocation ||
808
+ expected !== backingAddress)
809
+ fail(`Democracy backing ${backingAddress} does not belong to allocation ${allocation.accounts.allocation}. Choose one of its backings and retry.`, backingAddress);
810
+ if (backing.released)
811
+ fail(`Democracy backing ${backingAddress} was already released.`, backingAddress);
812
+ const [playerCandidate, profileCandidate, rent] = await readContextRawAccounts(ctx, [
813
+ backing.starbasePlayer,
814
+ authorization.profile,
815
+ RENT_ADDRESS,
816
+ ]);
817
+ const playerRaw = present(playerCandidate, backing.starbasePlayer, `Starbase Player ${backing.starbasePlayer}, which the backing returns to, is missing. Register it again at Star System ${backing.system} and retry.`);
818
+ const player = starbasePlayerAccountDefinition.decode(playerRaw, ctx.programs);
819
+ if (player.playerProfile !== backing.profile ||
820
+ player.system !== backing.system ||
821
+ player.sequenceId < backing.starbaseSequenceId)
822
+ fail(`Starbase Player ${backing.starbasePlayer} no longer matches the Profile and Starbase backing ${backingAddress} came from. Refresh it and retry.`, backing.starbasePlayer);
823
+ const instruction = adaptReleaseDemocracyBackingInstruction(ctx.programs, {
824
+ authorization,
825
+ position: allocation.accounts,
826
+ revisions: revisions(allocation),
827
+ expectedBackingRevision: data.backingRevision,
828
+ backing: backingAddress,
829
+ starbasePlayer: backing.starbasePlayer,
830
+ });
831
+ const accounts = new Map([
832
+ [backingAddress, backingRaw],
833
+ [playerRaw.address, playerRaw],
834
+ [authorization.profile, profileCandidate],
835
+ [RENT_ADDRESS, rent],
836
+ ]);
837
+ const funding = planStorageFunding(ctx.programs, {
838
+ action: readDemocracyStorageAction(ctx.programs, instruction, accounts),
839
+ accounts,
840
+ label: 'Democracy backing release',
841
+ });
842
+ const current = player.sequenceId === backing.starbaseSequenceId;
843
+ const description = `Release Democracy backing ${backingAddress}: free its ${backing.crew} crew and return its housing to Starbase Player ${backing.starbasePlayer}'s ${current ? 'cargo' : 'respawning cargo, since the Starbase it was deposited at is gone; housing that does not respawn is lost'}. ${funding.disclosure} Key permissions remain chain-authoritative.`;
844
+ return buildPlannerPlan(ctx.programs, {
845
+ kind: 'starbases.release-democracy-backing',
846
+ preconditions: [
847
+ ...(await positionPreconditions(allocation)),
848
+ await accountStatePrecondition(backingRaw, `Democracy backing ${backingAddress} stays unreleased.`),
849
+ funding.guard,
850
+ ],
851
+ steps: [
852
+ {
853
+ describes: description,
854
+ instruction,
855
+ signers: [authorization.authority],
856
+ },
857
+ ],
858
+ summary: description,
859
+ });
860
+ }
861
+ //# sourceMappingURL=democracy.js.map