> For the complete documentation index, see [llms.txt](https://docs.rome.builders/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rome.builders/ru/klyuchevye-ponyatiya/compute-budget.md).

# Бюджет вычислений

Каждая транзакция Solana имеет вычислительный бюджет, измеряемый в единицах вычисления (CU). Понимание затрат CU помогает проектировать эффективные контракты Rome.

## Обзор бюджета

| Режим              | Макс. CU                   | Примечания                                                          |
| ------------------ | -------------------------- | ------------------------------------------------------------------- |
| Атомарный (VmAt)   | \~1,400,000 CU             | Одна транзакция Solana                                              |
| Итеративный (VmIt) | Без ограничений (multi-tx) | Адаптивные опкоды/шаг — подгоняются под бюджет CU каждой транзакции |

Каждая транзакция Solana по умолчанию имеет бюджет 200,000 CU, который можно увеличить примерно до 1.4M CU с помощью инструкций compute budget (добавляются автоматически SDK Rome).

## Оценка затрат CU

### Операции EVM

| Операция                                     | Примерный расход CU  | Примечания                             |
| -------------------------------------------- | -------------------- | -------------------------------------- |
| Проверка подписи (ecrecover)                 | \~5,000 CU           | secp256k1 через системный вызов Solana |
| Простой перевод                              | \~50,000-100,000 CU  | Только обновление балансов             |
| Перевод ERC-20                               | \~100,000-150,000 CU | Включает вызов SPL precompile          |
| Развертывание контракта (небольшого размера) | \~200,000-400,000 CU | Зависит от размера байткода            |
| Запись в хранилище (SSTORE)                  | \~5,000-20,000 CU    | Холодный и теплый доступ               |

### Операции предкомпиляции

| Предкомпиляция  | Примерный расход CU |
| --------------- | ------------------- |
| ecrecover       | \~3,000-5,000 CU    |
| SHA-256         | \~1,000 CU          |
| BN254 ecAdd     | \~10,000 CU         |
| BN254 ecMul     | \~40,000 CU         |
| BN254 ecPairing | \~200,000+ CU       |

## Техники оптимизации

### 1. Используйте Yul для критически важных участков

Оптимизатор Solidity генерирует приемлемый код, но Yul (встроенный ассемблер) может значительно снизить CU для критически важных операций:

```solidity
// До: ~600K CU
function createPairAccount(bytes32 token0, bytes32 token1) external {
    // Операции на уровне Solidity
}

// После: ~150K CU (оптимизация Yul)
function createPairAccount(bytes32 token0, bytes32 token1) external {
    assembly {
        // Прямое манипулирование памятью, без накладных расходов на ABI-кодирование
    }
}
```

### 2. Кэшируйте вычисления PDA

Вычисление PDA через `find_program_address` — дорогая операция. Храните вычисленные PDA в хранилище контракта, а не вычисляйте их при каждом вызове:

```solidity
mapping(address => bytes32) private cachedPdas;

function getPda(address user) internal returns (bytes32) {
    bytes32 cached = cachedPdas[user];
    if (cached != bytes32(0)) return cached;

    bytes32 pda = RomeEVMAccount.pda(user);
    cachedPdas[user] = pda;
    return pda;
}
```

### 3. Жестко задавайте известные ID программ

Не загружайте ID программ из хранилища — используйте константы:

```solidity
// Дорого: чтение из хранилища
bytes32 splTokenProgram = storage_program_id;

// Дешево: константа времени компиляции
bytes32 constant SPL_TOKEN_PROGRAM = 0x06ddf6e1d765a193d9cbe146ceeb79ac1cb485ed5f5b37913a8cf5857eff00a9;
```

### 4. Минимизируйте число аккаунтов

Каждый аккаунт в транзакции Solana увеличивает накладные расходы CU. Сократите число аккаунтов за счет:

* Группировки операций, использующих общие аккаунты
* Использования меньшего числа промежуточных аккаунтов
* Избежания избыточных проверок создания ATA

### 5. Используйте настройки оптимизатора

```typescript
// hardhat.config.ts — включите оптимизатор в профиле сборки
solidity: {
  profiles: {
    default: { version: "0.8.28" },
    production: {
      version: "0.8.28",
      settings: { optimizer: { enabled: true, runs: 200 } },
    },
  },
}
```

Соберите с помощью `npx hardhat compile --build-profile production`.

## Измерение потребления CU

Используйте `eth_estimateGas` для измерения CU перед отправкой:

```bash
cast estimate --rpc-url http://localhost:9090 \\
  0xCONTRACT "myFunction(uint256)" 42
```

Или через ethers.js:

```javascript
const gas = await contract.myFunction.estimateGas(42);
console.log("Оцененный gas:", gas.toString());
```

## Что дальше

* [Ограничения](/ru/klyuchevye-ponyatiya/constraints.md) — полный список ограничений и пределов


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.rome.builders/ru/klyuchevye-ponyatiya/compute-budget.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
