Skip to main content

Documentation Index

Fetch the complete documentation index at: https://companyname-a7d5b98e-security-edits.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

There are several anti-patterns and potential attack vectors that smart contract developers should be aware of. These can affect the security, efficiency, and correctness of the contracts. Below are some common pitfalls and best practices to avoid them.

Signed/unsigned integer vulnerabilities

Improper handling of signed integers can allow attackers to exploit overflow/underflow conditions.

Vulnerable code

fun transferVotingPower(mutate votes: cell, from: slice, to: slice, amount: int): void {
    var fromVotes = getVotingPower(votes, from);
    var toVotes = getVotingPower(votes, to);

    fromVotes -= amount;  // Can become negative
    toVotes += amount;

    votes.setVotingPower(from, fromVotes);
    votes.setVotingPower(to, toVotes);
}

Secure implementation

fun transferVotingPower(mutate votes: cell, from: slice, to: slice, amount: int): void {
    var fromVotes = getVotingPower(votes, from);
    var toVotes = getVotingPower(votes, to);

    assert (fromVotes >= amount) throw 998;  // Validate sufficient balance

    fromVotes -= amount;
    toVotes += amount;

    votes.setVotingPower(from, fromVotes);
    votes.setVotingPower(to, toVotes);
}

Sending sensitive data on-chain

The entire smart contract computation is transparent; confidential runtime values can be retrieved through emulation.

Vulnerable code

// DON'T: Store password hash or private data
val privateData = beginCell()
    .storeSlice("secret_password_hash")
    .storeUint(userPrivateKey, 256)
    .endCell();

Account destruction race conditions

Destroying accounts using send mode 128 + 32 without proper checks can lead to fund loss in race conditions.

Vulnerable code

fun onInternalMessage(in: InMessage) {
    if (in.body.isEmpty()) {
        return;  // Dangerous: empty message handling
    }

    // Process and destroy account
    sendRawMessage(msg, 128 + 32);  // Destroys account
}

Secure approach

fun onInternalMessage(in: InMessage) {
    // Proper validation before any destruction
    assert (authorizedSender(in.senderAddress)) throw ErrCode.Unauthorized;

    // Ensure no pending operations
    assert (safeToDestroy()) throw ErrCode.PendingOperations;

    // Then proceed with destruction if really needed
}

Missing replay protection

Replay protection is a security mechanism that prevents an attacker from reusing a previous message. External messages without replay protection can be re-executed multiple times by an attacker which could lead to fund loss or other undesired behavior.

Secure implementation

fun onExternalMessage(mutate inMsg: slice) {
    var ds = contract.getData().beginParse();
    val storedSeqno = ds.loadUint(32);
    val msgSeqno = inMsg.loadUint(32);

    assert (msgSeqno == storedSeqno) throw 33;  // Prevent replay

    acceptExternalMessage();

    // Update sequence number
    contract.setData(
        beginCell()
            .storeUint(storedSeqno + 1, 32)
            .endCell()
    );
}

Unconditional accepting of external messages

Incoming external messages do not transfer funds. Receiving smart contract must pay for their processing from its balance. Upon receiving an external message, a smart contract can spend some free gas (gas_credit) in order to decide whether it is ready to accept it, and then pay for its further processing. External messages are usually accepted through the ACCEPT TVM instruction, which sets gas_limit to its maximum possible value specified in the network configuration, and sets gas_credit to zero. From this point on, the contract will have to pay for the entire processing of the incoming message. Therefore, if ACCEPT is not guarded by a condition, an attacker might repeatedly send messages, and spend the entire balance of the contract. The SETGASLIMIT instruction can lead to the same issue.

Vulnerable code

fun onExternalMessage(inMsg: slice) {
    acceptMessage();
    // ...
}

Secure implementation

Checks before accepting an external message vary by use case. The following example is a part of wallet v3 code, that doesn’t accept a message if it isn’t signed by the wallet’s owner.
fun onExternalMessage(inMsg: slice) {
    // parse message and contract storage (omitted)
    assert (msgSeqno == storedSeqno) throw 33;
    assert (subwalletId == storedSubwallet) throw 34;
    assert (checkSignature(inMsg.hash(), signature, publicKey)) throw 35;
    acceptMessage();
    // handle the message (omitted)
}

Invalid throw values

Exit codes 0 and 1 indicate normal execution of the compute phase of the transaction. Execution can be unexpectedly aborted by calling a throw directly with exit codes 0 and 1. This can make debugging very difficult since such aborted execution would be indistinguishable from a normal one.

Gas limitation

Be careful with the Out of gas error. It cannot be handled, so try to pre-calculate the gas consumption whenever possible. This will help avoid wasting extra gas, as the transaction will fail anyway.

Secure implementation

struct Vote {
    votes: int32
}

const voteGasUsage = 10000;  // precompute with tests

fun onInternalMessage(in: InMessage) {
    val msg = Vote.fromSlice(in.body);

    assert (
        in.valueCoins > getComputeFee(voteGasUsage, false)
    ) throw ErrCode.NotEnoughGas;  // Not enough gas!

    // ...subsequent logic...
}

Insecure random numbers

Generating truly secure random numbers in TON is challenging. The built-in random functions are pseudo-random and depend on logical time. An attacker can predict the randomized number by brute-forcing the logical time in the current block.

Secure approach

  • For critical applications, avoid relying solely on on-chain solutions.
  • Use built-in random functions with randomized logical time to enhance security by making predictions harder for attackers without access to a validator node. Note, however, that it is still not entirely foolproof.
  • Consider using the commit-and-disclose scheme:
  1. Participants generate random numbers off-chain and send their hashes to the contract.
  2. Once all hashes are received, participants disclose their original numbers.
  3. Combine the disclosed numbers (e.g., summing them) to produce a secure random value.
  • Don’t use randomization in external message receivers, as it remains vulnerable even with randomized logical time.

Executing third-party code

Executing untrusted code can compromise contract security.

Prevention

// Validate all external code before execution
assert (verifyCodeSignature(code)) throw ErrCode.UntrustedCode;
assert (validateCodeSafety(code)) throw ErrCode.InvalidCode;

Race condition of messages

A message cascade can be processed over many blocks. Assume that while one message flow is running, an attacker can initiate a second message flow in parallel. That is, if a property was checked at the beginning, such as whether the user has enough tokens, do not assume that it will still be satisfied at the third stage in the same contract.

Preventing front-running with signature verification

In TON blockchain, all pending messages are publicly visible in the mempool. Front-running can occur when an attacker observes a pending transaction containing a valid signature and quickly submits their own transaction using the same signature before the original transaction is processed.

Secure approach

Include critical parameters like the recipient address (to) within the data that is signed. This ensures that the signature is valid only for the intended operation and recipient, preventing attackers from reusing the signature for their benefit. Also, implement replay protection to prevent the same signed message from being used multiple times.
import "@stdlib/gas-payments"

struct RequestBody {
    to: address
    seqno: uint64
}

struct (0x988d4037) Request {
    signature: bytes64
    requestBody: RequestBody
}

enum ErrCode {
    InvalidSignature = 1000,
    InvalidSeqno = 1001,
}

struct Storage {
    publicKey: uint256
    seqno: uint64
}

fun Storage.load() {
    return Storage.fromCell(contract.getData())
}

fun Storage.save(self) {
    contract.setData(self.toCell())
}

fun onInternalMessage(in: InMessage) {
    // ignore internal messages
}

fun onExternalMessage(inMsg: slice) {
    val request = Request.fromSlice(inMsg);
    var storage = lazy Storage.load();

    assert (
        isSignatureValid(
            request.requestBody.toCell().hash(),
            request.signature as slice,
            storage.publicKey
        )
    ) throw ErrCode.InvalidSignature;

    assert (request.requestBody.seqno == storage.seqno) throw ErrCode.InvalidSeqno;
    storage.seqno += 1;

    acceptExternalMessage();
    storage.save();

    val msg = createMessage({
      bounce: BounceMode.NoBounce,
      dest: request.requestBody.to,
      value: 0,
      body: "Your action payload here"
    });
    msg.send(SEND_MODE_REGULAR);
}

get fun seqno(): uint64 {
    val storage = lazy Storage.load();
    return storage.seqno;
}
Remember to also implement replay protection to prevent reusing the same signature even if it’s correctly targeted.

Vulnerable approach

Do not sign data without including essential context like the recipient address. An attacker could intercept the message, copy the signature, and replace the recipient address in their own transaction, effectively redirecting the intended action or funds.
struct (0x988d4037) Request {
    signature: bytes64
    data: RemainingBitsAndRefs  // `to` address is not part of the signed data
}

struct Storage {
    publicKey: uint256
}

fun Storage.load() {
    return Storage.fromCell(contract.getData())
}

fun onInternalMessage(in: InMessage) {
    val request = Request.fromSlice(in.body);
    val storage = lazy Storage.load();

    // The signature only verifies `request.data`, not the intended recipient.
    if (isSignatureValid(
        request.data.hash(),
        request.signature as slice,
        storage.publicKey
    )) {
        // Attacker can see this message, copy the signature, and send their own
        // message to a different `to` address before this one confirms.
        // The `in.senderAddress` here is the original sender, but the attacker can initiate
        // a similar transaction targeting themselves or another address.
        val msg = createMessage({
            bounce: BounceMode.NoBounce,
            dest: in.senderAddress,  // Vulnerable: recipient isn't verified by the signature
            value: 0,
        });
        msg.send(128);  // Caution: sending the whole balance!
    }
}
Furthermore, once a signature is used in a transaction, it becomes publicly visible on the blockchain. Without proper replay protection, anyone can potentially reuse this signature and the associated data in a new transaction if the contract logic doesn’t prevent it.

Return gas excesses carefully

If excess gas is not returned to the sender, funds accumulate in contracts over time. This is suboptimal. Add a function to rake out excess, but popular contracts like Jetton wallet return it to the sender with a message using the 0xd53276db opcode.

Secure gas handling

struct (0xd53276db) Excesses {}

struct Vote {
    votes: uint32
}

struct Storage {
    votes: uint32
}

fun Storage.load() {
    return Storage.fromCell(contract.getData())
}

fun Storage.save(self) {
    contract.setData(self.toCell())
}

fun onInternalMessage(in: InMessage) {
    val msg = Vote.fromSlice(in.body);

    var storage = lazy Storage.load();
    storage.votes += msg.votes;
    storage.save();

    val excessesMsg = createMessage({
        bounce: BounceMode.NoBounce,
        dest: in.senderAddress,
        value: 0,
        body: Excesses {}
    });
    excessesMsg.send(
        SEND_MODE_IGNORE_ERRORS +
        SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE
    );
}

Pulling data from another contract

Contracts in the blockchain can reside in separate shards processed by another set of validators. This means that one contract cannot pull data from another contract. Specifically, no contract can call a getter function from another contract. Thus, any on-chain communication is asynchronous and done by sending and receiving messages.

Secure approach

Exchange messages to pull data from another contract. Shared messages:
message.tolk
struct (0x100001) GetMoney {}

struct (0x100002) ProvideMoney {}

struct (0x100003) TakeMoney {
    money: coins
}
OneContract.tolk
import "message"

struct OneContractStorage {
    money: coins
}

fun OneContractStorage.load() {
    return OneContractStorage.fromCell(contract.getData())
}

fun onInternalMessage(in: InMessage) {
    val msg = lazy ProvideMoney.fromSlice(in.body);

    match (msg) {
        ProvideMoney => {
            val storage = lazy OneContractStorage.load();

            val reply = createMessage({
                bounce: BounceMode.NoBounce,
                dest: in.senderAddress,
                value: 0,
                body: TakeMoney {
                    money: storage.money
                }
            });
            reply.send(
                SEND_MODE_IGNORE_ERRORS +
                SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE
            );
        }

        else => {
            assert (in.body.isEmpty()) throw 0xFFFF;
        }
    }
}
AnotherContract.tolk
import "message"

enum ErrCode {
    InvalidMoneyProvider = 100,
}

type AnotherContractMessage = GetMoney | TakeMoney

struct AnotherContractStorage {
    oneContractAddress: address
}

fun AnotherContractStorage.load() {
    return AnotherContractStorage.fromCell(contract.getData())
}

fun onInternalMessage(in: InMessage) {
    val msg = lazy AnotherContractMessage.fromSlice(in.body);
    val storage = lazy AnotherContractStorage.load();

    match (msg) {
        GetMoney => {
            val request = createMessage({
                bounce: BounceMode.NoBounce,
                dest: storage.oneContractAddress,
                value: 0,
                body: ProvideMoney {}
            });
            request.send(
                SEND_MODE_IGNORE_ERRORS +
                SEND_MODE_CARRY_ALL_REMAINING_MESSAGE_VALUE
            );
        }

        TakeMoney => {
            assert (in.senderAddress == storage.oneContractAddress)
                throw ErrCode.InvalidMoneyProvider;
            // ...further processing...
        }

        else => {
            assert (in.body.isEmpty()) throw 0xFFFF;
        }
    }
}

TON address representation issues

TON addresses have multiple formats that must be handled correctly.

Address formats

// Raw: 0:b4c1b2ede12aa76f4a44353944258bcc8f99e9c7c474711a152c78b43218e296
// Bounceable: EQC0wbLt4Sqnb0pENTlEJYvMj5npx8R0cRoVLHi0MhjilkPX
// Non-bounceable: UQC0wbLt4Sqnb0pENTlEJYvMj5npx8R0cRoVLHi0Mhjilh4S

// Always validate workchain
forceChain(toAddress);

Name collision vulnerabilities

Function or variable names can collide with built-in functions or reserved keywords.

Best practice

// Use descriptive, unique names
var userBalance = 0;  // Instead of just `balance`
fun validateUserSignature() { }  // Instead of just `validate()`

Incorrect data type handling

Reading or writing incorrect data types can corrupt contract state.

Vulnerable code

// Writing uint but reading int
val data = beginCell()
    .storeUint(value, 32)
    .endCell();

var storage = data.beginParse();
val readValue = storage.loadInt(32);  // Type mismatch

Secure implementation

// Consistent type usage
val data = beginCell()
    .storeUint(value, 32)
    .endCell();

var storage = data.beginParse();
val readValue = storage.loadUint(32);

Missing function return value checks

Ignoring function return values can lead to logic errors and unexpected behavior.

Vulnerable code

infoDict.delete(index);  // Ignoring success flag

Secure implementation

val success = infoDict.delete(index);
assert (success) throw ErrCode.FailToDeleteDict;

Contract code updates

Contracts can be updated if not properly protected, changing their behavior unexpectedly.

Secure implementation

fun updateCode(newCode: cell) {
    assert (authorizedAdmin(sender())) throw ErrCode.Unauthorized;
    assert (validateCode(newCode)) throw ErrCode.InvalidCode;

    setCode(newCode);
}