> ## Documentation Index
> Fetch the complete documentation index at: https://docs.optimism.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 앱에 Subblocks 통합하기

> pending 태그와 함께 표준 JSON-RPC 메서드를 사용하거나 viem 및 ethers를 통해 앱에서 사전 확인(pre-confirmed)된 Subblocks 상태를 조회합니다.

[Subblocks](https://docs.optimism.io/ko/op-stack/features/subblocks.md)를 스트리밍하는 체인은 200 ms마다 부분 블록을 게시하므로, 앱은 트랜잭션이 포함된 블록이 봉인(seal)되기 훨씬 전에 트랜잭션 결과를 표시할 수 있습니다.
이 가이드에서는 표준 Ethereum JSON-RPC와 viem 및 ethers 라이브러리를 통해 이러한 사전 확인(pre-confirmed) 상태를 읽는 방법을 설명합니다.

대부분의 앱은 엔드포인트를 변경하고 `pending` 블록 태그를 사용하기만 하면 됩니다.

* 프로덕션 환경에서는 원하는 제공업체의 subblocks 지원 RPC 엔드포인트를 앱에 지정하세요. 사용 중인 제공업체가 아직 subblocks를 지원하지 않는다면 [Discord](https://discord.gg/jPQhHTdemH)에서 알려 주세요.
  해당 제공업체와 협력하여 지원이 추가되도록 하겠습니다.
* subblocks를 지원하는 자체 node를 실행하려면 체인의 스트림을 가리키는 `--flashblocks-url=<websocket-url>`과 함께 `op-reth`를 시작하세요. 그러면 node는 subblock 상태를 기반으로 `pending`을 제공합니다.
  OP Mainnet 및 OP Sepolia 스트림 URL은 [네트워크 정보 페이지](https://docs.optimism.io/ko/op-mainnet/network-information/connecting-to-op.md)에 나와 있습니다.

> [!NOTE]
>
> 이 가이드는 대부분의 앱에서 필요로 하는 방식인 RPC 엔드포인트를 통한 사전 확인 상태 읽기를 다룹니다.
> 대신 WebSocket 스트림을 직접 사용하는 경우, 네 개의 페이로드 필드가 0으로 채워지므로 이를 처리해야 합니다. 자세한 내용은 [Subblocks 공지](https://docs.optimism.io/ko/notices/subblocks.md)를 참조하세요.
> Lagoon 체인에서는 스트림이 블록의 실행 후(post-execution) 트랜잭션도 트랜잭션 목록 밖에 담아 전달합니다. 자세한 내용은 [실행 후 트랜잭션](https://docs.optimism.io/ko/op-stack/features/subblocks.md#the-post-execution-transaction)을 참조하세요.

## 지원되는 RPC 메서드

subblock 상태는 이미 사용 중인 것과 동일한 Ethereum JSON-RPC 호출로 읽을 수 있습니다.
차이점은 일부 호출에서 "pending" 태그를 사용하여 마지막으로 최종 확정된 블록 대신 사전 확인 상태를 명시적으로 조회한다는 것입니다.

* **`eth_getBlockByNumber`**: `pending` 태그를 사용하여 최신 subblock 스냅샷을 가져옵니다.

  > [accordion] 응답 예시
  >
  > ```json theme={null}
  >     {
  >       "jsonrpc": "2.0",
  >       "id": 1,
  >       "result": {
  >         "number": "0x1234",
  >         "hash": "0x...",
  >         "transactions": [...]
  >       }
  >     }
  > ```

* **`eth_call`**: `pending` 태그를 사용하여 가장 최근의 사전 확인 상태를 대상으로 호출을 실행합니다.

  > [accordion] 요청 예시
  >
  > ```json theme={null}
  > {
  >   "jsonrpc": "2.0",
  >   "method": "eth_call",
  >   "params": [{"to": "0x...", "data": "0x..."}, "pending"],
  >   "id": 1
  > }
  > ```

* `eth_getBalance` / `eth_getTransactionCount`: `pending` 태그를 사용하여 블록 구간 내에서 변화하는 잔액 또는 트랜잭션 수를 각각 가져옵니다.

  > [accordion] `eth_getBalance` 응답 예시
  >
  > ```json theme={null}
  > {
  >   "jsonrpc": "2.0",
  >   "id": 1,
  >   "result": "0x0234"
  > }
  > ```

  > [accordion] `eth_getTransactionCount` 응답 예시
  >
  > ```json theme={null}
  > {
  >   "jsonrpc": "2.0",
  >   "id": 1,
  >   "result": "0x1b" // 27 transactions
  > }
  > ```

  `eth_getTransactionReceipt`, `eth_getTransactionByHash`, `eth_simulateV1`과 같은 다른 메서드는 `pending` 태그 없이도 사전 확인된 트랜잭션의 데이터를 반환합니다.
  지원되는 메서드와 pending 상태 동작은 [Subblocks 사양](https://specs.optimism.io/protocol/subblocks.html#json-rpc)을 참조하세요.

## 라이브러리

다음 라이브러리를 사용하려면 subblocks를 지원하는 RPC 엔드포인트가 필요합니다.

### Viem

```ts theme={null}
import { createPublicClient, createWalletClient, http, parseEther } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { opSepolia } from 'viem/chains';
import { publicActionsL2, walletActionsL2 } from 'viem/op-stack';

const account = privateKeyToAccount(`0x${process.env.PRIVATE_KEY}`);

const walletClient = createWalletClient({
  account,
  chain: opSepolia,
  transport: http("https://sepolia.optimism.io"),
}).extend(walletActionsL2());

const publicClient = createPublicClient({
  chain: opSepolia,
  transport: http("https://sepolia.optimism.io"),
}).extend(publicActionsL2());

const submissionTime = new Date();
const hash = await walletClient.sendTransaction({
  to: '0x...',
  value: parseEther('0.0001'),
});

// Wait for pre-confirmation
const receipt = await publicClient.waitForTransactionReceipt({ hash });
const confirmTime = new Date();
console.log('pre-confirmed in ms:', confirmTime.getTime() - submissionTime.getTime());
```

### Ethers

```ts theme={null}
import { ethers } from 'ethers';

// Here, provider is a subblocks-enabled RPC provider
const provider = new ethers.JsonRpcProvider("https://sepolia.optimism.io");
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY as string, provider);

const tx = { to: '0x...', value: ethers.parseEther('0.0001') };
const submission = new Date();

const sent = await wallet.sendTransaction(tx);

await sent.wait(0);
const confirmed = new Date();

// should represent the transaction (pre)confirmation faster than standard RPC
console.log('Pre-confirmed in ms:', confirmed.getTime() - submission.getTime());

// validates the transaction hash returned by the pre-confirmed transaction above
const receipt = await provider.getTransactionReceipt(sent.hash);
const validated = new Date();
console.log('Receipt validated in ms:', validated.getTime() - submission.getTime());
console.log('Transaction receipt:', receipt);
```

## 다음 단계

* subblocks가 [gas 사용량과 대용량 트랜잭션](https://docs.optimism.io/ko/app-developers/guides/transactions/subblocks-and-gas-usage.md)에 어떤 영향을 미치는지 알아보세요.
* [Subblocks 설명](https://docs.optimism.io/ko/op-stack/features/subblocks.md)에서 subblocks의 작동 방식을 알아보세요.
* wire format 및 JSON-RPC 세부 사항은 [Subblocks 사양](https://specs.optimism.io/protocol/subblocks.html)을 검토하세요.
* [커뮤니티](https://discord.gg/jPQhHTdemH)에 참여하여 모범 사례를 공유하고 지원을 받으세요!
