Skip to content

refactor(security-practices): port security article code samples to Tolk#2134

Open
aigerimu wants to merge 6 commits into
mainfrom
security-edits
Open

refactor(security-practices): port security article code samples to Tolk#2134
aigerimu wants to merge 6 commits into
mainfrom
security-edits

Conversation

@aigerimu
Copy link
Copy Markdown
Contributor

@aigerimu aigerimu commented Apr 27, 2026

closes #1186

Summary by CodeRabbit

  • Documentation
    • Modernized security best-practice examples to a unified style and updated message/handler patterns.
    • Added explicit error handling (ErrCode/assert) across examples for arithmetic, replay protection, authorization, and signature checks.
    • Expanded guidance on signed-request front-running prevention (with a secure and insecure variant), persistent storage helpers, and seqno handling.
    • Clarified examples for gas handling, address/workchain validation, name collisions, type consistency, and return-value checks.

@aigerimu aigerimu requested a review from a team as a code owner April 27, 2026 06:53
@mintlify
Copy link
Copy Markdown

mintlify Bot commented Apr 27, 2026

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

Project Status Preview Updated (UTC)
mintlify-ton-docs 🟢 Ready View Preview Apr 27, 2026, 6:54 AM

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

@aigerimu aigerimu marked this pull request as draft April 27, 2026 06:53
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d7fba722-cea6-451d-89cd-873f7b7a8a56

📥 Commits

Reviewing files that changed from the base of the PR and between 47416ab and 9a5f1a9.

📒 Files selected for processing (1)
  • contract-dev/techniques/security.mdx
✅ Files skipped from review due to trivial changes (1)
  • contract-dev/techniques/security.mdx

📝 Walkthrough

Walkthrough

Converts security best-practice code samples in documentation from func/tact to tolk, updating handler names, storage API calls, message acceptance, and explicit error/assert patterns across numerous inline examples; no API or exported/public declarations were changed. (47 words)

Changes

Cohort / File(s) Summary
Security Documentation & Code Examples
contract-dev/techniques/security.mdx
All inline code examples converted from func/tact to tolk style. Updates include handler renames (recv_internal/recv_externalonInternalMessage/onExternalMessage), storage API swaps (get_data/set_datacontract.getData/contract.setData), message acceptance renames, introduction of ErrCode/assert-based explicit error handling, guarded arithmetic for transfers, replay-protection seqno logic, signed-context checks and persistent Storage helpers, and multiple illustrative examples (destruction race, replay, external validation, gas/excess handling, cross-contract exchange, address/workchain checks, name-collision, type consistency, and update authorization).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Hopping through snippets, tidy and brisk,

I swapped old tricks for a safer risk.
Tolks lined up, assertions in place,
Storage snug in its new little space.
A joyful twitch — docs polished with grace.

🚥 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 'refactor(security-practices): port security article code samples to Tolk' accurately describes the main change: converting code samples in the security documentation from other languages to Tolk.
Linked Issues check ✅ Passed The PR successfully addresses issue #1186 by porting all code examples in the Security Best Practices article to Tolk format, as required.
Out of Scope Changes check ✅ Passed All changes are directly related to the primary objective of converting security documentation code samples to Tolk; no out-of-scope modifications are present.
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 security-edits

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

@aigerimu aigerimu changed the title refactor(security-practices): port gas article code samples to Tolk refactor(security-practices): port security article code samples to Tolk Apr 27, 2026
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx Outdated
Comment thread contract-dev/techniques/security.mdx
@github-actions
Copy link
Copy Markdown
Contributor

Thanks for the detailed security documentation updates in contract-dev/techniques/security.mdx: I have several suggestions to align language tags, phrasing, and terminology with the style guide; please apply the inline suggestions.


Per-comment submission: 9 posted, 2 failed.

Unposted inline comments (raw text):

  • contract-dev/techniques/security.mdx:L88-L90

    [HIGH] Wikipedia link used as primary replay-attack explanation

    Lines 88–90 describe replay protection and link “reusing a previous message” to Wikipedia’s Replay_attack article as the only explanation of the concept. The extended style guide prefers internal documentation or official specs for normative explanations in security-sensitive sections, and allows Wikipedia only as non‑normative background. As written, the sentence relies on Wikipedia as the primary definition for a security concept, which conflicts with that guidance.

    Please leave a reaction 👍/👎 to this suggestion to improve future reviews for everyone!

  • contract-dev/techniques/security.mdx:L387-L395

    [HIGH] Non-standard tolk fences in address-format example

    The “Address formats” example around lines 387–395 uses a tolk fenced block to show raw, bounceable, and non-bounceable addresses and a forceChain call. This continues the file-wide pattern of using an undocumented language tag. To align with the extended style guide, examples showing code-like configuration or API usage should employ a recognized highlighter, not a bespoke tag.

    Please leave a reaction 👍/👎 to this suggestion to improve future reviews for everyone!

@aigerimu aigerimu marked this pull request as ready for review April 28, 2026 05:57
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/security.mdx: please apply the inline suggestion to keep the example wording neutral and consistent with the docs style.

Comment thread contract-dev/techniques/security.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: 4

♻️ Duplicate comments (1)
contract-dev/techniques/security.mdx (1)

544-552: ⚠️ Potential issue | 🟠 Major

This section is not fully ported to Tolk yet.

The vulnerable snippet still uses a func fence (Line 546) while the paired secure snippet is tolk. For this PR’s objective (“port code samples to Tolk”), this section should be fully converted for consistency.

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

In `@contract-dev/techniques/security.mdx` around lines 544 - 552, The vulnerable
snippet uses a `func` code fence while the paired secure snippet is `tolk`, so
update the vulnerable example to use a `tolk` fence and ensure both examples are
fully ported to Tolk; locate the snippet containing `infoDict.delete(index);`
and replace the surrounding fence language from `func` to `tolk`, then verify
the secure implementation block is also a complete Tolk block (matching fence
type and content) so the section is fully converted and consistent.
🤖 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/security.mdx`:
- Around line 340-342: The Vote struct's votes field is declared as a signed int
(Vote.votes : int32) but Storage.votes is unsigned (Storage.votes : uint32),
causing a signed/unsigned mismatch at the addition site (storage.votes +=
msg.votes); change Vote.votes to uint32 to match Storage.votes and ensure the
addition uses the same unsigned type throughout (update the Vote struct
declaration and any references to Vote.votes accordingly).
- Around line 95-103: The Tolk external-message handlers (function
onExternalMessage and similar examples) call the wrong API: replace the call to
acceptMessage() with the documented acceptExternalMessage() to correctly accept
incoming external messages; update each usage in the Tolk code blocks that
currently call acceptMessage() so they call acceptExternalMessage() instead
(e.g., inside onExternalMessage and the two other external-message examples).
- Around line 270-277: The example uses msg.send(128) which is
SendRemainingBalance and will drain the contract; update the example to use a
non-draining send mode (e.g., msg.send(0) for a regular send or msg.send(3) to
forward fees) or explicitly document why draining is intended; locate the
createMessage call and the msg.send(128) invocation (and note the presence of
seqno replay protection) and replace the 128 mode or add a clear comment
explaining the deliberate use of SendRemainingBalance.
- Around line 64-71: The secure-example snippets use the outdated Tolk signature
onInternalMessage(msgValue: int, inMsgFull: cell, inMsgBody: slice) and the bare
sender variable; update both occurrences (the snippets handling empty message
and the later similar block) to the modern entrypoint signature fun
onInternalMessage(in: InMessage) and replace any use of sender with
in.senderAddress; adjust any references to message parts to use fields on the
InMessage (e.g., in.body or in.raw) so sendRawMessage is called with the correct
in-derived values and types (keep the same destruction logic but sourced from
in).

---

Duplicate comments:
In `@contract-dev/techniques/security.mdx`:
- Around line 544-552: The vulnerable snippet uses a `func` code fence while the
paired secure snippet is `tolk`, so update the vulnerable example to use a
`tolk` fence and ensure both examples are fully ported to Tolk; locate the
snippet containing `infoDict.delete(index);` and replace the surrounding fence
language from `func` to `tolk`, then verify the secure implementation block is
also a complete Tolk block (matching fence type and content) so the section is
fully converted and consistent.
🪄 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: ca165394-0a02-4b9f-90ad-50f083258940

📥 Commits

Reviewing files that changed from the base of the PR and between 8d4f473 and 47416ab.

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

Comment thread contract-dev/techniques/security.mdx Outdated
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx
Comment thread contract-dev/techniques/security.mdx Outdated
Comment thread contract-dev/techniques/security.mdx Outdated
Comment thread contract-dev/techniques/security.mdx Outdated
Comment thread contract-dev/techniques/security.mdx Outdated
Comment thread contract-dev/techniques/security.mdx Outdated
Comment thread contract-dev/techniques/security.mdx Outdated
@aigerimu aigerimu marked this pull request as draft April 29, 2026 07:46
@aigerimu aigerimu marked this pull request as ready for review April 30, 2026 16:32
@aigerimu aigerimu requested review from Kaladin13 and Shvandre April 30, 2026 16:33
Comment on lines +470 to +474
TakeMoney => {
assert (in.senderAddress == storage.oneContractAddress)
throw ErrCode.InvalidMoneyProvider;
// ...further processing...
}
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.

[HIGH] Commented TODO-style ellipsis in Tolk example

The Tolk example for AnotherContract includes a placeholder comment // ...further processing... inside a runnable snippet. The documentation style guide requires using language-appropriate comments for omissions and explicitly forbids literal ellipses used as pseudo-code placeholders in examples, especially when they could be mistaken for syntax. Keeping this placeholder as-is violates the style rules for documentation snippets and may confuse readers about whether the code is complete or executable. The surrounding example is otherwise realistic and should either show minimal real logic or use a neutral, non-elliptic comment to indicate omitted details (see https://github.com/ton-org/docs/blob/main/contribute/style-guide-extended.mdx?plain=1#L640-L652 for the underlying rule).

Suggested change
TakeMoney => {
assert (in.senderAddress == storage.oneContractAddress)
throw ErrCode.InvalidMoneyProvider;
// ...further processing...
}
TakeMoney => {
assert (in.senderAddress == storage.oneContractAddress)
throw ErrCode.InvalidMoneyProvider;
// Add application-specific processing here.
}

Please leave a reaction 👍/👎 to this suggestion to improve future reviews for everyone!

@github-actions
Copy link
Copy Markdown
Contributor

Thanks for the updates in contract-dev/techniques/security.mdx: please apply the couple of inline suggestions to tighten the security wording and clean up the example snippet.


Per-comment submission: 1 posted, 1 failed.

Unposted inline comments (raw text):

  • contract-dev/techniques/security.mdx:L181-L183

    [HIGH] Vague phrase “not entirely foolproof” in security guidance

    The guidance on using built-in random functions ends with the phrase “it is still not entirely foolproof,” which is vague and emotionally toned rather than technically precise. This conflicts with the style guidance against dramatic or marketing-style intensifiers and does not clearly describe what risks remain. Replacing this phrase with a concrete statement about residual risk and limitations of on-chain randomness improves clarity and keeps the focus on actionable security considerations. The surrounding context about secure random numbers supports rephrasing without changing the underlying recommendation.

    ```  …(truncated)
    

var fromVotes = getVotingPower(votes, from);
var toVotes = getVotingPower(votes, to);

assert (fromVotes >= amount) throw 998; // Validate sufficient balance
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.

This secure version still accepts a negative amount. For example, amount = -10 passes fromVotes >= amount, then increases fromVotes and decreases toVotes, which is exactly the signed-value class of bug this section warns about. Please either make amount an unsigned type or add an explicit amount >= 0 check before the balance check.

;; ...
```tolk
fun onExternalMessage(inMsg: slice) {
acceptMessage();
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.

acceptMessage() is not the Tolk API used by the standard library docs for accepting external messages; the documented function is acceptExternalMessage()

this appears again in the secure example below at line 142, so both examples should use acceptExternalMessage() to stay copy-pasteable and consistent with the earlier replay-protection snippet

assert (authorizedAdmin(sender)) throw ErrCode.Unauthorized;
assert (validateCode(newCode)) throw ErrCode.InvalidCode;

contract.setCode(newCode);
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.

Tolk exposes contract.setCodePostponed(newCodeCell), not contract.setCode(newCode). as written, the final secure implementation points readers to a non-existent API; please use contract.setCodePostponed(newCode) here, matching the Tolk standard-library docs and the upgrade guide

https://docs.ton.org/tolk/features/standard-library#contract-setcodepostponed-newcodecell

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 > Security best practices] Translate code examples to Tolk

3 participants