> 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/ko/core-concepts/compute-budget.md).

# 컴퓨트 예산

Rome EVM 작업의 Solana 컴퓨트 유닛(CU) 비용 — 원자적 예산과 반복적 예산, 그리고 CU 효율적인 Solidity 계약을 설계하는 방법.

모든 Solana 트랜잭션에는 Compute Units(CU)로 측정되는 컴퓨트 예산이 있습니다. CU 비용을 이해하면 효율적인 Rome 컨트랙트를 설계하는 데 도움이 됩니다.

## 예산 개요

| 모드        | 최대 CU                                 | 참고                                                              |
| --------- | ------------------------------------- | --------------------------------------------------------------- |
| 원자적(VmAt) | \~1,400,000 CU                        | 단일 Solana 트랜잭션                                                  |
| 반복적(VmIt) | 레그당 최대 약 1,400,000 CU; 세션당 최대 160회 반복 | 각 레그는 자체 Solana 트랜잭션이며, 적응형 opcode/step은 각 tx의 CU 예산에 맞춰 패킹됩니다. |

각 Solana 트랜잭션의 기본 예산은 200,000 CU이며, 컴퓨트 예산 지침(Rome SDK에 의해 자동 추가)을 통해 약 140만 CU까지 확장할 수 있습니다.

반복 실행은 무제한이 아닙니다. 하나의 세션은 160회 반복 후 종료되며, Rust Rome SDK의 반복 컴포저는 최대 128개 레그를 계획합니다. 지갑이 직접 서명하는 계획은 `rome_submitSignedV1Plan`를 거치며, 호출당 최대 64개의 트랜잭션만 허용합니다. 대부분의 호출은 훨씬 적은 수만 필요합니다. 레거시 트랙 CPI는 반복 세션 내에서 거부되므로, 이를 수행하는 호출은 원자적 예산 안에 들어가야 합니다. 참조: [릴레이된 호출 및 장시간 호출](/ko/developer-guides/call-evm-from-solana.md#relayed-calls-and-long-calls) 및 [제약 사항](/ko/core-concepts/constraints.md).

## CU 비용 추정치

### EVM 연산

| 연산                   | 대략적인 CU               | 참고                                                                     |
| -------------------- | --------------------- | ---------------------------------------------------------------------- |
| 트랜잭션 서명 검증(EVM 키 경로) | \~25,000 CU           | 위의 `secp256k1_recover` syscall로, 아래의 `ecrecover` precompile와 동일한 비용입니다 |
| 단순 전송                | \~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    | 콜드 액세스 vs 웜 액세스                                                        |

### Precompile 연산

| 프리컴파일           | 대략적인 CU                      | 참고                                                                                                                                                                                           |
| --------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ecrecover       | \~25,700 CU                  |                                                                                                                                                                                              |
| SHA-256         | 측정된 32바이트 워드당 \~257 CU       | 여기에 소액의 고정 비용이 추가됩니다. 이 프로그램은 SHA-256, RIPEMD-160 및 identity precompile의 가격을 워드당 약 2,200 CU라는 하나의 공유 기준으로 책정하며, 이는 세 가지 중 가장 비용이 큰 RIPEMD-160에 맞춘 수치이므로 SHA-256 호출은 실제 사용량보다 더 많은 비용이 청구됩니다. |
| BN254 ecAdd     | 거의 0 CU                      | 32바이트 복사보다 저렴함                                                                                                                                                                               |
| BN254 ecMul     | \~4,200 CU                   |                                                                                                                                                                                              |
| BN254 ecPairing | \~22,000 CU + 쌍당 \~12,800 CU | 4쌍 검사는 약 73,000 CU로, 단일 원자적 트랜잭션 범위 내에 충분히 들어갑니다.                                                                                                                                            |

이 수치는 프로그램 자체의 보정값에서 나온 것으로, 테스트넷 배포에서 Solana 노드로부터 읽어온 컴퓨트 유닛을 사용했습니다. 이 페이지를 위해 재측정한 것은 아니며, 자신의 호출은 `computeUnitsConsumed`.

## 최적화 기법

### 1. Hot Path에는 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 https://hadrian.testnet.romeprotocol.xyz/ \
  0xCONTRACT "myFunction(uint256)" 42
```

또는 ethers.js를 통해:

```javascript
const gas = await contract.myFunction.estimateGas(42);
console.log("추정 가스:", gas.toString());
```

## 다음 단계

* [제약 사항](/ko/core-concepts/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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.rome.builders/ko/core-concepts/compute-budget.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
