gas: redundant SLOADs/external calls in the highest-traffic task-contract and staking paths
メンテナーはふだん 1 日以内に返信
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 54/100
- issue の種類
- リファクタリング
- 明瞭さ
- 明確に書かれている
- 活発さ
- 活発
- 技術スタック
- solidity
- 領域
- backend, blockchain, performance
調査の方向性
Start in foundry/src/DINTaskCoordinator.sol, DINTaskAuditor.sol, and DinValidatorStake.sol; the issue lists the affected functions and line locations. Read those functions and run the relevant Foundry tests before making changes. Cache repeated reads and loop values as described in findings 1–4, and replace the string reverts in releaseGIRegistrationSlots as in finding 5; done when the behavior stays the same and the changes pass the contract tests.
索引モデルが issue の本文から書いたものです。
説明
Summary
Five safe, behavior-preserving gas optimizations found during a fresh pass over foundry/src/ (checked against develop @ 6e361cb), all in the repo's highest-call-frequency paths (every registration, every GI finalize/slash, every stake/unstake/slash). None change the public ABI, storage layout, or any revert/event behavior — each just caches a value that's already being read/computed and reuses it instead of re-reading. Batched into one issue since they're the same category of fix (cache-before-reuse) repeated across a few files, rather than filing five near-identical issues.
This followed a scan explicitly looking for a different angle than the security/correctness review already done on this codebase (C-1's gas-DoS, the EIP-170 size-reduction passes) — this is runtime gas-per-call, not bytecode size or unbounded-loop risk. No new unbounded-loop gas-DoS was found beyond the already-tracked C-1/BL-10 class.
Findings
1. Duplicate getStake(msg.sender) call in every aggregator/auditor registration
foundry/src/DINTaskCoordinator.sol:414 and :422 (registerDINaggregator), foundry/src/DINTaskAuditor.sol (registerDINAuditor, identical shape) — dinvalidatorStakeContract.getStake(msg.sender) is called once for the per-model stake-floor check and again for the concurrent-registration-cap check:
uint256 floorMin = dinvalidatorStakeContract.getModelStakeMin(modelId);
if (floorMin > 0 && dinvalidatorStakeContract.getStake(msg.sender) < floorMin) // call #1
revert TC_StakeBelowModelFloor();
uint256 capPerUnit = dinvalidatorStakeContract.maxConcurrentRegistrationsPerStakeUnit();
if (capPerUnit > 0) {
uint256 maxAllowed = (dinvalidatorStakeContract.getStake(msg.sender) / // call #2, same value
dinvalidatorStakeContract.minStake()) * capPerUnit;
...
Fix: read uint256 stake = dinvalidatorStakeContract.getStake(msg.sender); once, reuse in both branches. Saves a full external STATICCALL (~150-700 gas) on every registration once both DAO knobs are non-zero (both default to 0 today, so the saving is currently latent, but the fix is free and unconditionally safe to apply now).
2. _activeAggregatorPool/_activeAuditorPool call isValidatorActive twice per registrant
foundry/src/DINTaskCoordinator.sol:692-714, foundry/src/DINTaskAuditor.sol:793-815 — the classic "count then fill" two-pass pattern for sizing a memory array re-queries isValidatorActive(registeredPool[i]) for the same address in both passes:
for (uint i = 0; i < registeredPool.length; i++) {
if (dinvalidatorStakeContract.isValidatorActive(registeredPool[i])) { activeCount++; }
}
activePool = new address[](activeCount);
uint ptr;
for (uint i = 0; i < registeredPool.length; i++) {
address validator = registeredPool[i];
if (dinvalidatorStakeContract.isValidatorActive(validator)) { activePool[ptr++] = validator; } // re-queries
}
Fix: store each result in a bool[] memory active during the first pass, read from that in the second instead of re-calling. Saves one external CALL per active registrant — called once per GI by autoCreateTier1AndTier2/createAuditorsBatches, over up to 300 registrants (MAX_REGISTERED_AGGREGATORS/MAX_REGISTERED_AUDITORS), so potentially tens of thousands of gas per GI at scale.
3. array.length/struct-field re-read every loop iteration in the finalize/slash functions
Several spots re-read a storage array's .length or a struct field every iteration of a loop where neither changes during the loop:
DINTaskCoordinator.sol:finalizeT1Aggregation(batches.lengthat the outer loop,b.aggregators.length+b.batchIdre-read in the inner loop),finalizeT2Aggregation(same shape),slashAggregators(t1batches.length/t2batches.length)DINTaskAuditor.sol:finalizeEvaluation(batch.modelIndexes.length/batch.auditors.lengthre-read per inner iteration, plus twice more for twonewarray allocations sized from the same field),slashAuditors(batch.auditors.length/batch.modelIndexes.lengthre-read per inner iteration)
Example (finalizeT1Aggregation):
for (uint i = 0; i < batches.length; i++) {
Tier1Batch storage b = batches[i];
for (uint j = 0; j < b.aggregators.length; j++) { // storage SLOAD every iteration
address aggregator = b.aggregators[j];
if (t1Submitted[_GI][b.batchId][aggregator]) { // b.batchId re-read multiple times too
Fix: cache uint256 aggLen = b.aggregators.length; and uint256 batchId = b.batchId; once per outer iteration, and the outer .length once before the loop. Each avoided re-read is a warm SLOAD (~100 gas); for a 3-aggregator batch, b.batchId alone is read ~9x instead of once. These are exactly the functions C-1 already flagged for O(n) asymptotic cost (pagination is still the real fix for that) — this doesn't change the shape, just shaves a constant factor off every call today, called every single GI.
4. _syncValidatorStatus reads status and activeStake twice each
foundry/src/DinValidatorStake.sol:716-737 — validator.status is checked twice (both reads of the same packed slot, no intervening write) and validator.activeStake is read twice in a mutually-exclusive else if chain:
function _syncValidatorStatus(ValidatorInfo storage validator) internal {
if (validator.status == ValidatorStatus.Blacklisted) { return; } // read #1
if (validator.status == ValidatorStatus.Jailed && validator.jailedUntil > block.timestamp) { return; } // read #2
if (validator.pendingWithdrawals > 0) { validator.status = ValidatorStatus.Exiting; }
else if (validator.activeStake >= MIN_STAKE) { validator.status = ValidatorStatus.Active; } // read #1
else if (validator.activeStake > 0) { validator.status = ValidatorStatus.Exiting; } // read #2
else { validator.status = ValidatorStatus.None; }
}
Fix: cache both into locals at the top, reuse. This is the most-called internal helper in the contract — invoked from stake, unstake, claimUnstaked, reactivate, unblacklistValidator, and (via _applySlash) every slash/slashPartial/recordNoParticipation call. ~100 gas (one warm SLOAD) per avoided extra read, on every stake and every slash.
5. One stray require(..., "string") instead of a custom error
foundry/src/DINTaskCoordinator.sol:1290-1291 (releaseGIRegistrationSlots) — every other revert path in both task contracts uses a custom error; this function is the one holdout:
require(giEnded, "GI has not ended");
require(!registrationSlotsReleased[_GI], "slots already released");
Fix: add TC_GINotEnded()/TC_SlotsAlreadyReleased() custom errors and swap. Small (string-revert overhead only hits the revert path, not the happy path), but free and consistent with the rest of the file.
Considered, not recommending without a decision
Three struct-packing opportunities (DINTaskAuditor.LMSubmission, DinEmission.EmissionState, DINModelRegistry.ModelRequest) could save a storage slot each by reordering/shrinking fields, but all three structs sit behind a public array/mapping whose auto-generated getter encodes fields in declared order (or type, for EmissionState) — so the fix would change the public ABI's output shape, not just internal layout. LMSubmission is the highest-value one (called every submitLocalModel, every client, every GI — a full SSTORE's worth, ~20k+ gas, if it drops from 4 slots to 3), but making lmSubmissions internal and hand-writing a reassembling getter is real added complexity. Not filing as actionable work; noting here in case a maintainer wants to make that call deliberately.
Recommendation
All five numbered findings are mechanical, zero-behavior-change read-caching — safe to implement directly. No storage layout, ABI, event, or revert-selector changes beyond #5 (which only changes the revert error type, already the norm everywhere else in these files).
- 主要言語
- Python
- スター
- 4
- フォーク
- 7
- 平均マージ
- 3日 58分
- マージ済み PR(30日)
- 39
環境構築
このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
InfiniteZeroFoundation/DevNet のほかの issue
-
dincli: `task model-owner register-request --manifestCID` fails because the registry contract isn't initialised対応中かも このイシューにリンクされたプルリクエストがオープン中、またはマージ済みです。 オープンbug good first issue
難易度 2/5 1〜3時間 初心者へのやさしさ 79/100
InfiniteZeroFoundation/DevNet#295 ·
メンテナーはふだん 1 日以内に返信
-
ROADMAP.md: refresh "What is still open for P3" (several items were fixed in October)対応中かも @umermjd11 が 1 日前に担当しました。 オープンdocumentation good first issue
難易度 2/5 1〜3時間 初心者へのやさしさ 74/100
InfiniteZeroFoundation/DevNet#285 · 担当者 1 名 ·
メンテナーはふだん 1 日以内に返信
-
good first issue help wanted
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
InfiniteZeroFoundation/DevNet#277 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
InfiniteZeroFoundation/DevNet#266 ·
メンテナーはふだん 1 日以内に返信
-
Approved documentation
難易度 1/5 1〜3時間 初心者へのやさしさ 82/100
InfiniteZeroFoundation/DevNet#248 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
InfiniteZeroFoundation/DevNet の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
メンテナーはふだん 1 日以内に返信
-
[oblt-aw][autodoc] Document obs-aw-automerge contract and fix automerge doc inconsistencies対応中かも @github-actions が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
メンテナーはふだん 1 日以内に返信
-
admission-deferred priority: medium status: ready work-class: scoped
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
melodic-software/claude-code-plugins#10887 · コメント 4 件 ·
メンテナーはふだん 1 日以内に返信
-
backend bug good first issue
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
PoCInnovation/Distribox#255 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
google/langextract#598 ·
メンテナーはふだん 1 日以内に返信