> 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/rukovodstva-dlya-razrabotchikov/deploy-solidity.md).

# Развертывание контрактов Solidity

Это руководство описывает развертывание смарт-контрактов Solidity в Rome EVM с использованием Hardhat и Foundry.

## Предварительные требования

* Установлен Node.js v22.13+ (Hardhat) или Foundry
* Пополненный адрес Rome EVM (см. [Быстрый старт](/ru/nachalo-raboty/quickstart.md))
* Ваш закрытый ключ, экспортированный как переменная окружения

```bash
export PRIVATE_KEY="0xYOUR_PRIVATE_KEY"
```

## Настройка сети

| Сеть              | URL RPC                                     | Идентификатор цепочки |
| ----------------- | ------------------------------------------- | --------------------- |
| Локальная         | `http://localhost:9090`                     | `1001`                |
| Hadrian (devnet)  | `https://hadrian.testnet.romeprotocol.xyz/` | `200010`              |
| Martius (testnet) | `https://martius.testnet.romeprotocol.xyz/` | `121214`              |

## Hardhat

### Настройка

```bash
mkdir my-rome-project && cd my-rome-project
npx hardhat --init
```

Примите значения по умолчанию (Hardhat 3, текущий каталог, шаблон TypeScript + viem); зависимости установятся автоматически.

### hardhat.config.ts

```typescript
import hardhatToolboxViemPlugin from "@nomicfoundation/hardhat-toolbox-viem";
import { configVariable, defineConfig } from "hardhat/config";

export default defineConfig({
  plugins: [hardhatToolboxViemPlugin],
  solidity: {
    profiles: {
      default: { version: "0.8.28" },
      production: {
        version: "0.8.28",
        settings: { optimizer: { enabled: true, runs: 200 } },
      },
    },
  },
  networks: {
    rome_local: {
      type: "http",
      chainType: "l1",
      chainId: 1001,
      url: "http://localhost:9090",
      accounts: [configVariable("PRIVATE_KEY")],
    },
    hadrian: {
      type: "http",
      chainType: "l1",
      chainId: 200010,
      url: "https://hadrian.testnet.romeprotocol.xyz/",
      accounts: [configVariable("PRIVATE_KEY")],
    },
    martius: {
      type: "http",
      chainType: "l1",
      chainId: 121214,
      url: "https://martius.testnet.romeprotocol.xyz/",
      accounts: [configVariable("PRIVATE_KEY")],
    },
  },
});
```

`configVariable("PRIVATE_KEY")` разрешается из среды (или из зашифрованного хранилища ключей — `npx hardhat keystore set PRIVATE_KEY`).

### Развернуть

```bash
npx hardhat run scripts/deploy.ts --network hadrian
```

### Проверить в обозревателе блокчейна

```bash
npx hardhat verify --network martius 0xCONTRACT_ADDRESS
```

Требуется конфигурация верификатора Sourcify из [Проверить контракты](/ru/rukovodstva-dlya-razrabotchikov/verify-contracts.md) в вашем `hardhat.config.ts`.

## Foundry

### Настройка

```bash
forge init my-rome-project
cd my-rome-project
```

### Развернуть

```bash
# Локально
forge create --rpc-url http://localhost:9090 \\
  --private-key $PRIVATE_KEY \\
  src/Counter.sol:Counter

# Devnet
forge create --rpc-url https://hadrian.testnet.romeprotocol.xyz/ \\
  --private-key $PRIVATE_KEY \\
  src/Counter.sol:Counter
```

### Вызов развернутого контракта

```bash
# Чтение
cast call 0xCONTRACT_ADDRESS "number()" \\
  --rpc-url https://hadrian.testnet.romeprotocol.xyz/

# Запись
cast send 0xCONTRACT_ADDRESS "increment()" \\
  --rpc-url https://hadrian.testnet.romeprotocol.xyz/ \\
  --private-key $PRIVATE_KEY
```

## Использование Rome Solidity SDK

Для контрактов, взаимодействующих с программами Solana, используйте интерфейсы из публичного [`rome-solidity`](https://github.com/rome-protocol/rome-solidity) репозитория (публикация в npm ожидается):

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {ICrossProgramInvocation, IHelperProgram}
    from "@rome-protocol/rome-solidity/contracts/interface.sol";

contract MyRomeContract {
    IHelperProgram constant Helper =
        IHelperProgram(0xFF00000000000000000000000000000000000009);
    ICrossProgramInvocation constant Cpi =
        ICrossProgramInvocation(0xFF00000000000000000000000000000000000008);

    // Передача токена SPL из PDA вызывающего
    function moveSpl(address to, uint64 tokens, bytes32 mint) external {
        Helper.transfer_spl(to, tokens, mint);
    }

    // Вызов любой программы Solana через CPI
    function callSolanaProgram(
        bytes32 programId,
        ICrossProgramInvocation.AccountMeta[] calldata accounts,
        bytes calldata data
    ) external {
        Cpi.invoke(programId, accounts, data);
    }
}
```

## Перенесите существующий протокол

Любой контракт Solidity развертывается в Rome без изменений — контракт соблюдения, протокол DeFi или уже существующее проверенное приложение. Ниже приведены два примера из production, которые можно форкнуть и развернуть с тем же процессом Hardhat / Foundry, что и выше:

* [**compound-on-rome-comet**](https://github.com/rome-protocol/compound-on-rome-comet) — канонический Compound v3 (Comet), стандартный Foundry.
* [**rome-aave-v3**](https://github.com/rome-protocol/rome-aave-v3) — канонический Aave v3.

Оба получают выполнение в Solana и композиционность CPI без изменений в контракте.

## Ограничения развертывания

| Ограничение                   | Лимит                  | Примечания                                                               |
| ----------------------------- | ---------------------- | ------------------------------------------------------------------------ |
| Максимальный размер контракта | 24 КБ                  | Как в Ethereum (EIP-170, 24 576 байт)                                    |
| Лимит размера транзакции      | 80 КБ на holder        | Крупные развертывания прозрачно распределяются по учетным записям holder |
| Бюджет вычислений             | ≈1,4 млн CU (атомарно) | Используйте итеративный режим для ресурсоемких контрактов                |
| Версия Solidity               | Рекомендуется 0.8.28   | Более ранние версии работают, но 0.8.28 соответствует SDK                |

## Распространенные ошибки

| Ошибка                          | Причина                            | Исправление                                                                                                                |
| ------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `недостаточно средств для газа` | У EVM-адреса нет токена для газа   | Оберните газ через [Rome App](https://app.devnet.romeprotocol.xyz) (см. [Быстрый старт](/ru/nachalo-raboty/quickstart.md)) |
| `слишком низкий nonce`          | Устаревший nonce в кошельке        | Сбросьте учетную запись MetaMask или укажите nonce вручную                                                                 |
| `выполнение отменено`           | Логика контракта завершилась сбоем | Отладьте с помощью `eth_call` или `forge test --fork-url`                                                                  |
| `транзакция недооценена`        | Цена газа ниже минимальной         | Увеличьте цену газа в транзакции                                                                                           |

## Что дальше

* [Вызывать Solana из EVM](/ru/rukovodstva-dlya-razrabotchikov/call-solana-from-evm.md) — используйте precompile CPI для взаимодействия с программами Solana
* [Проверить контракты](/ru/rukovodstva-dlya-razrabotchikov/verify-contracts.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/rukovodstva-dlya-razrabotchikov/deploy-solidity.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.
