Оценка газа перед деплоем

Оценишь gas и fees в sandbox: compute phase, forward fee и какой value класть в сообщение.

Оценка газа

Комиссия на TON складывается из compute phase (газ TVM), action/forward fees и storage. До mainnet снимай цифры в @ton/sandbox: там у транзакции есть фазы и totalFees.


Замер в тесте

typescript
// @ton/sandbox ^0.27.0 · @ton/core ^0.60.0 · @ton/test-utils ^0.6.0
import { Blockchain, SandboxContract, TreasuryContract } from "@ton/sandbox";
import { toNano, beginCell } from "@ton/core";
import { Counter } from "../build/Counter/tact_Counter";
import "@ton/test-utils";

function printTxFees(label: string, tx: any) {
  if (tx.description.type !== "generic") return;
  const compute = tx.description.computePhase;
  const gasUsed =
    compute.type === "vm" ? compute.gasUsed : 0n;
  console.log(label, {
    gasUsed: gasUsed.toString(),
    totalFees: tx.totalFees.coins.toString(),
  });
}

describe("Counter gas", () => {
  it("measures Add path", async () => {
    const blockchain = await Blockchain.create();
    const user = await blockchain.treasury("user");
    const counter = blockchain.openContract(await Counter.fromInit(7n, 0n));

    await counter.send(user.getSender(), { value: toNano("0.05") }, null);

    const result = await counter.send(
      user.getSender(),
      { value: toNano("0.05") },
      { $$type: "Add", amount: 1n },
    );

    const target = result.transactions.find(
      (t) => t.address?.equals(counter.address),
    );
    expect(target).toBeTruthy();
    printTxFees("Add", target);

    // Практическое правило: value ≥ compute + fwd + запас на storage
    // Для простых receivers часто хватает 0.02–0.05 GRAM; замеряй свой путь.
    expect(result.transactions).toHaveTransaction({
      to: counter.address,
      success: true,
    });
  });
});
bash
# Опционально: репортёр газа из sandbox
# в jest.config: testEnvironment + @ton/sandbox/jest-reporter
npx blueprint test

Как это работает

  • computePhase.gasUsed — сколько газа сожгла TVM; растёт с парсингом cell, map-update, циклами.
  • totalFees — суммарные комиссии транзакции (не только gasUsed × gasPrice).
  • Value сообщения должно покрыть fees и оставить контракту нужный баланс для storage/ответов.
  • Худший путь (большой map, несколько исходящих сообщений) замеряй отдельно — средний happy-path врёт.
  • На mainnet gas price и storage rate другие, чем в sandbox; закладывай запас, не копируй nanotons один в один.

Частые ошибки

Шлёшь toNano("0.01") «потому что в туториале так» → сложный receiver падает mid-flight или не может ответить.

Смотришь только первую tx в цепочке → дорогим может быть второй hop (контракт→контракт).

Оптимизируешь gas, ломая bounce/проверки → дешевле, но некорректно; сначала корректность, потом газ.


Что дальше

Материалы gramdocs.tech носят образовательный характер и не являются финансовой, юридической или инвестиционной рекомендацией. Работа с блокчейном TON и токеном Gram связана с рисками потери средств. Правовая информация