bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 66쪽
ing either calldata or blobs. Under normal conditions, using blobs is default method, but in extreme situations where blob prices significantly exceed those of calldata, the Starknet sequencer can switch to use calldata instead.
<Tip>
See [Data availability with EIP-4844](https://community.starknet.io/t/data-availability-with-eip4844/) on the Starknet Community Forum or review [an example blob published on Ethereum by the Starknet sequencer](https://etherscan.io/tx/0x8a227491bc78424c2cac1b203c95cdd99ede5112d41f0e7eab26f3c8aa9c658d/) for more details.
</Tip>
The format for state diffs remains the same as in version 0.11.0, but the data sent to Ethereum changed to a Fast Fourier Transform (FFT) of the original data. To recover Starknet's state diff based on blobs or calldata published onchain, an Inverse Fast Fourier Transform (IFFT) on the data must first be performed, afterwhich decoding can proceed as usual.
### v0.13.3
In Starknet version 0.13.3, sending state diffs to Ethereum changed from sending raw state diffs to sending compressed state diffs. The employed compression scheme is a simple lookup table variant, where a list of 252-bit field elements is transformed into a (usually smaller) list of 252-bit field elements as follows:
1. Unique field elements in the data are split into buckets of 15, 31, 62, 83, 125, and 252 bits (i.e. felts that require less than 15 bits go into the 15 bits bucket, felts that require 16 to 31 bits go into the 31 bits bucket, and so on).
2. Each bucket is packed according to its number of bits (e.g., the 31 bits bucket allows the packing of 8 elements into a single felt).
3. A list of pointers whose length is the length of the original data is constructed, where the `i`'th pointer is the bucket of the `i`'th element if the `i`'th element is a first occurrence, or a special index that indicates a repetition otherwise.
<Warning>
The list of pointers can be packed to \~ 1/84 of the original list length since we only need 3 bits to indicate the bucket and we can fit 84 of those into a felt.
</Warning>
4. A list of repeating value pointers is constructed, by adding `(bucket_index, index_in_bucket)` for every repetition in the original data.
To illustrate the above, consider the following example: Let indices 0,1, …, 5 correspond to buckets 252, 125, …, 15, and let 6 denote a special bucket of repetitions. For the data list `[2^250, 10, 100, 2^63, 2^63+1, 10, 100]`, we construct the following:
* Bucket 252: `[2^250]`
* Bucket 83: `[2^63, 2^63+1]`
* Bucket 15: `[10, 100]`
* Pointers: `[0, 5, 5, 3, 3, 6, 6]`
* Repeating value pointers: `[(5, 0), (5, 1)]` (We have two repetitions: the first for 10, which is the first element in bucket index 5, and the second for 100, which is the second element in the same bucket)
The final compressed list packs each bucket and each list individually and adds some necessary metadata.
<Note>
This simple-to-write compression was chosen over the common Brotli or gzip compressions employed by other chains for similar purposes because the compression must be proven (i.e., either the compression or decompression must be implemented within the Starknet OS, and therefore its efficiency is crucial).
You can find a Python implementation of it in the [cairo-lang repository](https://github.com/starkware-libs/cairo-lang).
</Note>
To better lends itself to the new compression scheme, as well as allow its construction to be based on the state diff alone, the uncompressed encoding of contract diff headers also changed as follows:
$\left|\right. \underset{\text{64 bits}}{\underbrace{\text{new nonce }(\text{if changed})}} \left|\right. \underset{\text{64 bits}}{\underbrace{\#\text{ of storage updates}}} \left|\right. \underset{\text{1 bit}}{\underbrace{\text{class information flag}}} \left|\right. \underset{\text{1 bit}}{\underbrace{\text{updates information flag}}}_{\text{LSB}}$
where:
* The updates information flag is `0` if the number of updates is less than 256 (and therefore can fit in 8 bits), and `1` otherwise
* The semantics of class information flag is unchanged (i.e., it indicates whether or not the class was replaced)
* If the nonce of the contract is unchanged, the value of the new nonce is zero
<Note>
This definition can slightly deviate from the previous semantics, if an account contract was modified externally (e.g., via `execute_from_outside`). In this case, the contract's nonce is unchanged, yet it appears in the state update (since its storage was updated). Pre-v0.13.3, the current nonce of the account would have appeared although it is unchanged, while in v0.13.3 the value of new nonce is zero. This change helps with making the encoding derivable solely from the state diff itself, without referring to the global state of the chain.
</Note>
### v0.13.4
In Starknet v0.13.4, a second layer, termed *stateful compression*, was added to the compression of state diffs.
Stateful compression is based on the observation that most parts that were “incompressible” by the previous compression — now termed *stateless compression* — are storage keys and contract addresses, which can be indexed based on their first occurrence in a state diff, thus encoding them with potentially much less than the full 32bytes.
To achieve this, a new system contract at address `0x2` was introduced, defined as follows:
* Storage slot `0x0` of the contract is the value of a global counter, initialized to `128` in the beginning of the first block of v0.13.4.
* Whenever a non-indexed storage key or contract address appears in a state diff, it is mapped to the current value of the counter, and the counter is increased.
<Note>
Storage keys that require at most 127 bits and addresses of system contracts (currently, `0x1` and `0x2`) are not mapped and continue to be referred to directly.
</Note>
* The (uncompressed) state-diff includes the corresponding counter values from the value-to-index mapping rather than the original values.
As its name suggests, stateful compression introduces dependency between state diffs submitted to Ethereum. That is, state diffs of a given block cannot be decoded without knowing the state diffs of the previous blocks. This dependency is only relevant for post-v0.13.4 state diffs, while pre-v0.13.4 state diffs remain self-contained.
<Warning>
Starknet v0.13.4 introduces dependency between state diffs, making post-v0.13.4 state diffs non-decodable without knowledge of previous post-v0.13.4 state diffs.
</Warning>
# Fees
Source: https://docs.starknet.io/learn/protocol/fees
## Overview
Every transaction on Starknet requires a small fee to process. The components contributing to this fee include [L2 computation, L2 data, and L1 data](/learn/protocol/fees#fee-components), which are measured in [L2 gas, L1 gas, and L1 data gas](/learn/protocol/fees#fee-resources). A transaction's fee can be [estimated](/learn/protocol/fees#fee-estimations) and [limited](/learn/protocol/fees#fee-limits), and is ultimately [charged](/learn/protocol/fees#fee-charges) based on a predefined [formula](/learn/protocol/fees#overall-fee).
<Note>
This section describes fees that are paid on L2 starting in Starknet 0.13.0. For information about messaging fees that are paid on L1, see [L1→L2 message fees](/learn/protocol/messaging/#l1-l2-message-fees).
</Note>
## Fee components
The following components contribute to a transaction's fee:
* [L2 computation](/learn/protocol/fees#l2-computation)
* [L2 data](/learn/protocol/fees#l2-data) (calldata, events and code)
* [L1 data](/learn/protocol/fees#l1-data), which includes:
* The cost of posting the state diffs induced by the transaction to L1 (for more details, see [Data availability](/learn/protocol/data-availability/))
* L2→L1 messages (which are eventually sent to the Starknet core contract as L1 calldata by the Starknet sequencer)
## Fee units
The three components contributing to a transaction's fee are measured by the following three units:
* *L2 gas*, measuring L2 resources, including computation and data
* *L1 data gas*, measuring the L1 data required to post the state diff induced by the transaction to L1
* *L1 gas*, measuring the L1 gas required for sending L2→L1 messages
## Fee estimations
The fee for a transaction can be estimated by using the [`starknet_estimateFee endpoint`](https://github.com/starkware-libs/starknet-specs/blob/v0.7.1/api/starknet_api_openrpc.json#L612), and interfaces for fee estimations are also exposed by the various [Starknet SDKs](../cheatsheets/tools).
## Fee limits
Starting in Starknet v0.14.0, all transactions have to specify STRK-denominated `max_amount` and `max_price_per_unit` for each of the three [fee unit](/learn/protocol/fees#fee-units). A necessary condition for a transaction to enter a block is that `max_price_per_unit` is greater than or equal to the [block's corresponding price](/learn/protocol/fees#gas-prices) for each resource, but if included sequencers are then enforced by the [Starknet OS](/learn/protocol/snos/) (and as such, enforced by a proof) to charge no more than the max price specified by the transaction.
<Note>
`v3` transactions already provide these bounds (as part of the `resource_bounds` dictionary)
Sequencers usually charges less than the max price specified in the transaction, as charges are in accordance with the [formula for determining a transaction's fee](/learn/protocol/fees#overall-fee).
</Note>
## Fee charges
The fee for a transaction is charged atomically with the transaction execution on L2, by the Starknet OS injecting a transfer of STRK with an amount equal to the fee paid, the sender equal to the transaction submitter, and the sequencer as a receiver.
<Note>
Starknet does not currently implement burning of fees, and all fees charged are received by the sequencer.
</Note>
## Fee formula
<Warning>
Starknet's fee formula is highly non-trivial.
To mitigate this, the first section details the formula for determining a transaction's overall fee, while subsequent ones dive into the different fee components and explain how this formula was derived.
Some parts may require reading more than once, but don't hesitate to [reach out](https://github.com/starknet-io/starknet-docs/issues/new?assignees=landauraz\&title=Feedback%20for%20%22The%20Starknet%20operating%20system%22) if you feel further clarification is needed.
</Warning>
<Note>
While sequencer are [enforced not to overcharge fees](/learn/protocol/fees#fee_limits), they are not yet enforced to charge fees charged according to Starknet's fee formula.
</Note>
### Overall fee
The following formula describes the overall fee of a transaction:
$$
\begin{align*}
& \text{l1}_{\text{gas price}} \cdot \Big( \\
&\quad \text{message}_{\text{calldata cost}} \cdot 3t + \\
&\quad (\text{message}_{\text{calldata cost}} + \text{l1}_{\text{log data cost}}) \cdot \sum_{i = 1}^{t} q_{i} + \\
&\quad (\text{l1}_{\text{storage write cost}} + \text{log}_{\text{message to l1 cost}}) \cdot t \Big) \\
&+ (\text{l2}_{\text{gas price}} + \text{tip}) \cdot \left( \text{sierra}_{\text{gas consumed}} + \max_k v_k w_k + \text{l2}_{\text{payload costs}} \right) \\
&+
\begin{cases}
\text{l1}_{\text{data gas price}} \cdot \text{felt}_{\text{size in bytes}} \cdot \left( \ell + 2(n - 1) + 2(m - 1) + 2D \right), & \text{if } \text{l1}_{\text{da mode}} = \text{BLOB} \\
\text{l1}_{\text{gas price}} \cdot \left( \text{da}_{\text{calldata cost}} \cdot \left( \ell + 2(n - 1) + 2(m - 1) + 2D \right) - \right. \\
\quad \text{contract}_{\text{update discount}} \cdot (n - 1) - \text{sender}_{\text{balance update discount}}, & \text{if } \text{l1}_{\text{da mode}} = \text{CALLDATA}
\end{cases}
\end{align*}
$$
where:
* $\text{l1}_{\text{gas price}}$ is the L1 gas price of the block that includes the transaction (see [Gas prices](/learn/protocol/fees#gas-prices) for more information)
* $\text{message}_{\text{calldata cost}}$ is 1,124 gas
* $t$ is the number of L2→L1 messages sent by the transaction
* $\text{l1}_{\text{log data cost}}$ is 256 gas
* $t,\ q_{1}, \ldots, q_{t}$ are the payload sizes of the L2→L1 messages sent by the transaction
* $\text{l1}_{\text{storage write cost}}$ is 20,000 gas (the cost of writing to a new storage slot on Ethereum)
* $\text{log}_{\text{message to l1 cost}}$ is 1,637 gas (see [L2→L1 messages](/learn/protocol/fees#l2→l1-messages) for more information)
* $\text{l2}_{\text{gas price}}$ is the L2 gas price of the block that includes the transaction (see [Gas prices](/learn/protocol/fees#gas-prices) for more information)
* $\text{tip}$ is the tip specified by the transaction
* $\text{sierra}_{\text{gas consumed}}$ is the amount of [Sierra gas](/learn/protocol/fees#sierra-gas) charged for computation of the transaction
* $v$ is a vector that represents resource usage of the transaction (Cairo steps or number of applications of each builtin), where each of its entries, $v_{k}$, corresponds to the usage of a different resource type (see [VM resources](/learn/protocol/fees#vm-resources) for more information)
<Note>
The fee formula of a transaction can track both raw VM resources (reflected by $v_{k}$) and Sierra gas, depending on what classes it goes through (see [L2 computation](/learn/protocol/fees#l2-computation) for more details).
</Note>
* $w$ is the `CairoResourceFeeWeights` vector (see [VM resources](/learn/protocol/fees#vm-resources) for more information)
* $\text{l2}_{\text{payload costs}}$ is the gas cost of the data sent by the transaction over Starknet, which includes calldata, code, and event emission (see [L2 data](/learn/protocol/fees#l2-data) for more information)
* $\text{l1}_{\text{da mode}}$ is either $\text{CALLDATA}$ or $\text{BLOB}$, depending on how the state diff of the block that includes the transaction is sent to L1 (see [Data availability](/learn/protocol/data-availability/) for more information)
* $\text{l1}_{\text{data gas price}}$ is the L1 data gas price of the block that includes the transaction (see [Gas prices](/learn/protocol/fees#gas-prices) for more information)
* $\text{felt}_{\text{size in bytes}}$ is 32 (the number of bytes required to encode a single STARK field element)
* $ℓ$ is the number of contracts whose class was changed by the transaction, which happens on contract deployment and when applying the `replace_class` syscall
* $n$ is the number of unique contracts updated by the transaction, which also includes changes to classes of existing contracts and contract deployments, even if the storage of the newly deployed contract is untouched (in other words, $n \geq ℓ$)
<Note>
Notice that $n \geq 1$ always holds, because the fee token contract is always updated, which does not incur any fee.
</Note>
* $m$ is the number of storage values updated by the transaction, not counting multiple updates for the same key
<Note>
Notice that $m \geq 1$ always holds, because the sequencer's balance is always updated, which does not incur any fee.
</Note>
* $D$ is 1 if the transaction is of type `DECLARE` and 0 otherwise, as declare transactions need to post on L1 the new class hash and compiled class hash which are added to the state
* $\text{da}_{\text{calldata cost}}$ is 551 gas, derived as follows:
* 512 gas per 32-byte word for calldata
* \~100 gas for onchain hashing that happens for every word sent
* A 10% discount for not incurring additional costs for repeated updates to the same storage slot within a single block
* $\text{contract}_{\text{update discount}}$ is 312 gas (see [Storage updates](/learn/protocol/fees#storage-updates) for more information)
* $\text{sender}_{\text{balance update discount}}$ is $240$ gas (see [Storage updates](/learn/protocol/fees#storage-updates) for more information)
### Gas prices
Each Starknet block has three integers associated with it: `l1_gas_price`, `l2_gas_price`, and `l1_data_gas_price`.
`l1_gas_price` and `l1_data_price` are computed by taking the average of the last 60 L1 base gas or data gas prices sampled every 60 seconds by the sequencer, plus 1 Gwei. For `l1_data_gas_price`, this number is then multiplied by a scaling factor of 0.135 that approximate for the average rate compression achieved from posting the data to Ethereum.
`l2_gas_price` is calculated in a similar way to Ethereum's [EIP 1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md), , which means computing `l2_gas_price` as follows:
$$
\max \left(
\left( 1 + \frac{\text{prev}_{\text{L2 gas use}} - \text{TARGET}}{\text{TARGET}} \cdot C \right)
\cdot \text{prev}_{\text{L2 gas price}},\
\text{MIN}_{\text{PRICE}}
\right)
$$
where:
* $\text{prev}_\text{L2 gas use}$ is the total L2 gas used in the previous block
* $\text{TARGET}$ is 80% of [Starknet's block capacity](/learn/cheatsheets/chain-info/#current_limits)
* C equals $\frac{1}{48}$
* $\text{prev}_\text{L2 gas price}$ is the previous block's `l2_gas_price`
* $\text{MIN}_\text{PRICE}$ is currently 3gFri, or $3*10^{-9}$ STRK. $\text{MIN}_\text{PRICE}$ is subjected to change with time, as a function of the transaction processing cost.
This assures that:
* If the total gas used in the previous block is equal to $\text{TARGET}$, then `l2_gas_price` won't change
* If the total gas used in the previous block is larger or smaller than $\text{TARGET}$, then `l2_gas_price` will respectively increase or decrease. Since $\text{TARGET}$ is larger than half of the block size, price will decrease faster when there is no congestion compared to its increase rate when there is congestion.
* When there is no congestion in the network, the `l2_gas_price` will be equal to $\text{MIN}_\text{PRICE}$
### L2 computation
Measuring the L2 computation component of a transaction differs depending on the contract class version of the caller:
* For Sierra ≥ 1.7.0, computation is measured in [Sierra gas](/learn/protocol/fees#sierra-gas)
* For CairoZero classes or Sierra ≤ 1.6.0, computation is measured in [VM resources](/learn/protocol/fees#vm-resources)
<Note>
Sierra gas is only tracked if the parent call was also tracking Sierra gas, which means that if the account contract is Sierra 1.6.0 or older, VM resources will be tracked **throughout the entire transaction**. This condition may be relaxed in the future.
</Note>
#### Sierra gas
<Tip>
The following is a very rough description of Sierra's built-in gas accounting mechanism. For a comprehensive analysis, see [*Analysis of the gas accounting algorithm of Cairo 1.0 by CryptoExperts*](https://github.com/starkware-libs/cairo/blob/main/docs/other/gas_blog_post.pdf).
</Tip>
A Sierra program has a simple structure: types and function declaration, followed by a sequence of applications of *libfuncs*, Sierra's basic logical units (similar to opcodes, e.g. `u8_add` is a libfunc).
The Cairo compiler defines a libfunc costs table, which is measured in “Sierra gas” and has a 1-1 ratio with L2 gas (i.e., a libfunc which costs 500 Sierra gas adds 500 to a transaction's overall L2 gas)
<Note>
Despite the 1-1 ratio between Sierra gas and L2 gas, L2 gas accounts for “everything L2”, while Sierra gas strictly deals with computation, hence the distinction in terminology.
</Note>
The cost of each libfunc is determined by its expanded CASM generated via the Sierra→CASM compiler based on a 100-1 ratio with Cairo steps (i.e., if a libfunc's assembly includes 10 Cairo steps, it will cost 1000 Sierra gas), while the costs of the various builtins are defined as follows:
| Builtin | Sierra gas cost |
| - | - |
| Range check | 70 |
| Pedersen | 4,050 |
| Poseidon | 491 |
| Bitwise | 583 |
| ECDSA | 10,561 |
| EC\_OP | 4,085 |
| Keccak | 136,189 |
| ADD\_MOD | 230 |
| MUL\_MOD | 604 |
<Tip>
To review pricing for various syscalls, see the `versioned constants.json` files in the [sequencer's resources directory](https://github.com/starkware-libs/sequencer/tree/main/crates/blockifier/resources).
</Tip>
To handle gas usage, Sierra h프로젝트로 돌아가기