@claritydao/midnight-agora-contracts 0.1.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.
@@ -0,0 +1,875 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma language_version 0.18.0;
3
+
4
+ import CompactStandardLibrary;
5
+
6
+ import '../DAO/StakeModule';
7
+ import '../DAO/ProposalModule';
8
+ import '../DAO/EffectModule';
9
+ import '../DAO/TreasuryModule';
10
+ import '../utils/Initializable';
11
+ import '../utils/Pausable';
12
+ import '../utils/DivModule';
13
+ import '../utils/Utils';
14
+ import '../fungigleToken/FungibleToken';
15
+ import '../utils/TypesModule';
16
+
17
+ // Exports from TypesModule
18
+ export { TimeComparison };
19
+ export { ProposalStatus };
20
+ export { EffectStatus };
21
+ export { EffectActionType };
22
+ export { DelegationStatus };
23
+ export { VoteChoice };
24
+ export { TreasuryTransactionType };
25
+ export { TreasuryOperationType };
26
+ export { GovernorPermission };
27
+ export { StakeRecord };
28
+ export { DelegationKey };
29
+ export { DelegationRecord };
30
+ export { StakeInfo };
31
+ export { VoteRecord };
32
+ export { EffectAction };
33
+ export { Effect };
34
+ export { Proposal };
35
+ export { GovernanceConfig };
36
+ export { ProofOfStake };
37
+ export { ProofOfGovernorApproval };
38
+ export { ProofOfEffectExecution };
39
+ export { TreasuryBalance };
40
+ export { TreasuryTransaction };
41
+ export { TreasuryOperation };
42
+ export { TreasuryStatistics };
43
+ export { GovernorConfig };
44
+ export { QueuedProposal };
45
+ export { GovernorStatus };
46
+ export { storeTimestamp };
47
+ export { validateTime };
48
+ export { getCurrentTime };
49
+
50
+ // Exports from Utils
51
+ export { isKeyOrAddressZero };
52
+ export { isKeyZero };
53
+ export { isKeyOrAddressEqual };
54
+ export { isContractAddress };
55
+ export { emptyString };
56
+
57
+ // Exports from StakeModule
58
+ export { stakes };
59
+ export { delegations };
60
+ export { totalStakes };
61
+ export { governanceConfig };
62
+ // NOTE: registerStake, withdrawStake, delegateStake, undelegateStake not exported - use Governor variants
63
+ export { getStakeInfo };
64
+ export { getTotalDelegatedPower };
65
+ export { hasProposalThreshold };
66
+ export { hasVotingPower };
67
+ export { updateGovernanceConfig };
68
+ export { getGovernanceConfig };
69
+ export { getStakeRecord };
70
+ export { getDelegationRecord };
71
+ export { validateStakeWithdrawal };
72
+
73
+ // Exports from ProposalModule
74
+ export { proposals };
75
+ export { userVotes };
76
+ export { proposalCounter };
77
+ // NOTE: createProposal, castVote, finalizeProposal, queueProposal, markProposalExecuted, cancelProposal not exported - use Governor variants
78
+ export { getProposal };
79
+ export { getProposalVoteCount };
80
+ export { generateProposalId };
81
+ export { createVoteKey };
82
+ export { updateProposalVotes };
83
+ export { updateProposalEffect };
84
+
85
+ // Exports from EffectModule
86
+ export { effects };
87
+ export { effectCounter };
88
+ export { treasuryBalance };
89
+ export { daoConfig };
90
+ // NOTE: createEffect, executeEffect, cancelEffect, batchExecuteEffects not exported - use Governor variants
91
+ export { getEffect };
92
+ export { getEffectCountByProposal };
93
+ export { canExecuteEffect };
94
+ export { validateEffectActions };
95
+ export { createMintTokenEffect };
96
+ export { createTransferEffect };
97
+ export { createConfigUpdateEffect };
98
+ export { generateEffectId };
99
+ export { mint };
100
+ export { getDaoConfig };
101
+
102
+ // Exports from TreasuryModule
103
+ export { treasuryBalances };
104
+ export { authorizedSpenders };
105
+ export { spendingLimits };
106
+ export { totalTreasuryValue };
107
+ export { transactionCounter };
108
+ // NOTE: depositToTreasury, withdrawFromTreasury, transferTreasuryTokens, burnTreasuryTokens not exported - use Governor variants
109
+ export { setSpendingLimit };
110
+ export { authorizeSpender };
111
+ export { revokeSpenderAuthorization };
112
+ export { getTreasuryBalance };
113
+ export { getTotalTreasuryValue };
114
+ export { getTreasuryTransactionCount };
115
+ export { getSpendingLimit };
116
+ export { isAuthorizedSpender };
117
+ export { validateTreasurySpending };
118
+ export { getTreasuryStatistics };
119
+ export { batchTreasuryOperations };
120
+
121
+ // Exports from FungibleToken
122
+ export { _balances };
123
+ export { _allowances };
124
+ export { _totalSupply };
125
+ export { name };
126
+ export { symbol };
127
+ export { decimals };
128
+ export { totalSupply };
129
+ export { balanceOf };
130
+ export { transfer };
131
+ export { _unsafeTransfer };
132
+ export { allowance };
133
+ export { approve };
134
+ export { transferFrom };
135
+ export { _unsafeTransferFrom };
136
+ export { _transfer };
137
+ export { _unsafeUncheckedTransfer };
138
+ export { _mint };
139
+ export { _unsafeMint };
140
+ export { _burn };
141
+ export { _approve };
142
+ export { _spendAllowance };
143
+
144
+ // --- Governor centralized validation circuits ---
145
+ export { createProposalWithEffect };
146
+ export { castVoteWithValidation };
147
+ export { finalizeProposalWithValidation };
148
+ export { queueProposalWithValidation };
149
+ export { markProposalExecutedWithValidation };
150
+ export { cancelProposalWithValidation };
151
+ export { finalizeAndQueueProposal };
152
+ export { executeEffectWithValidation };
153
+ export { createEffectWithValidation };
154
+ export { cancelEffectWithValidation };
155
+ export { batchExecuteEffectsWithValidation };
156
+ export { executeQueuedProposal };
157
+ export { cancelProposalWithReason };
158
+ export { emergencyVetoProposal };
159
+ export { registerStakeWithValidation };
160
+ export { withdrawStakeWithValidation };
161
+ export { delegateStakeWithValidation };
162
+ export { undelegateStakeWithValidation };
163
+ export { depositToTreasuryWithValidation };
164
+ export { withdrawFromTreasuryWithValidation };
165
+ export { transferTreasuryTokensWithValidation };
166
+ export { burnTreasuryTokensWithValidation };
167
+
168
+ // Witness for local secret key (admin authentication)
169
+ witness local_secret_key(): Maybe<Bytes<32>>;
170
+
171
+ // Ledger state for governor configuration
172
+ export ledger governorConfig: GovernorConfig;
173
+
174
+ // Ledger state for active proposal counter
175
+ export ledger activeProposalCount: Counter;
176
+
177
+ // Ledger state for queued proposal counter
178
+ export ledger queuedProposalCount: Counter;
179
+
180
+ // Ledger state for governor permissions
181
+ export ledger governorPermissions: Map<Bytes<32>, GovernorPermission>;
182
+
183
+ constructor(
184
+ initialConfig: GovernorConfig,
185
+ tokenName: Opaque<"string">,
186
+ tokenSymbol: Opaque<"string">,
187
+ tokenDecimals: Uint<8>,
188
+ admin_key: Bytes<32>
189
+ ) {
190
+
191
+ initialize(disclose(tokenName), disclose(tokenSymbol), disclose(tokenDecimals));
192
+
193
+
194
+ governorConfig = disclose(initialConfig);
195
+ governorPermissions.insert(disclose(admin_key), GovernorPermission.Admin);
196
+
197
+
198
+ }
199
+
200
+ // Circuit to create a complete proposal with effect
201
+ export circuit createProposalWithEffect(
202
+ creator: Bytes<32>,
203
+ title: Opaque<'string'>,
204
+ description: Opaque<'string'>,
205
+ actions: Vector<10, EffectAction>,
206
+ proof: ProofOfStake,
207
+ votingStartTime: Uint<64>,
208
+ votingEndTime: Uint<64>
209
+ ): Uint<64> {
210
+
211
+ assert(proof.userId == disclose(creator), "Creator must match proof");
212
+
213
+ const config = governorConfig;
214
+
215
+ // CENTRALIZED VALIDATION: Check if creator has proposal threshold
216
+ // This is done in Governor to avoid ledger state isolation issues
217
+ const creatorVotingPower = getTotalDelegatedPower(disclose(creator));
218
+ assert(creatorVotingPower >= config.governance.proposalThreshold, "Insufficient stake for proposal");
219
+
220
+ // Check if max active proposals limit is reached
221
+ const currentActiveCount = activeProposalCount.read();
222
+ assert(currentActiveCount < config.maxActiveProposals, "Too many active proposals");
223
+
224
+ // Create proposal first with temporary effectId = 0
225
+ const proposalId = createProposal(disclose(creator), title, description, 0, proof, votingStartTime, votingEndTime);
226
+
227
+ // Create effect with the correct proposal ID
228
+ const effectId = createEffectWithValidation(proposalId, disclose(actions), proof);
229
+
230
+ // Update proposal with the correct effect ID
231
+ updateProposalEffect(proposalId, effectId);
232
+
233
+ // Increment active proposal counter
234
+ activeProposalCount.increment(1);
235
+
236
+ return proposalId;
237
+ }
238
+
239
+ // Circuit to cast a vote with centralized validation
240
+ export circuit castVoteWithValidation(
241
+ proposalId: Uint<64>,
242
+ voter: Bytes<32>,
243
+ choice: VoteChoice,
244
+ proof: ProofOfStake
245
+ ): [] {
246
+ assert(proof.userId == disclose(voter), "Voter must match proof");
247
+
248
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
249
+
250
+ // 1. Validate proposal exists and is active
251
+ const proposal = getProposal(disclose(proposalId));
252
+ const currentTime = getCurrentTime();
253
+ assert(proposal.status == ProposalStatus.Active, "Proposal not active");
254
+ assert(currentTime >= proposal.votingStartTime && currentTime <= proposal.votingEndTime, "Proposal not in voting period");
255
+
256
+ // 2. Validate voter has voting power (external access works correctly)
257
+ const voterVotingPower: Uint<64> = getTotalDelegatedPower(disclose(voter));
258
+ assert(voterVotingPower > 0, "No voting power");
259
+
260
+ // 3. Create proof with actual voting power for module consumption
261
+ const votingProof = ProofOfStake {
262
+ userId: proof.userId,
263
+ amount: voterVotingPower, // Pass the actual voting power
264
+ nonce: proof.nonce
265
+ };
266
+
267
+ // Call simplified module function with validated data
268
+ castVote(proposalId, voter, choice, votingProof, voterVotingPower);
269
+ }
270
+
271
+
272
+ // Circuit to finalize proposal with centralized validation
273
+ export circuit finalizeProposalWithValidation(
274
+ proposalId: Uint<64>,
275
+ proof: ProofOfGovernorApproval
276
+ ): [] {
277
+ assert(proof.proposalId == disclose(proposalId), "Proposal ID mismatch");
278
+
279
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
280
+
281
+ // 1. Validate proposal exists
282
+ const proposal = getProposal(disclose(proposalId));
283
+ const currentTime = getCurrentTime();
284
+ const config = governorConfig;
285
+
286
+ // 2. Validate proposal status and timing
287
+ assert(proposal.status == ProposalStatus.Active, "Proposal not active");
288
+ assert(currentTime > proposal.votingEndTime, "Voting period not ended");
289
+
290
+ // 3. Validate proposal hasn't exceeded lifetime
291
+ assert(currentTime <= proposal.createdAt + config.governance.proposalLifetime, "Proposal lifetime exceeded");
292
+
293
+ // Call simplified module function with validated data
294
+ finalizeProposal(disclose(proposalId), proof);
295
+ }
296
+
297
+ // Circuit to queue proposal with centralized validation
298
+ export circuit queueProposalWithValidation(
299
+ proposalId: Uint<64>,
300
+ proof: ProofOfGovernorApproval
301
+ ): [] {
302
+ assert(proof.proposalId == disclose(proposalId), "Proposal ID mismatch");
303
+
304
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
305
+
306
+ // 1. Validate proposal exists
307
+ const proposal = getProposal(disclose(proposalId));
308
+ const currentTime = getCurrentTime();
309
+ const config = governorConfig;
310
+
311
+ // 2. Validate proposal status
312
+ assert(proposal.status == ProposalStatus.Succeeded, "Proposal not succeeded");
313
+
314
+ // 3. Validate execution delay has passed (timelock)
315
+ const executionDeadline = (proposal.finalizedAt + config.governance.executionDelay) as Uint<64>;
316
+ assert(currentTime >= executionDeadline, "Execution delay not met");
317
+
318
+ // 4. Validate proposal hasn't expired (grace period check)
319
+ const gracePeriodDeadline = (proposal.finalizedAt + config.governance.executionDelay + config.governance.gracePeriod) as Uint<64>;
320
+ assert(currentTime <= gracePeriodDeadline, "Proposal expired - grace period passed");
321
+
322
+ // 5. Increment queued proposal counter
323
+ queuedProposalCount.increment(1);
324
+
325
+ // Call simplified module function with validated data
326
+ queueProposal(disclose(proposalId), proof);
327
+ }
328
+
329
+ // Circuit to mark proposal as executed with centralized validation
330
+ export circuit markProposalExecutedWithValidation(
331
+ proposalId: Uint<64>,
332
+ proof: ProofOfEffectExecution
333
+ ): [] {
334
+
335
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
336
+
337
+ // 1. Validate proposal exists
338
+ const proposal = getProposal(disclose(proposalId));
339
+ const currentTime = getCurrentTime();
340
+ const config = governorConfig;
341
+
342
+ // 2. Validate proposal status
343
+ assert(proposal.status == ProposalStatus.Queued, "Proposal not queued");
344
+
345
+ // 3. Validate grace period has not expired
346
+ const gracePeriodDeadline = (proposal.finalizedAt + config.governance.executionDelay + config.governance.gracePeriod) as Uint<64>;
347
+ assert(currentTime <= gracePeriodDeadline, "Grace period expired");
348
+
349
+ // 4. Validate proposal is within execution window
350
+ const executionStart = (proposal.finalizedAt + config.governance.executionDelay) as Uint<64>;
351
+ assert(currentTime >= executionStart, "Execution window not yet open");
352
+
353
+ // Call simplified module function with validated data
354
+ markProposalExecuted(disclose(proposalId), proof);
355
+ }
356
+
357
+ // Circuit to cancel proposal with centralized validation
358
+ export circuit cancelProposalWithValidation(
359
+ proposalId: Uint<64>,
360
+ proof: ProofOfGovernorApproval
361
+ ): [] {
362
+ assert(proof.proposalId == disclose(proposalId), "Proposal ID mismatch");
363
+
364
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
365
+
366
+ // 1. Validate proposal exists
367
+ const proposal = getProposal(disclose(proposalId));
368
+
369
+ // 2. Validate proposal can be cancelled
370
+ assert(proposal.status == ProposalStatus.Active || proposal.status == ProposalStatus.Queued, "Cannot cancel proposal");
371
+
372
+ // Call simplified module function with validated data
373
+ cancelProposal(disclose(proposalId), proof);
374
+
375
+ // Decrement counters based on proposal status
376
+ if (proposal.status == ProposalStatus.Active) {
377
+ activeProposalCount.decrement(1);
378
+ } else if (proposal.status == ProposalStatus.Queued) {
379
+ queuedProposalCount.decrement(1);
380
+ }
381
+ }
382
+
383
+ // Circuit to finalize proposal and queue for execution
384
+ export circuit finalizeAndQueueProposal(
385
+ proposalId: Uint<64>,
386
+ proof: ProofOfGovernorApproval
387
+ ): [] {
388
+ assert(proof.proposalId == disclose(proposalId), "Proposal ID mismatch");
389
+
390
+ // Finalize proposal with validation
391
+ finalizeProposalWithValidation(disclose(proposalId), proof);
392
+
393
+ // Decrement active proposal counter
394
+ activeProposalCount.decrement(1);
395
+ }
396
+
397
+ // Circuit to execute an effect with centralized validation
398
+ export circuit executeEffectWithValidation(
399
+ effectId: Uint<64>,
400
+ proof: ProofOfGovernorApproval
401
+ ): [] {
402
+
403
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
404
+
405
+ // 1. Validate effect exists
406
+ const effectKey = disclose(effectId);
407
+ const effect = getEffect(effectKey);
408
+ assert(effect.id != 0, "Effect does not exist");
409
+
410
+ // 2. Validate effect is pending
411
+ assert(effect.status == EffectStatus.Pending, "Effect not pending");
412
+
413
+ // 3. Validate effect actions have sufficient treasury balance
414
+ for (const action of effect.actions) {
415
+ if (action.typ == EffectActionType.Transfer) {
416
+ const treasuryBalance = getTreasuryBalance(action.token);
417
+ assert(treasuryBalance.amount >= action.amount, "Insufficient treasury balance for transfer");
418
+ }
419
+ }
420
+
421
+ // Call simplified module function with validated data
422
+ executeEffect(effectKey, proof);
423
+ }
424
+
425
+ // Circuit to create an effect with centralized validation
426
+ export circuit createEffectWithValidation(
427
+ proposalId: Uint<64>,
428
+ actions: Vector<10, EffectAction>,
429
+ proof: ProofOfStake
430
+ ): Uint<64> {
431
+
432
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
433
+
434
+ // 1. Validate effect actions
435
+ assert(validateEffectActions(disclose(actions)), "Invalid effect actions");
436
+
437
+ // 2. Additional treasury balance validations for transfer actions
438
+ for (const action of disclose(actions)) {
439
+ if (action.typ == EffectActionType.Transfer) {
440
+ const treasuryBalance = getTreasuryBalance(action.token);
441
+ assert(treasuryBalance.amount >= action.amount, "Insufficient treasury balance for planned transfer");
442
+ }
443
+ }
444
+
445
+ // Call simplified module function with validated data
446
+ return createEffect(proposalId, disclose(actions), proof);
447
+ }
448
+
449
+ // Circuit to cancel an effect with centralized validation
450
+ export circuit cancelEffectWithValidation(
451
+ effectId: Uint<64>,
452
+ proof: ProofOfGovernorApproval
453
+ ): [] {
454
+
455
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
456
+
457
+ // 1. Validate effect exists
458
+ const effectKey = disclose(effectId);
459
+ const effect = getEffect(effectKey);
460
+ assert(effect.id != 0, "Effect does not exist");
461
+
462
+ // 2. Validate effect is pending
463
+ assert(effect.status == EffectStatus.Pending, "Effect not pending");
464
+
465
+ // Call simplified module function with validated data
466
+ cancelEffect(effectKey, proof);
467
+ }
468
+
469
+ // Circuit to batch execute effects with centralized validation
470
+ export circuit batchExecuteEffectsWithValidation(
471
+ effectIds: Vector<10, Uint<64>>,
472
+ validCount: Uint<8>,
473
+ proof: ProofOfGovernorApproval
474
+ ): [] {
475
+
476
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
477
+
478
+ // Validate count is within bounds
479
+ assert(validCount <= 10, "Valid count exceeds maximum batch size");
480
+ assert(validCount > 0, "Valid count must be greater than 0");
481
+
482
+ // Validate each effect individually before batch execution
483
+ for (const effectId of effectIds) {
484
+ const effectKey = disclose(effectId);
485
+
486
+ const isValidEffect = effectKey != 0;
487
+ if (isValidEffect) { // Skip default/empty effect IDs
488
+ const effect = getEffect(effectKey);
489
+ const isPendingEffect = effect.id != 0 && effect.status == EffectStatus.Pending;
490
+ if (isPendingEffect) {
491
+ // Validate treasury balance for transfer actions
492
+ for (const action of effect.actions) {
493
+ const isTransferAction = action.typ == EffectActionType.Transfer;
494
+ if (isTransferAction) {
495
+ const treasuryBalance = getTreasuryBalance(action.token);
496
+ assert(treasuryBalance.amount >= action.amount, "Insufficient treasury balance for batch transfer");
497
+ }
498
+ }
499
+ }
500
+ }
501
+ }
502
+
503
+ // Call simplified module function with validated data
504
+ batchExecuteEffects(effectIds, proof);
505
+ }
506
+
507
+ // Circuit to execute a queued proposal
508
+ export circuit executeQueuedProposal(
509
+ proposalId: Uint<64>,
510
+ effectId: Uint<64>,
511
+ proof: ProofOfGovernorApproval
512
+ ): [] {
513
+ assert(proof.proposalId == disclose(proposalId), "Proposal ID mismatch");
514
+
515
+ const currentTime = getCurrentTime();
516
+ const proposal = getProposal(disclose(proposalId));
517
+
518
+ // Check if proposal is queued
519
+ assert(proposal.status == ProposalStatus.Queued, "Proposal not queued");
520
+
521
+ // Execute the effect with validation
522
+ const effectProof = ProofOfGovernorApproval {
523
+ proposalId: disclose(proposalId),
524
+ effectId: disclose(effectId),
525
+ approvalTime: currentTime,
526
+ nonce: proof.nonce
527
+ };
528
+
529
+ executeEffectWithValidation(disclose(effectId), effectProof);
530
+
531
+ // Mark proposal as executed with validation
532
+ const executionProof = ProofOfEffectExecution {
533
+ effectId: disclose(effectId),
534
+ executorId: default<Bytes<32>>, // Governor
535
+ executionTime: currentTime,
536
+ nonce: proof.nonce
537
+ };
538
+
539
+ markProposalExecutedWithValidation(disclose(proposalId), executionProof);
540
+
541
+ // Decrement queued proposal counter
542
+ queuedProposalCount.decrement(1);
543
+ }
544
+
545
+ // Circuit to cancel a proposal
546
+ export circuit cancelProposalWithReason(
547
+ proposalId: Uint<64>,
548
+ reason: Opaque<'string'>,
549
+ proof: ProofOfGovernorApproval
550
+ ): [] {
551
+ assert(proof.proposalId == disclose(proposalId), "Proposal ID mismatch");
552
+
553
+ const proposal = getProposal(disclose(proposalId));
554
+
555
+ // Cancel the proposal with validation
556
+ cancelProposalWithValidation(disclose(proposalId), proof);
557
+
558
+ // Cancel associated effect with validation
559
+ cancelEffectWithValidation(proposal.effectId, proof);
560
+ }
561
+
562
+ // Circuit to emergency veto a proposal
563
+ export circuit emergencyVetoProposal(
564
+ proposalId: Uint<64>,
565
+ vetoers: Vector<10, Bytes<32>>,
566
+ proof: ProofOfGovernorApproval
567
+ ): [] {
568
+ assert(proof.proposalId == disclose(proposalId), "Proposal ID mismatch");
569
+
570
+ const config = governorConfig;
571
+ assert(config.emergencyVetoEnabled, "Emergency veto not enabled");
572
+
573
+ // Calculate total veto power
574
+ const totalVetoPower = calculateTotalVetoPower(disclose(vetoers));
575
+
576
+ // Check if veto threshold is met
577
+ assert(totalVetoPower >= config.emergencyVetoThreshold, "Insufficient veto power");
578
+
579
+ // Cancel the proposal
580
+ cancelProposalWithReason(disclose(proposalId), default<Opaque<'string'>>, proof);
581
+ }
582
+
583
+
584
+ // Circuit to register stake with centralized validation
585
+ export circuit registerStakeWithValidation(
586
+ userId: Bytes<32>,
587
+ amount: Uint<64>,
588
+ proof: ProofOfStake
589
+ ): [] {
590
+ assert(proof.userId == disclose(userId), "User ID must match proof");
591
+ assert(proof.amount == disclose(amount), "Amount must match proof");
592
+
593
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
594
+
595
+ // 1. Validate minimum stake amount
596
+ const config = governorConfig;
597
+ assert(disclose(amount) >= config.governance.minStakeAmount, "Amount below minimum stake");
598
+
599
+ // Call simplified module function with validated data
600
+ registerStake(userId, amount, proof);
601
+ }
602
+
603
+ // Circuit to withdraw stake with centralized validation
604
+ export circuit withdrawStakeWithValidation(
605
+ userId: Bytes<32>,
606
+ amount: Uint<64>,
607
+ proof: ProofOfStake
608
+ ): [] {
609
+ assert(proof.userId == disclose(userId), "User ID must match proof");
610
+ assert(proof.amount == disclose(amount), "Amount must match proof");
611
+
612
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
613
+
614
+ // 1. Validate user has sufficient stake
615
+ const stakeRecord = getStakeRecord(disclose(userId));
616
+ assert(stakeRecord.amount >= disclose(amount), "Insufficient stake to withdraw");
617
+
618
+ // 2. Validate withdrawal conditions (staking period)
619
+ const currentTime = getCurrentTime();
620
+ const config = governorConfig;
621
+ const stakingPeriod = config.governance.stakingPeriod;
622
+ const timeSinceStaking = (currentTime - stakeRecord.stakedAt) as Uint<64>;
623
+ assert(timeSinceStaking >= stakingPeriod, "Invalid withdrawal conditions - staking period not met");
624
+
625
+ // Call simplified module function with validated data
626
+ withdrawStake(userId, amount, proof);
627
+ }
628
+
629
+ // Circuit to delegate stake with centralized validation
630
+ export circuit delegateStakeWithValidation(
631
+ delegator: Bytes<32>,
632
+ delegatee: Bytes<32>,
633
+ amount: Uint<64>,
634
+ proof: ProofOfStake
635
+ ): [] {
636
+ assert(proof.userId == disclose(delegator), "Delegator must match proof");
637
+
638
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
639
+
640
+ // 1. Validate amount is positive
641
+ assert(disclose(amount) > 0, "Amount must be positive");
642
+
643
+ // 2. Validate delegator has sufficient stake
644
+ const delegatorStake = getStakeRecord(disclose(delegator));
645
+ assert(delegatorStake.amount >= disclose(amount), "Insufficient stake to delegate");
646
+
647
+ // Call simplified module function with validated data
648
+ delegateStake(delegator, delegatee, amount, proof);
649
+ }
650
+
651
+ // Circuit to undelegate stake with centralized validation
652
+ export circuit undelegateStakeWithValidation(
653
+ delegator: Bytes<32>,
654
+ delegatee: Bytes<32>,
655
+ amount: Uint<64>,
656
+ proof: ProofOfStake
657
+ ): [] {
658
+ assert(proof.userId == disclose(delegator), "Delegator must match proof");
659
+
660
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
661
+
662
+ // 1. Validate amount is positive
663
+ assert(disclose(amount) > 0, "Amount must be positive");
664
+
665
+ // 2. Validate sufficient delegation exists
666
+ const delegationRecord = getDelegationRecord(disclose(delegator), disclose(delegatee));
667
+ assert(delegationRecord.amount >= disclose(amount), "Insufficient delegation to undelegate");
668
+
669
+ // Call simplified module function with validated data
670
+ undelegateStake(delegator, delegatee, amount, proof);
671
+ }
672
+
673
+ // Circuit to deposit to treasury with centralized validation
674
+ export circuit depositToTreasuryWithValidation(
675
+ token: Bytes<32>,
676
+ amount: Uint<64>,
677
+ depositor: Bytes<32>,
678
+ proof: ProofOfStake
679
+ ): [] {
680
+ assert(proof.userId == disclose(depositor), "Depositor must match proof");
681
+
682
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
683
+
684
+ // 1. Validate amount is positive
685
+ assert(disclose(amount) > 0, "Amount must be positive");
686
+
687
+ // Call simplified module function with validated data
688
+ depositToTreasury(token, amount, depositor, proof);
689
+ }
690
+
691
+ // Circuit to withdraw from treasury with centralized validation
692
+ export circuit withdrawFromTreasuryWithValidation(
693
+ token: Bytes<32>,
694
+ amount: Uint<64>,
695
+ recipient: Bytes<32>,
696
+ effectId: Uint<64>,
697
+ proof: ProofOfEffectExecution
698
+ ): [] {
699
+ assert(proof.effectId == disclose(effectId), "Effect ID must match proof");
700
+
701
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
702
+
703
+ // 1. Validate amount is positive
704
+ assert(disclose(amount) > 0, "Amount must be positive");
705
+
706
+ // 2. Validate sufficient treasury balance
707
+ const treasuryBalance = getTreasuryBalance(token);
708
+ assert(treasuryBalance.amount >= disclose(amount), "Insufficient treasury balance");
709
+
710
+ // Call simplified module function with validated data
711
+ withdrawFromTreasury(token, amount, recipient, effectId, proof);
712
+ }
713
+
714
+ // Circuit to transfer treasury tokens with centralized validation
715
+ export circuit transferTreasuryTokensWithValidation(
716
+ fromToken: Bytes<32>,
717
+ toToken: Bytes<32>,
718
+ amount: Uint<64>,
719
+ effectId: Uint<64>,
720
+ proof: ProofOfEffectExecution
721
+ ): [] {
722
+ assert(proof.effectId == disclose(effectId), "Effect ID must match proof");
723
+
724
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
725
+
726
+ // 1. Validate amount is positive
727
+ assert(disclose(amount) > 0, "Amount must be positive");
728
+
729
+ // 2. Validate tokens are different
730
+ assert(disclose(fromToken) != disclose(toToken), "Cannot transfer to same token");
731
+
732
+ // 3. Validate sufficient balance in source token
733
+ const fromBalance = getTreasuryBalance(fromToken);
734
+ assert(fromBalance.amount >= disclose(amount), "Insufficient balance in source token");
735
+
736
+ // Call simplified module function with validated data
737
+ transferTreasuryTokens(fromToken, toToken, amount, effectId, proof);
738
+ }
739
+
740
+ // Circuit to burn treasury tokens with centralized validation
741
+ export circuit burnTreasuryTokensWithValidation(
742
+ token: Bytes<32>,
743
+ amount: Uint<64>,
744
+ effectId: Uint<64>,
745
+ proof: ProofOfEffectExecution
746
+ ): [] {
747
+ assert(proof.effectId == disclose(effectId), "Effect ID must match proof");
748
+
749
+ // CENTRALIZED VALIDATIONS: Done in Governor to avoid ledger state isolation
750
+
751
+ // 1. Validate amount is positive
752
+ assert(disclose(amount) > 0, "Amount must be positive");
753
+
754
+ // 2. Validate sufficient treasury balance
755
+ const treasuryBalance = getTreasuryBalance(token);
756
+ assert(treasuryBalance.amount >= disclose(amount), "Insufficient treasury balance");
757
+
758
+ // Call simplified module function with validated data
759
+ burnTreasuryTokens(token, amount, effectId, proof);
760
+ }
761
+
762
+ // Circuit to update governor configuration
763
+ export circuit updateGovernorConfig(
764
+ newConfig: GovernorConfig,
765
+ proof: ProofOfGovernorApproval
766
+ ): [] {
767
+ assert(isCurrentUserAdmin(), "Only admin can update governor config");
768
+ governorConfig = disclose(newConfig);
769
+ updateGovernanceConfig(disclose(newConfig.governance), proof);
770
+ }
771
+
772
+ // Circuit to get governor status
773
+ export circuit getGovernorStatus(): GovernorStatus {
774
+ const currentTime = getCurrentTime();
775
+
776
+ return GovernorStatus {
777
+ currentTime,
778
+ activeProposalCount: activeProposalCount.read(),
779
+ queuedProposalCount: queuedProposalCount.read(),
780
+ config: governorConfig
781
+ };
782
+ }
783
+
784
+ // Circuit to get active proposal count
785
+ export circuit getActiveProposalCount(): Uint<64> {
786
+ return activeProposalCount.read();
787
+ }
788
+
789
+ // Circuit to get queued proposal count
790
+ export circuit getQueuedProposalCount(): Uint<64> {
791
+ return queuedProposalCount.read();
792
+ }
793
+
794
+
795
+
796
+ // Helper functions
797
+ export circuit calculateTotalVetoPower(vetoers: Vector<10, Bytes<32>>): Uint<64> {
798
+ // Calculate total veto power from all vetoers
799
+ // Since we can't iterate easily in Compact, we'll check each position manually
800
+ const vetoer0 = disclose(vetoers[0]);
801
+ const vetoer1 = disclose(vetoers[1]);
802
+ const vetoer2 = disclose(vetoers[2]);
803
+ const vetoer3 = disclose(vetoers[3]);
804
+ const vetoer4 = disclose(vetoers[4]);
805
+ const vetoer5 = disclose(vetoers[5]);
806
+ const vetoer6 = disclose(vetoers[6]);
807
+ const vetoer7 = disclose(vetoers[7]);
808
+ const vetoer8 = disclose(vetoers[8]);
809
+ const vetoer9 = disclose(vetoers[9]);
810
+
811
+ const power0 = vetoer0 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer0) : 0 as Uint<64>;
812
+ const power1 = vetoer1 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer1) : 0 as Uint<64>;
813
+ const power2 = vetoer2 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer2) : 0 as Uint<64>;
814
+ const power3 = vetoer3 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer3) : 0 as Uint<64>;
815
+ const power4 = vetoer4 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer4) : 0 as Uint<64>;
816
+ const power5 = vetoer5 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer5) : 0 as Uint<64>;
817
+ const power6 = vetoer6 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer6) : 0 as Uint<64>;
818
+ const power7 = vetoer7 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer7) : 0 as Uint<64>;
819
+ const power8 = vetoer8 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer8) : 0 as Uint<64>;
820
+ const power9 = vetoer9 != default<Bytes<32>> ? getTotalDelegatedPower(vetoer9) : 0 as Uint<64>;
821
+
822
+ const totalPower = (((((((((power0 + power1) + power2) + power3) + power4) + power5) + power6) + power7) + power8) + power9) as Uint<64>;
823
+
824
+ return totalPower;
825
+ }
826
+
827
+
828
+ // Circuit to check governor permissions
829
+ export circuit hasGovernorPermission(
830
+ userId: Bytes<32>,
831
+ requiredPermission: GovernorPermission
832
+ ): Boolean {
833
+ const userKey = disclose(userId);
834
+ const userPermission = governorPermissions.member(userKey) ? governorPermissions.lookup(userKey) : GovernorPermission.None;
835
+ return userPermission == requiredPermission || userPermission == GovernorPermission.Admin;
836
+ }
837
+
838
+ // Helper function to get local secret key or error
839
+ export circuit local_sk_or_error(): Bytes<32> {
840
+ const maybe_sk = disclose(local_secret_key());
841
+ assert(maybe_sk.is_some, "Local secret key is not set");
842
+ const sk = maybe_sk.value;
843
+
844
+ return sk;
845
+ }
846
+
847
+ // Helper function to check if current user is admin
848
+ export circuit isCurrentUserAdmin(): Boolean {
849
+ const sk = local_sk_or_error();
850
+ return hasGovernorPermission(sk, GovernorPermission.Admin);
851
+ }
852
+
853
+ // Generate a hash of a key
854
+ export circuit getKeyHash(key: Bytes<32>): Bytes<32> {
855
+ return persistentHash<Vector<2, Bytes<32>>>([pad(32, "keyhash:"), key]);
856
+ }
857
+
858
+ // Circuit to set system timestamp (admin only)
859
+ export circuit setSystemTimestamp(
860
+ timestamp: Uint<64>,
861
+ ): [] {
862
+ assert(isCurrentUserAdmin(), "Only admin can set system timestamp");
863
+ storeTimestamp(disclose(timestamp));
864
+ }
865
+
866
+ // Circuit to set governor permissions (admin only)
867
+ export circuit setGovernorPermissionSecure(
868
+ userId: Bytes<32>,
869
+ permission: GovernorPermission,
870
+ proof: ProofOfGovernorApproval
871
+ ): [] {
872
+ assert(isCurrentUserAdmin(), "Only admin can set governor permissions");
873
+ governorPermissions.insert(disclose(userId), disclose(permission));
874
+ }
875
+