Generated banner for Ton Vulnerability Scanner
Generated logo for Ton Vulnerability Scanner

Ton Vulnerability Scanner

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Review and audit
  • Security
  • CC-BY-SA-4.0
  • No issues found

From the author

Scans TON (The Open Network) smart contracts for 3 critical vulnerabilities including integer-as-boolean misuse, fake Jetton contracts, and forward TON without gas checks. Use when auditing FunC contracts.
— the description by Trail of Bits

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The TON Vulnerability Scanner is a specialized tool designed to assist developers and auditors in identifying three critical security flaws common in FunC smart contracts. It provides a systematic approach to reviewing boolean logic, Jetton token transfer handlers, and gas management, ensuring that contracts are robust before deployment. The skill emphasizes transparency by requiring a standardized coverage table for every audit, ensuring that all three specific vulnerability patterns are explicitly addressed.

What it does

  • Scans FunC source code for integer-as-boolean logic errors.
  • Identifies missing sender validation in Jetton transfer notification handlers.
  • Detects insecure gas forwarding patterns that could lead to contract drainage.
  • Generates a structured coverage report with verdicts for all three vulnerability patterns.
  • Provides actionable code fixes and remediation strategies for identified issues.
  • Offers guidance on writing unit and integration tests to verify security patches.

When to use it

  • During the pre-launch security assessment of TON dApps.
  • When auditing FunC smart contracts for production readiness.
  • While reviewing Jetton token implementations and transfer notification logic.
  • When validating gas forwarding and boolean condition handling in existing contracts.

Advantages

  • Focuses on high-impact, platform-specific vulnerabilities unique to TON.
  • Enforces a rigorous, auditable reporting format for every scan.
  • Reduces the risk of common exploits like unauthorized token minting.
  • Provides clear, actionable remediation steps for developers.

Usage examples

“Audit my FunC contract in the contracts/ directory for security vulnerabilities.”
The agent scans the files, checks for the three defined patterns, and returns a coverage table with findings and recommended code fixes.
“Check my Jetton staking contract for potential fake transfer notification attacks.”
The agent specifically analyzes the transfer_notification handler and reports whether sender validation is correctly implemented.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/trailofbits/ton-vulnerability-scanner/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip ton-vulnerability-scanner.zip -d .agents/skills

Documentation by Trail of Bits

TON Vulnerability Scanner

1. Purpose

Systematically scan TON blockchain smart contracts written in FunC for platform-specific security vulnerabilities related to boolean logic, Jetton token handling, and gas management. This skill encodes 3 critical vulnerability patterns unique to TON's architecture.

2. When to Use This Skill

  • Auditing TON smart contracts (FunC language)

  • Reviewing Jetton token implementations

  • Validating token transfer notification handlers

  • Pre-launch security assessment of TON dApps

  • Reviewing gas forwarding logic

  • Assessing boolean condition handling

3. Platform Detection

File Extensions & Indicators
  • FunC files: .fc, .func

Language/Framework Markers
;; FunC contract indicators
#include "imports/stdlib.fc";

() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    ;; Contract logic
}

() recv_external(slice in_msg) impure {
    ;; External message handler
}

;; Common patterns
send_raw_message()
load_uint(), load_msg_addr(), load_coins()
begin_cell(), end_cell(), store_*()
transfer_notification operation
op::transfer, op::transfer_notification
.store_uint().store_slice().store_coins()
Project Structure
  • contracts/*.fc - FunC contract source

  • wrappers/*.ts - TypeScript wrappers

  • tests/*.spec.ts - Contract tests

  • ton.config.ts or wasm.config.ts - TON project config

Tool Support
  • TON Blueprint: Development framework for TON

  • toncli: CLI tool for TON contracts

  • ton-compiler: FunC compiler

  • Manual review primarily (limited automated tools)


4. How This Skill Works

When invoked, I will:

  1. Search your codebase for FunC/Tact contracts

  2. Analyze each contract for the 3 vulnerability patterns

  3. Report findings with file references and severity, above them a coverage table carrying a verdict for every pattern

  4. Provide fixes for each identified issue

  5. Emit the coverage table — all 3 patterns, each with a verdict


5. Example Output

When vulnerabilities are found, you'll get a report like this:

=== TON VULNERABILITY SCAN RESULTS ===

Project: my-ton-contract
Files Scanned: 3 (.fc, .tact)
Vulnerabilities Found: 2

Coverage: 3/3 patterns reported
 1 Integer as Boolean .............. found   contracts/wallet.fc:45
 2 Fake Jetton Contract ............ found   contracts/staking.fc:85
 3 Forward TON Without Gas Check ... clear   forward amounts fixed at 0.05 TON

---

[CRITICAL] Fake Jetton Contract - Missing Sender Validation
File: contracts/staking.fc:85
Pattern: transfer_notification sender not checked against the stored Jetton wallet

6. Vulnerability Patterns (3 Patterns)

I check for 3 critical vulnerability patterns unique to TON. For detailed detection patterns, code examples, mitigations, and testing strategies, see VULNERABILITY_PATTERNS.md.

Pattern Summary:
  1. Integer as Boolean ⚠️ HIGH - Positive integers used as true; FunC's true is -1

  2. Fake Jetton Contract ⚠️ CRITICAL - transfer_notification sender not validated

  3. Forward TON Without Gas Check ⚠️ HIGH - Forwarding without reserving gas for the rest of execution

For complete vulnerability patterns with code examples, see VULNERABILITY_PATTERNS.md.

7. Scanning Workflow

Step 1: Platform Identification
  1. Verify FunC language (.fc or .func files)

  2. Check for TON Blueprint or toncli project structure

  3. Locate contract source files

  4. Identify Jetton-related contracts

Step 2: Boolean Logic Review
# Find boolean-like variables
rg "int.*is_|int.*has_|int.*flag|int.*enabled" contracts/

# Check for positive integers used as booleans
rg "= 1;|return 1;" contracts/ | grep -E "is_|has_|flag|enabled|valid"

# Look for NOT operations on boolean-like values
rg "~.*\(|~ " contracts/

For each boolean:

  • [ ] Uses -1 for true, 0 for false

  • [ ] NOT using 1 or other positive integers

  • [ ] Logic operations work correctly

Step 3: Jetton Handler Analysis
# Find transfer_notification handlers
rg "transfer_notification|op::transfer_notification" contracts/

For each Jetton handler:

  • [ ] Validates sender address

  • [ ] Sender checked against stored Jetton wallet address

  • [ ] Cannot trust forward_payload without sender validation

  • [ ] Has admin function to set Jetton wallet address

Step 4: Gas/Forward Amount Review
# Find forward amount usage
rg "forward_ton_amount|forward_amount" contracts/
rg "load_coins\(\)" contracts/

# Find send_raw_message calls
rg "send_raw_message" contracts/

For each outgoing message:

  • [ ] Forward amounts are fixed/bounded

  • [ ] OR user-provided amounts validated against msg_value

  • [ ] Cannot drain contract balance

  • [ ] Appropriate send_raw_message flags used

Step 5: Manual Review

TON contracts require thorough manual review:

  • Boolean logic with ~, &, | operators

  • Message parsing and validation

  • Gas economics and fee calculations

  • Storage operations and data serialization


8. Reporting Format

Coverage Table

Report on every pattern in §6, whether or not it turned anything up. Emit this table above the findings, with all 3 rows present:

#PatternVerdictEvidence
1Integer as Booleanclearsearched is_/has_/flag; all set to -1
2Fake Jetton Contract
3Forward TON Without Gas Check

Each verdict is one of:

  • found — cite file:line and write the finding up in full below.

  • clear — the pattern applies to this contract and the contract handles it. Name the function, stored address, or check you searched for, so a reader can repeat the search.

  • n/a — the pattern cannot apply here. Give the reason in one clause ("this contract handles no Jetton transfer notifications"). Not having looked is not n/a.

Three patterns is a short list, which makes an incomplete table harder to excuse rather than easier: a report covering one pattern and silent on the other two reads exactly like a clean contract. Emit all three rows even when all three are clear. A row whose Verdict cell is empty is incomplete in the same way: row 1 above is filled in to show the shape, and every row is filled in the same way before the report is done.

Finding Template
## [CRITICAL] Fake Jetton Contract - Missing Sender Validation

**Location**: `contracts/staking.fc:85-95` (recv_internal, transfer_notification handler)

**Description**:
The `transfer_notification` operation handler does not validate that the sender is the expected Jetton wallet contract. Any attacker can send a fake `transfer_notification` message claiming to have transferred tokens, crediting themselves without actually depositing any Jettons.

**Vulnerable Code**:
```func
// staking.fc, line 85
if (op == op::transfer_notification) {
    int jetton_amount = in_msg_body~load_coins();
    slice from_user = in_msg_body~load_msg_addr();

    ;; WRONG: No validation of sender_address!
    ;; Attacker can claim any jetton_amount

    credit_user(from_user, jetton_amount);
}
```

**Attack Scenario**:
1. Attacker deploys malicious contract
2. Malicious contract sends `transfer_notification` message to staking contract
3. Message claims attacker transferred 1,000,000 Jettons
4. Staking contract credits attacker without checking sender
5. Attacker can now withdraw from contract or gain benefits without depositing

**Proof of Concept**:
```typescript
// Attacker sends fake transfer_notification
const attackerContract = await blockchain.treasury("attacker");

await stakingContract.sendInternalMessage(attackerContract.getSender(), {
  op: OP_CODES.TRANSFER_NOTIFICATION,
  jettonAmount: toNano("1000000"), // Fake amount
  fromUser: attackerContract.address,
});

// Attacker successfully credited without sending real Jettons
const balance = await stakingContract.getUserBalance(attackerContract.address);
expect(balance).toEqual(toNano("1000000")); // Attack succeeded
```

**Recommendation**:
Store expected Jetton wallet address and validate sender:
```func
global slice jetton_wallet_address;

() recv_internal(...) impure {
    load_data();  ;; Load jetton_wallet_address from storage

    slice cs = in_msg_full.begin_parse();
    int flags = cs~load_uint(4);
    slice sender_address = cs~load_msg_addr();

    int op = in_msg_body~load_uint(32);

    if (op == op::transfer_notification) {
        ;; CRITICAL: Validate sender
        throw_unless(error::wrong_jetton_wallet,
            equal_slices(sender_address, jetton_wallet_address));

        int jetton_amount = in_msg_body~load_coins();
        slice from_user = in_msg_body~load_msg_addr();

        ;; Safe to credit user
        credit_user(from_user, jetton_amount);
    }
}
```

**References**:
- building-secure-contracts/not-so-smart-contracts/ton/fake_jetton_contract

9. Priority Guidelines

Critical (Immediate Fix Required)
  • Fake Jetton contract (unauthorized minting/crediting)

High (Fix Before Launch)
  • Integer as boolean (logic errors, broken conditions)

  • Forward TON without gas check (balance drainage)


10. Testing Recommendations

Unit Tests
import { Blockchain } from "@ton/sandbox";
import { toNano } from "ton-core";

describe("Security tests", () => {
  let blockchain: Blockchain;
  let contract: Contract;

  beforeEach(async () => {
    blockchain = await Blockchain.create();
    contract = blockchain.openContract(await Contract.fromInit());
  });

  it("should use correct boolean values", async () => {
    // Test that TRUE = -1, FALSE = 0
    const result = await contract.getFlag();
    expect(result).toEqual(-1n); // True
    expect(result).not.toEqual(1n); // Not 1!
  });

  it("should reject fake jetton transfer", async () => {
    const attacker = await blockchain.treasury("attacker");

    const result = await contract.send(
      attacker.getSender(),
      { value: toNano("0.05") },
      {
        $$type: "TransferNotification",
        query_id: 0n,
        amount: toNano("1000"),
        from: attacker.address,
      }
    );

    expect(result.transactions).toHaveTransaction({
      success: false, // Should reject
    });
  });

  it("should validate gas for forward amount", async () => {
    const result = await contract.send(
      user.getSender(),
      { value: toNano("0.01") }, // Insufficient gas
      {
        $$type: "Transfer",
        to: recipient.address,
        forward_ton_amount: toNano("1"), // Trying to forward 1 TON
      }
    );

    expect(result.transactions).toHaveTransaction({
      success: false,
    });
  });
});
Integration Tests
// Test with real Jetton wallet
it("should accept transfer from real jetton wallet", async () => {
  // Deploy actual Jetton minter and wallet
  const jettonMinter = await blockchain.openContract(JettonMinter.create());
  const userJettonWallet = await jettonMinter.getWalletAddress(user.address);

  // Set jetton wallet in contract
  await contract.setJettonWallet(userJettonWallet);

  // Real transfer from Jetton wallet
  const result = await userJettonWallet.sendTransfer(
    user.getSender(),
    contract.address,
    toNano("100"),
    {}
  );

  expect(result.transactions).toHaveTransaction({
    to: contract.address,
    success: true,
  });
});

11. Additional Resources


12. Quick Reference Checklist

Before completing TON contract audit:

Boolean Logic (HIGH):

  • [ ] All boolean values use -1 (true) and 0 (false)

  • [ ] NO positive integers (1, 2, etc.) used as booleans

  • [ ] Functions returning booleans return -1 for true

  • [ ] Boolean logic with ~, &, | uses correct values

  • [ ] Tests verify boolean operations work correctly

Jetton Security (CRITICAL):

  • [ ] transfer_notification handler validates sender address

  • [ ] Sender checked against stored Jetton wallet address

  • [ ] Jetton wallet address stored during initialization

  • [ ] Admin function to set/update Jetton wallet

  • [ ] Cannot trust forward_payload without sender validation

  • [ ] Tests with fake Jetton contracts verify rejection

Gas & Forward Amounts (HIGH):

  • [ ] Forward TON amounts are fixed/bounded

  • [ ] OR user-provided amounts validated: msg_value >= tx_fee + forward_amount

  • [ ] Contract balance protected from drainage

  • [ ] Appropriate send_raw_message flags used

  • [ ] Tests verify cannot drain contract with excessive forward amounts

Testing:

  • [ ] Unit tests for all three vulnerability types

  • [ ] Integration tests with real Jetton contracts

  • [ ] Gas cost analysis for all operations

  • [ ] Testnet deployment before mainnet

  • [ ] Coverage table emitted with all 3 rows, each carrying a verdict of found, clear or n/a with a reason


13. Rationalizations to Reject

  • "The contract is small, so most patterns obviously don't apply." Obvious to whom? An n/a costs one clause and makes the judgment reviewable. Silence records nothing, and a reader cannot tell it apart from not having checked. With only three patterns, there is no version of this scan too large to complete.

  • "There is no automated tooling for FunC, so coverage can't be systematic." The absence of a scanner is the reason the table matters, not an excuse for skipping it. Manual review is the method here; the table is what makes it auditable.

  • "I checked the patterns that matter for this contract." Deciding which patterns matter is the scan, not a precondition for starting it. Rank by severity after the table is complete, not by leaving rows out.

  • "No findings, so there is nothing to report." A zero-finding scan still emits the full coverage table. That table is the deliverable: it is what distinguishes a contract that was examined from one that was glanced at.

  • "The sender is obviously the Jetton wallet." Then cite the stored address it is compared against. Any contract can send a transfer notification; the check is a comparison against an address the contract itself computed, and its absence is the fake-Jetton bug.

  • "The message is non-bounceable, so gas doesn't matter." Name the reserve. Forwarding without leaving enough for the remaining execution strands the contract mid-operation regardless of bounce behavior.

Files

resources/VULNERABILITY_PATTERNS.md

6. Vulnerability Checklist (3 Patterns)

6.1 INTEGER AS BOOLEAN ⚠️ HIGH

Description: FunC uses integers for boolean values (0 = false, -1 = true). The bitwise NOT operator ~ on non-standard boolean values (positive integers) produces unexpected results, causing logic errors.

Background:

  • FunC true = -1 (all bits set: 0xFFFFFFFF...)

  • FunC false = 0 (all bits clear: 0x00000000...)

  • ~ is bitwise NOT: ~0 = -1, ~(-1) = 0

  • But ~1 = -2 (not 0!), ~2 = -3 (not 0!)

Detection Patterns:

;; VULNERABLE: Using positive integers as booleans
int is_active = 1;  ;; WRONG: Should be -1 for true, 0 for false

if (is_active) {
    ;; This works - 1 is truthy
}

if (~ is_active) {
    ;; PROBLEM: ~1 = -2, which is still truthy!
    ;; This branch will ALWAYS execute, not just when is_active is false
}

;; VULNERABLE: Returning positive integers as booleans
int is_valid(int value) {
    if (value > 100) {
        return 1;  ;; WRONG: Should return -1
    }
    return 0;  ;; Correct for false
}

int valid = is_valid(150);  ;; Returns 1
if (~ valid) {
    ;; PROBLEM: ~1 = -2 (truthy), this executes when it shouldn't!
}

;; VULNERABLE: Boolean arithmetic
int flag1 = 1;  ;; Wrong true value
int flag2 = 1;  ;; Wrong true value
int both_true = flag1 & flag2;  ;; 1 & 1 = 1 (works)
int neither_true = (~ flag1) & (~ flag2);  ;; ~1 & ~1 = -2 & -2 = -2 (WRONG!)
;; Expected 0 (false), got -2 (truthy)

What to Check:

  • [ ] All boolean values use 0 (false) or -1 (true)

  • [ ] NO positive integers (1, 2, etc.) used as booleans

  • [ ] Functions returning booleans return -1 (not 1) for true

  • [ ] Boolean logic with ~, &, | uses correct values

  • [ ] Conditions test against 0 explicitly where needed

Mitigation:

;; SECURE: Use correct boolean values
const int TRUE = -1;   ;; All bits set
const int FALSE = 0;   ;; All bits clear

int is_active = TRUE;  ;; Correct

if (is_active) {
    ;; Works correctly
}

if (~ is_active) {
    ;; Works correctly: ~(-1) = 0 (falsy)
}

;; SECURE: Return correct boolean values
int is_valid(int value) method_id {
    if (value > 100) {
        return TRUE;   ;; -1 for true
    }
    return FALSE;      ;; 0 for false
}

int valid = is_valid(150);
if (~ valid) {
    ;; Correct: ~(-1) = 0 (falsy), this doesn't execute
}

;; SECURE: Boolean operations with correct values
int flag1 = TRUE;   ;; -1
int flag2 = TRUE;   ;; -1
int both_true = flag1 & flag2;         ;; -1 & -1 = -1 (TRUE)
int neither_true = (~ flag1) & (~ flag2);  ;; 0 & 0 = 0 (FALSE)

;; SECURE: Explicit comparisons when needed
int status_code = get_status();  ;; Returns 0, 1, 2, etc.

;; Instead of treating as boolean:
if (status_code) { }  ;; Ambiguous!

;; Explicitly compare:
if (status_code != 0) { }  ;; Clear intent
if (status_code == 1) { }  ;; Even better

Common Mistake Patterns:

;; MISTAKE 1: Loading boolean from storage/message
slice cs = get_data().begin_parse();
int flag = cs~load_uint(1);  ;; Returns 0 or 1, not 0 or -1!

;; FIX: Convert to proper boolean
int flag_bool = flag ? TRUE : FALSE;

;; MISTAKE 2: Comparing with 1 instead of TRUE
int is_owner = sender == owner_address;  ;; Returns 0 or -1 (correct)

if (is_owner == 1) {  ;; WRONG: will never match
    ;; This never executes!
}

;; FIX: Compare with TRUE or just use directly
if (is_owner == TRUE) { }  ;; Correct
if (is_owner) { }          ;; Also correct

;; MISTAKE 3: Returning count as boolean
int count_items() {
    return items.length;  ;; Returns 0, 1, 2, 3... (not boolean!)
}

int has_items = count_items();
if (~ has_items) {
    ;; WRONG: ~1 = -2 (truthy), ~2 = -3 (truthy), etc.
}

;; FIX: Return proper boolean or use explicit comparison
int has_items() {
    return items.length > 0 ? TRUE : FALSE;
}
;; OR
int count = count_items();
if (count == 0) { }  ;; Explicit comparison

Testing:

;; Test boolean logic
int test_boolean_logic() {
    int t = TRUE;
    int f = FALSE;

    ;; Basic logic
    throw_unless(100, t == -1);
    throw_unless(101, f == 0);

    ;; Negation
    throw_unless(102, ~t == f);
    throw_unless(103, ~f == t);

    ;; AND logic
    throw_unless(104, t & t == t);
    throw_unless(105, t & f == f);
    throw_unless(106, f & f == f);

    ;; OR logic
    throw_unless(107, t | t == t);
    throw_unless(108, t | f == t);
    throw_unless(109, f | f == f);

    return TRUE;
}

References: building-secure-contracts/not-so-smart-contracts/ton/integer_as_boolean


4.2 FAKE JETTON CONTRACT ⚠️ CRITICAL

Description: The transfer_notification operation can be sent by any contract. Without sender validation, attackers can send fake transfer notifications claiming to have transferred tokens that were never sent.

Background:

  • Jetton (TON's token standard) uses transfer_notification to notify recipients

  • Real flow: User → Jetton Wallet → Receiver (with notification)

  • Attack: Attacker → Receiver (fake notification, no Jetton Wallet involved)

Detection Patterns:

;; VULNERABLE: No sender validation in transfer_notification
() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    slice cs = in_msg_full.begin_parse();
    int flags = cs~load_uint(4);
    slice sender_address = cs~load_msg_addr();

    int op = in_msg_body~load_uint(32);

    if (op == op::transfer_notification) {
        ;; WRONG: No validation of sender_address!
        int jetton_amount = in_msg_body~load_coins();
        slice from_user = in_msg_body~load_msg_addr();
        slice forward_payload = in_msg_body;

        ;; Process as if jettons were received
        ;; Attacker can claim any jetton_amount without actually sending tokens!
        credit_user(from_user, jetton_amount);
    }
}

;; VULNERABLE: Validating user address but not Jetton wallet
if (op == op::transfer_notification) {
    int jetton_amount = in_msg_body~load_coins();
    slice from_user = in_msg_body~load_msg_addr();

    ;; Validates from_user but not sender!
    throw_unless(error::unauthorized, equal_slices(from_user, authorized_user));

    ;; WRONG: Anyone can send this message claiming to be from authorized_user
    credit_user(from_user, jetton_amount);
}

;; VULNERABLE: Trusting forward_payload data
if (op == op::transfer_notification) {
    int jetton_amount = in_msg_body~load_coins();
    slice from_user = in_msg_body~load_msg_addr();
    slice forward_payload = in_msg_body;

    ;; Parse data from forward_payload
    int token_id = forward_payload~load_uint(32);

    ;; WRONG: Attacker controls all this data!
    ;; Can claim any token_id, any jetton_amount
}

What to Check:

  • [ ] transfer_notification handler validates sender address

  • [ ] Sender must be expected Jetton wallet address

  • [ ] Jetton wallet addresses stored during initialization

  • [ ] Cannot trust forward_payload without sender validation

  • [ ] User address in notification is NOT sufficient validation

Mitigation:

;; SECURE: Store expected Jetton wallet address at initialization
global slice jetton_wallet_address;

() load_data() impure {
    slice ds = get_data().begin_parse();
    jetton_wallet_address = ds~load_msg_addr();
    ;; Load other data
}

() save_data() impure {
    set_data(begin_cell()
        .store_slice(jetton_wallet_address)
        ;; Store other data
        .end_cell());
}

;; Initialize with Jetton wallet address
() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    load_data();

    slice cs = in_msg_full.begin_parse();
    int flags = cs~load_uint(4);
    slice sender_address = cs~load_msg_addr();

    int op = in_msg_body~load_uint(32);

    if (op == op::transfer_notification) {
        ;; CRITICAL: Validate sender is expected Jetton wallet
        throw_unless(error::wrong_jetton_wallet,
            equal_slices(sender_address, jetton_wallet_address));

        ;; Now safe to trust the notification
        int jetton_amount = in_msg_body~load_coins();
        slice from_user = in_msg_body~load_msg_addr();
        slice forward_payload = in_msg_body;

        ;; Can safely credit user
        credit_user(from_user, jetton_amount);

        ;; Can safely parse forward_payload
        if (~ forward_payload.slice_empty?()) {
            int token_id = forward_payload~load_uint(32);
            ;; Use token_id
        }
    }
}

;; SECURE: Multiple Jetton support with dictionary
global cell jetton_wallets;  ;; Dictionary: jetton_type -> wallet_address

() load_data() impure {
    slice ds = get_data().begin_parse();
    jetton_wallets = ds~load_dict();
}

() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    load_data();

    slice cs = in_msg_full.begin_parse();
    int flags = cs~load_uint(4);
    slice sender_address = cs~load_msg_addr();

    int op = in_msg_body~load_uint(32);

    if (op == op::transfer_notification) {
        int jetton_amount = in_msg_body~load_coins();
        slice from_user = in_msg_body~load_msg_addr();
        slice forward_payload = in_msg_body;

        ;; Parse jetton type from forward_payload
        int jetton_type = forward_payload~load_uint(8);

        ;; Look up expected wallet address for this jetton type
        (slice expected_wallet, int found) = jetton_wallets.udict_get?(256, jetton_type);

        ;; Validate sender matches expected wallet
        throw_unless(error::unauthorized_jetton,
            found & equal_slices(sender_address, expected_wallet));

        ;; Safe to process
        credit_user_jetton(from_user, jetton_type, jetton_amount);
    }
}

Admin Function to Set Jetton Wallet:

;; Only owner can set/update Jetton wallet address
if (op == op::set_jetton_wallet) {
    throw_unless(error::unauthorized, equal_slices(sender_address, owner_address));

    slice new_jetton_wallet = in_msg_body~load_msg_addr();
    jetton_wallet_address = new_jetton_wallet;

    save_data();
    return ();
}

Testing:

// Test fake transfer notification is rejected
it("should reject fake transfer notification", async () => {
  const attacker = await blockchain.treasury("attacker");

  // Attacker sends fake transfer_notification directly
  const result = await contract.sendInternalMessage(attacker.getSender(), {
    op: OP_CODES.TRANSFER_NOTIFICATION,
    jettonAmount: toNano("1000"),
    fromUser: user.address,
  });

  expect(result.transactions).toHaveTransaction({
    from: attacker.address,
    to: contract.address,
    success: false, // Should be rejected
    exitCode: ERROR_CODES.WRONG_JETTON_WALLET,
  });
});

// Test real Jetton wallet notification is accepted
it("should accept real jetton transfer", async () => {
  // Send from actual Jetton wallet
  const result = await contract.sendInternalMessage(jettonWallet.address, {
    op: OP_CODES.TRANSFER_NOTIFICATION,
    jettonAmount: toNano("100"),
    fromUser: user.address,
  });

  expect(result.transactions).toHaveTransaction({
    from: jettonWallet.address,
    to: contract.address,
    success: true,
  });
});

References: building-secure-contracts/not-so-smart-contracts/ton/fake_jetton_contract


4.3 FORWARD TON WITHOUT GAS CHECK ⚠️ HIGH

Description: Allowing users to specify forward_ton_amount in outgoing messages without validating sufficient gas can drain the contract's TON balance. User pays small gas but specifies large forward amount from contract balance.

Detection Patterns:

;; VULNERABLE: User-specified forward_ton_amount without validation
() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    int op = in_msg_body~load_uint(32);

    if (op == op::transfer) {
        slice to_address = in_msg_body~load_msg_addr();
        int amount = in_msg_body~load_coins();
        int forward_ton_amount = in_msg_body~load_coins();  ;; USER CONTROLLED!

        ;; WRONG: No check that msg_value covers forward_ton_amount
        ;; Contract pays from its own balance!

        var msg = begin_cell()
            .store_uint(0x18, 6)
            .store_slice(to_address)
            .store_coins(forward_ton_amount)  ;; Drains contract balance!
            .store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
            .end_cell();

        send_raw_message(msg, 1);
    }
}

;; VULNERABLE: No gas validation for operations
() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    int op = in_msg_body~load_uint(32);

    if (op == op::claim_reward) {
        slice user = in_msg_body~load_msg_addr();
        int forward_amount = in_msg_body~load_coins();

        ;; Calculate reward
        int reward = calculate_reward(user);

        ;; WRONG: Sends user-specified forward_amount
        ;; No validation that msg_value >= tx_fee + forward_amount
        var msg = begin_cell()
            .store_uint(0x18, 6)
            .store_slice(user)
            .store_coins(forward_amount + reward)
            .store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
            .end_cell();

        send_raw_message(msg, 1);  ;; Contract pays gas!
    }
}

What to Check:

  • [ ] User cannot specify arbitrary forward TON amounts

  • [ ] IF forward amount is user-specified: validate msg_value >= tx_fee + forward_ton_amount

  • [ ] Prefer fixed/bounded forward amounts

  • [ ] Contract balance protected from drainage

  • [ ] Gas costs accounted for in all operations

Mitigation:

;; SECURE: Fixed forward amounts (PREFERRED)
const int FORWARD_TON_AMOUNT = 50000000;  ;; 0.05 TON (fixed)
const int TX_FEE = 10000000;  ;; 0.01 TON estimated fee

() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    int op = in_msg_body~load_uint(32);

    if (op == op::transfer) {
        slice to_address = in_msg_body~load_msg_addr();
        int amount = in_msg_body~load_coins();

        ;; Use fixed forward amount
        ;; No user control, no drainage risk

        var msg = begin_cell()
            .store_uint(0x18, 6)
            .store_slice(to_address)
            .store_coins(FORWARD_TON_AMOUNT)  ;; Fixed amount
            .store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
            ;; Store message body
            .end_cell();

        send_raw_message(msg, 1);
    }
}

;; SECURE: Validate msg_value covers all costs (if user-specified)
() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    int op = in_msg_body~load_uint(32);

    if (op == op::transfer_with_forward) {
        slice to_address = in_msg_body~load_msg_addr();
        int amount = in_msg_body~load_coins();
        int forward_ton_amount = in_msg_body~load_coins();

        ;; CRITICAL: Validate msg_value covers tx fee + forward amount
        throw_unless(error::insufficient_gas,
            msg_value >= TX_FEE + forward_ton_amount);

        var msg = begin_cell()
            .store_uint(0x18, 6)
            .store_slice(to_address)
            .store_coins(forward_ton_amount)
            .store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
            .end_cell();

        ;; Safe: user provided sufficient gas
        send_raw_message(msg, 1);
    }
}

;; SECURE: Bounded forward amounts
const int MAX_FORWARD_TON = 100000000;  ;; 0.1 TON maximum

() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    int op = in_msg_body~load_uint(32);

    if (op == op::claim_with_notification) {
        slice user = in_msg_body~load_msg_addr();
        int forward_ton_amount = in_msg_body~load_coins();

        ;; Enforce maximum forward amount
        throw_unless(error::forward_amount_too_high,
            forward_ton_amount <= MAX_FORWARD_TON);

        ;; Validate msg_value covers costs
        throw_unless(error::insufficient_gas,
            msg_value >= TX_FEE + forward_ton_amount);

        ;; Calculate reward from contract logic
        int reward = calculate_reward(user);

        var msg = begin_cell()
            .store_uint(0x18, 6)
            .store_slice(user)
            .store_coins(reward)  ;; Reward from contract
            .store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
            ;; Message body
            .end_cell();

        ;; Send with user's gas
        send_raw_message(msg, 64);  ;; Flag 64: use all remaining gas from incoming message
    }
}

;; SECURE: Don't allow user to specify forward amount at all
() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
    int op = in_msg_body~load_uint(32);

    if (op == op::withdraw) {
        slice user = in_msg_body~load_msg_addr();

        ;; No forward_ton_amount parameter
        ;; Use contract's calculated amount only

        int withdrawal_amount = calculate_withdrawal(user);

        var msg = begin_cell()
            .store_uint(0x18, 6)
            .store_slice(user)
            .store_coins(withdrawal_amount)  ;; Contract controlled
            .store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
            .end_cell();

        send_raw_message(msg, 1);
    }
}

Send Message Flags Reference:

;; send_raw_message flag values:
;; 0   - Normal send, pay fees from message value
;; 1   - Pay fees separately from contract balance
;; 64  - Return remaining value from incoming message
;; 128 - Carry all remaining balance

;; Safe patterns:
send_raw_message(msg, 64);  ;; Use incoming msg_value for fees
send_raw_message(msg, 0);   ;; Fees from message value itself

;; Dangerous with user input:
send_raw_message(msg, 1);   ;; Fees from contract - validate msg_value!
send_raw_message(msg, 128); ;; Never use with user-controlled amounts!

Testing:

// Test cannot drain contract with large forward amount
it("should reject large forward amount without sufficient gas", async () => {
  const result = await contract.sendInternalMessage(user.getSender(), {
    value: toNano("0.01"), // Only 0.01 TON provided
    body: {
      op: OP_CODES.TRANSFER,
      toAddress: recipient.address,
      amount: toNano("100"),
      forwardTonAmount: toNano("10"), // Trying to forward 10 TON!
    },
  });

  expect(result.transactions).toHaveTransaction({
    success: false,
    exitCode: ERROR_CODES.INSUFFICIENT_GAS,
  });

  // Contract balance should not decrease
  expect(await contract.getBalance()).toEqual(initialBalance);
});

References: building-secure-contracts/not-so-smart-contracts/ton/forward_value_without_check


Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Trail of Bits
Publisher
Trail of Bits (Official)
Source
trailofbits/skills · plugins/building-secure-contracts/skills/ton-vulnerability-scanner · commit e4dd0bb
Licence
Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Trail of Bits.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download ton-vulnerability-scanner.zip