Skip to content

feat(contract-dev): edit random numbers guide to fit style guide and use Tolk code#2115

Open
kay-is wants to merge 7 commits intomainfrom
random-numbers-style
Open

feat(contract-dev): edit random numbers guide to fit style guide and use Tolk code#2115
kay-is wants to merge 7 commits intomainfrom
random-numbers-style

Conversation

@kay-is
Copy link
Copy Markdown
Collaborator

@kay-is kay-is commented Apr 22, 2026

Fixes #2113.

Summary by CodeRabbit

  • Documentation
    • Updated randomness guidance with new API examples and references.
    • Reorganized content into a consolidated comparison table and clearer sections for single-block, block-skipping, and commit-reveal approaches.
    • Clarified security model and attacker/validator limitations for each approach.
    • Strengthened best practices: require RNG initialization before use, warn about external-message vulnerabilities, and recommend testnet testing under validator manipulation.
    • Presentation tweaks: clearer step phrasing, labeled code blocks, and added caution notes.

Copilot AI review requested due to automatic review settings April 22, 2026 15:16
@kay-is kay-is requested a review from a team as a code owner April 22, 2026 15:16
@mintlify
Copy link
Copy Markdown

mintlify Bot commented Apr 22, 2026

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
mintlify-ton-docs 🟢 Ready View Preview Apr 22, 2026, 3:18 PM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 22, 2026

Warning

Rate limit exceeded

@kay-is has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 46 minutes and 23 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 46 minutes and 23 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: deecbe10-eb12-4cd1-b63f-0e66bf2ce5ca

📥 Commits

Reviewing files that changed from the base of the PR and between 46dba6e and b30eb35.

📒 Files selected for processing (1)
  • contract-dev/techniques/random.mdx
📝 Walkthrough

Walkthrough

This PR updates the randomness techniques document to use the new APIs (random.initialize(), random.uint256(), random.range()), reorganizes approach sections and comparison table, and revises security and best-practice guidance to reflect the deterministic-PRNG framing and initialization requirement.

Changes

Cohort / File(s) Summary
Documentation
contract-dev/techniques/random.mdx
Replaced legacy random()/randomize_lt() references with random.initialize(), random.uint256(), and random.range(); removed multi-approach split in favor of a consolidated comparison table; reworked security model text (deterministic PRNG framing, validator timing/censorship notes); updated best practices to require random.initialize() and changed testing guidance; minor presentation/markup edits (labeled code fences, caution aside).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐇 I hopped through docs to make things clear,
Old calls replaced so new APIs appear,
Initialize first, then numbers will play,
Range and uint dance in a deterministic way,
Hooray for clarity—now hop on, hooray! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title mentions updating the guide to fit style guide and use Tolk code, which aligns with the main changes documented in the summary.
Linked Issues check ✅ Passed The PR addresses issue #2113 by documenting style cleanup and Tolk code migration for the random numbers guide, matching the stated objectives.
Out of Scope Changes check ✅ Passed All changes are confined to the random numbers documentation file with style updates and Tolk code examples, directly addressing the linked issue requirements.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch random-numbers-style

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates to contract-dev/techniques/random.mdx: there are several suggestions to align terminology, safety guidance, and best-practices wording—please apply the inline suggestions.

Comment thread contract-dev/techniques/random.mdx
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Updates the “Random numbers” technique guide to match the documentation style guide and replaces FunC-centric examples/links with Tolk equivalents.

Changes:

  • Rewrites the introduction and “why randomness is hard” sections for style/clarity.
  • Replaces FunC APIs (randomize_lt, rand, random) with Tolk APIs (random.initialize, random.range, random.uint256) and updates the example code block to Tolk.
  • Reorganizes content by adding a comparison table and tightening the security-model descriptions for each approach.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx
@github-actions

This comment has been minimized.

@kay-is
Copy link
Copy Markdown
Collaborator Author

kay-is commented Apr 22, 2026

/review

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for improving the randomness documentation in contract-dev/techniques/random.mdx: I’ve left a couple of suggestions to clarify high-stakes guidance and environment usage—please apply the inline suggestions.

Comment thread contract-dev/techniques/random.mdx
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
@kay-is
Copy link
Copy Markdown
Collaborator Author

kay-is commented Apr 23, 2026

/review

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates in contract-dev/techniques/random.mdx: I have one inline suggestion to strengthen safety guidance around high-value randomness use cases; please apply the inline suggestion.

Comment thread contract-dev/techniques/random.mdx
@github-actions

This comment has been minimized.

@kay-is kay-is marked this pull request as ready for review April 23, 2026 08:28
Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update to contract-dev/techniques/random.mdx: I’ve suggested one critical inline improvement to strengthen the guidance around randomness safety—please apply the inline suggestion.

Comment thread contract-dev/techniques/random.mdx
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
contract-dev/techniques/random.mdx (3)

69-73: ⚠️ Potential issue | 🟠 Major

Clarify that random.initialize() is required setup, not sufficient security.

Line 72 says not to use random.initialize() for high-value applications, while Line 134 says to always call it. The risk is relying on single-block randomness, not the initialization call itself.

Suggested wording
-  Validators can predict single-block randomness. Do not use `random.initialize()` for high-value applications such as financial lotteries or significant asset distribution.
+  Validators can predict single-block randomness. Do not rely on single-block randomness that only calls `random.initialize()` for high-value applications such as financial lotteries or significant asset distribution.
-- Always call `random.initialize()` before using `random.uint256()` or `random.range()` to prevent users from predicting random values.
-- Keep randomness out of external message receivers. External messages remain vulnerable even with `random.initialize()`.
+- For single-block randomness, call `random.initialize()` before using `random.uint256()` or `random.range()`. This reduces regular-user prediction risk, but does not protect against validator control.
+- Keep randomness out of external message receivers. External messages remain vulnerable even with `random.initialize()`.

Also applies to: 134-135

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@contract-dev/techniques/random.mdx` around lines 69 - 73, Update the caution
and the instruction that calls random.initialize() to make clear that
random.initialize() is a required setup step but does not provide secure
randomness by itself; specifically, modify the Aside warning and the guidance
around random.initialize() to say “always call random.initialize() during setup,
but do not rely on single-block randomness for high-value use cases” and mention
recommended alternatives (e.g., VRF, commit-reveal, or an oracle like Chainlink)
for secure randomness instead of relying solely on random.initialize().

25-25: ⚠️ Potential issue | 🟡 Minor

Replace vague speed intensifiers with concrete wording.

“Very slow”/“very slow” is subjective and repeats a previously flagged style issue. Prefer “Slow” in the table and reserve the explanatory timing detail for the Speed section.

Suggested wording
-| Speed                                | Fast                                     | Slow                                                         | Very slow                                                          |
+| Speed                                | Fast                                     | Slow                                                         | Slow                                                               |
-The commit-reveal scheme is very slow compared to other approaches, as it involves multiple phases and requires waiting for several blocks to complete the process. The time to finality can range from minutes to hours depending on the number of participants and block times.
+The commit-reveal scheme is slower than the other approaches, as it involves multiple phases and requires waiting for several blocks to complete the process. The time to finality can range from minutes to hours depending on the number of participants and block times.

Also applies to: 118-118

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@contract-dev/techniques/random.mdx` at line 25, Replace the
subjective/redundant "Very slow" cell in the table row (the cell containing the
Speed intensity labels: "Fast | Slow | Very slow") with "Slow" so the table uses
a single concrete label, and update the corresponding explanatory text in the
"Speed" section (the narrative paragraph that expands on timing) to include the
timing detail previously implied by "Very slow"; also remove the duplicate "Very
slow" occurrence noted elsewhere (the second occurrence flagged) so both table
cells use consistent concrete wording ("Slow") and timing is documented only in
the Speed section.

100-100: ⚠️ Potential issue | 🟠 Major

Avoid unconditional security claims for commit-reveal.

“Cryptographically secure” and “the most secure” overstate the guarantee unless participant independence, binding commitments, penalties, and censorship assumptions are satisfied.

Suggested wording
-Multiple participants commit to secret values by publishing hashes, then reveal those values in a later phase. The final randomness is derived from combining all revealed values, ensuring no single party can determine the outcome alone. When properly implemented, this approach provides cryptographically secure randomness suitable for high-value applications.
+Multiple participants commit to secret values by publishing hashes, then reveal those values in a later phase. The final randomness is derived from combining all valid revealed values, reducing the ability of any single party to determine the outcome alone. With binding commitments, independent participants, non-reveal penalties, and review, this approach can support high-value applications.
-The commit-reveal scheme is the most secure on-chain randomness approach, as it relies on cryptographic commitments and multiple independent participants. It prevents any single participant from unilaterally determining the final value.
+The commit-reveal scheme can provide stronger on-chain randomness guarantees than single-block or block-skipping approaches when it relies on cryptographic commitments and multiple independent participants. It prevents any single participant from unilaterally determining the final value under those assumptions.

Also applies to: 110-110

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@contract-dev/techniques/random.mdx` at line 100, The statement about
"commit-reveal" overclaims security; change the sentence asserting it is
"cryptographically secure" to a conditional claim that depends on specific
assumptions by updating the paragraph about commit-reveal to note that it can
provide strong unpredictability only when participant independence, binding
commitments, enforceable penalties or slashing for non-reveal, and
censorship-resistance are ensured; explicitly remove absolute terms like
"cryptographically secure" and "the most secure" and replace with phrasing such
as "can provide strong randomness under the above conditions" and/or list the
required assumptions so readers understand the limits of the commit-reveal
scheme.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@contract-dev/techniques/random.mdx`:
- Around line 104-106: Update the "Commit phase"/"Reveal phase"/"Combination"
sections to require domain-separated, canonical commitments: instruct
participants to commit to H(domain || round_id || participant_id ||
random_nonce) instead of hashing the raw random number, and require the contract
to verify participant_id and round_id when accepting reveals; also replace or
augment the XOR/sum example with a canonical aggregation specification (e.g.,
sort participant IDs and aggregate in that deterministic order or use a vetted
merge function) to prevent replay/duplication attacks and cancellation issues.

---

Duplicate comments:
In `@contract-dev/techniques/random.mdx`:
- Around line 69-73: Update the caution and the instruction that calls
random.initialize() to make clear that random.initialize() is a required setup
step but does not provide secure randomness by itself; specifically, modify the
Aside warning and the guidance around random.initialize() to say “always call
random.initialize() during setup, but do not rely on single-block randomness for
high-value use cases” and mention recommended alternatives (e.g., VRF,
commit-reveal, or an oracle like Chainlink) for secure randomness instead of
relying solely on random.initialize().
- Line 25: Replace the subjective/redundant "Very slow" cell in the table row
(the cell containing the Speed intensity labels: "Fast | Slow | Very slow") with
"Slow" so the table uses a single concrete label, and update the corresponding
explanatory text in the "Speed" section (the narrative paragraph that expands on
timing) to include the timing detail previously implied by "Very slow"; also
remove the duplicate "Very slow" occurrence noted elsewhere (the second
occurrence flagged) so both table cells use consistent concrete wording ("Slow")
and timing is documented only in the Speed section.
- Line 100: The statement about "commit-reveal" overclaims security; change the
sentence asserting it is "cryptographically secure" to a conditional claim that
depends on specific assumptions by updating the paragraph about commit-reveal to
note that it can provide strong unpredictability only when participant
independence, binding commitments, enforceable penalties or slashing for
non-reveal, and censorship-resistance are ensured; explicitly remove absolute
terms like "cryptographically secure" and "the most secure" and replace with
phrasing such as "can provide strong randomness under the above conditions"
and/or list the required assumptions so readers understand the limits of the
commit-reveal scheme.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 131b0e2a-42a8-45d8-8a73-6d4d39279880

📥 Commits

Reviewing files that changed from the base of the PR and between a70d91a and 46dba6e.

📒 Files selected for processing (1)
  • contract-dev/techniques/random.mdx

Comment on lines +104 to +106
1. **Commit phase**: Each participant generates a random number off-chain and submits its hash to the contract.
1. **Reveal phase**: After all commitments are received, participants disclose their original numbers.
1. **Combination**: The contract combines the revealed numbers (e.g., by XOR or sum) to produce the final random value.
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Apr 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Bind commitments to the participant and round.

Hashing only the random number is copyable and replayable; with XOR aggregation, duplicated commitments can also cancel out. The guide should require domain-separated commitments and canonical aggregation.

Suggested wording
-1. **Commit phase**: Each participant generates a random number off-chain and submits its hash to the contract.
+1. **Commit phase**: Each participant generates a secret off-chain and submits a domain-separated hash that binds the secret to the participant address, contract address, and round identifier.
 1. **Reveal phase**: After all commitments are received, participants disclose their original numbers.
-1. **Combination**: The contract combines the revealed numbers (e.g., by XOR or sum) to produce the final random value.
+1. **Combination**: The contract validates each reveal, rejects duplicates or mismatched commitments, orders accepted reveals canonically, and hashes the transcript to produce the final random value.
 - On-chain verification of commitments.
+- Domain separation and replay protection for commitments.
+- Duplicate commitment handling.
 - Penalty mechanisms for non-reveals or invalid reveals.
 - Timeout handling for missing participants.

Also applies to: 120-124

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@contract-dev/techniques/random.mdx` around lines 104 - 106, Update the
"Commit phase"/"Reveal phase"/"Combination" sections to require
domain-separated, canonical commitments: instruct participants to commit to
H(domain || round_id || participant_id || random_nonce) instead of hashing the
raw random number, and require the contract to verify participant_id and
round_id when accepting reveals; also replace or augment the XOR/sum example
with a canonical aggregation specification (e.g., sort participant IDs and
aggregate in that deterministic order or use a vetted merge function) to prevent
replay/duplication attacks and cancellation issues.

Copy link
Copy Markdown
Collaborator Author

@kay-is kay-is Apr 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @novusnota or @delovoyhomie, can one of you confirm this?

It sounds reasonable, but my crypto skills aren't strong enough to check this without substantial effort 🫣

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@novusnota novusnota requested review from Kaladin13 and Shvandre April 23, 2026 09:22
delovoyhomie
delovoyhomie previously approved these changes Apr 23, 2026
Comment thread contract-dev/techniques/random.mdx
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Comment thread contract-dev/techniques/random.mdx Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Contract dev > Techniques > Random numbers] Style cleanup & Tolk port

3 participants