Starknet 백서

Starknet

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 67쪽

as special libfuncs for gas-handling, such as the `withdraw_gas` libfunc. For functions with neither branching nor recursion, the Cairo→Sierra compiler adds a single `withdraw_gas(C)` call in the beginning of the function, where `C` is the sum over the costs of the libfuncs included in the function. For functions with branching, the compiler adds a call to `withdraw_gas(C)` before the actual branching, where `C` is the maximal branch cost. <Note> In its latest version, the compiler also adds a call to `redeposit_gas(C)` on the cheaper branches, where `C` is unused gas on that branch. </Note> For functions with recursion (or other cases where costs can only be known in runtime), things get trickier. The naive way to handle such cases would be to add a `withdraw_gas` instruction after every libfunc, but since `withdraw_gas` itself has some cost (decreasing a counter and handling the insufficient gas case) this would incur a large burden on the program. Instead, the compiler constructs the call graph induced by the program, and asserts that every cycle includes a `withdraw_gas(X)` instruction, where `X` should cover the cost of a single run through the cycle, greatly reducing the overhead compared to the naive mechanism. #### VM resources A Cairo program execution yields an execution trace, and when proving a Starknet block, we aggregate all the transactions appearing in that block to the execution trace up to some maximal length $L$, derived from the specs of the proving machine and the desired proof latency. Tracking the execution trace length associated with each transaction is simple, as Cairo step requires the same constant number of trace cells. Therefore, in a world without builtins, the fee associated with the L2 computation component of a transaction $t x$ should be correlated with $\text{TraceCells} \left[\right. t x \left]\right. / L$. <Note> The aforementioned observation is no longer true for Starknet's next-gent prover S-two, which handles some opcodes more efficiently than others. However, we neglect this intricacy for the purposes of this discussion. </Note> When we introduce builtins into the equation, we need to consider an a priori limit for each builtin in the proof. This set of limits is known as the proof's *layout*, which determines the ratio between steps and each builtin. <Note> Today, Starknet's prover is able to dynamically choose a layout based on a given block resource's consumption, i.e. there is no longer an a priori fixed layout. However, pricing for old classes still behaves as if we are using a fixed layout. </Note> For example, consider that the prover can process a trace with the following limits: <table> <tr> <td> Up to 500M Cairo steps </td> <td> Up to 20M Pedersen hashes </td> <td> Up to 4M signature verifications </td> <td> Up to 10M range checks </td> </tr> </table> which means that a proof is closed and sent to L1 when any of these slots is filled. Now, suppose that a transaction uses 10K Cairo steps and 500 Pedersen hashes. At most 20M/500 = 40K such transactions can fit into the hypothetical trace, therefore its gas price should correlate with 1/40K of the cost of submitting proof (notice that this estimate ignores the number of Cairo steps as it is not the limiting factor, since 500M/10K > 20M/500). With this example in mind, it is possible to formulate the exact fee associated with L2 computation. For each transaction, the sequencer calculates a vector, `CairoResourceUsage`, that contains the following: * The number of Cairo steps * The number of applications of each Cairo builtin (e.g., 5 range checks and 2 Pedersen hashes) and crosses this information with a `CairoResourceFeeWeights` vector, a predefined weights vector in accordance with the proof parameters, in which each resource type has an entry that specifies the relative gas cost of that component in the proof. The sequencer then charges only according to the limiting factor, making the final fee defined by: $\underset{k}{max} \left[\right. \text{CairoResourceUsage}_{k} \cdot \text{CairoResourceFeeWeights}_{k} \left]\right.$ where $k$ enumerates the Cairo resource components. Going back to the above example, if the cost of submitting a proof with 20M Pedersen hashes is roughly 5M gas, then the weight of the Pedersen builtin is 5,000,000/20,000,0000 = 25 gas per application. #### VM resources vs. Sierra gas The difference in tracking Sierra gas vs. tracking VM resources can be summed up as follows: * For VM resources builtin weights reflect the proof layout, while for Sierra gas they reflect trace cell consumption * For VM resources only the maximal resource (e.g., most used builtin) is considered, while for Sierra gas the sum of all resources (i.e., all libfuncs) is considered This means that when the tracking Sierra gas, step-heavy transactions will most likely be slightly more expensive, as builtins will be taken into account *in addition* to Cairo steps. On the other hand, builtin-heavy transactions will become much cheaper — depending on the builtin that maximized the old fee and with the exception of the Pedersen builtin. ### L1 data #### Storage updates Whenever a transaction updates some value in the storage of some contract, the following data is sent to L1: * One 32-bye word if the transaction is a `DEPLOY` transaction (since we need to specify the deployed contract's class hash) * Two 32-byte words per contract * Two 32-byte words for every updated storage value <Note> Only the most recent value reaches L1, making the transaction's fee depend on the number of *unique* storage updates. If the same storage cell is updated multiple times within the transaction, the fee remains that of a single update. For information on the exact data and its construction, see [Data availability](/learn/protocol/data-availability#v0-11-0). </Note> Therefore, the storage update fee for a transaction is defined as follows: $$ \text{data}_{\text{gas price}} \cdot \text{felt}_{\text{size in bytes}} \cdot \left( \ell + 2(n - 1) + 2(m - 1) + 2D \right) $$ <Note> This formula only refer to the case of submitting data to L1 via blobs, for the calldata case, see [Overall fee](/learn/protocol/fees#overall-fee)). </Note> where: * $\text{felt}_{\text{size in bytes}}$ is 32, which is the number of bytes required to encode a single STARK field element. * $ℓ$ is the number of contracts whose class was changed, which happens on contract deployment and when applying the `replace_class` syscall. * $n$ is the number of unique contracts updated, 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 ℓ$. Notice that $n \geq 1$ always holds, because the fee token contract is always updated, which does not incur any fee. * $m$ is the number of values updated, not counting multiple updates for the same key. Notice that $m \geq 1$ always holds, because the sequencer's balance is always updated, which does not incur any fee. * $D$ is 1 if the transaction is of type `DECLARE` and 0 otherwise. Declare transactions need to post on L1 the new class hash and compiled class hash which are added to the state. <Note> Improvements to the above pessimistic estimation might be gradually implemented in future versions of Starknet. For example, if different transactions within the same block update the same storage cell, there is no need to charge for both transactions, because only the last value reaches L1. In the future, Starknet might include a refund mechanism for such cases. </Note> #### L2→L1 messages When a transaction that raises the `send_message_to_l1` syscall is included in a state update, the following data reaches L1: * L2 sender address * L1 destination address * Payload size * Payload (list of field elements) Therefore, the gas cost associated with a single L2→L1 message is defined as follows: $$ \text{message}_{\text{calldata cost}} \cdot \left( 3 + \text{payload}_{\text{size}} \right) + \text{l1}_{\text{log data cost}} \cdot \text{payload}_{\text{size}} + \text{log}_{\text{message to l1 cost}} + \text{l1}_{\text{storage write cost}} $$ Where: * $\text{message}_{\text{calldata cost}}$ is 1,124 gas, which is the sum of 512 gas for submitting the state update to the core contract and 612 gas for submitting the state update to the verifier contract (which incurs \~100 additional gas for hashing) * $\text{l1}_{\text{log data cost}}$ is 256 gas, paid for every payload element during the emission of the `LogMessageToL1` event * $\text{log}_{\text{message to l1 cost}}$ is 1,637 gas, which is the fixed cost involved in emitting a `LogMessageToL1` event with two topics and a two-word data array, resulting in a total of\ $375 + 2 \cdot 375 + 2 \cdot 256$ gas (log opcode cost, topics cost, and data array cost) * $\text{l1}_{\text{storage write cost}}$ is 20K gas per message, paid in order to store the message hash on the Starknet core contract and enable the target L1 contract to consume the message ### L2 data L2 data composes of: * Calldata, including transaction calldata (in the case of `INVOKE` transactions or `L1_HANDLER`), constructor calldata (in the case of `DEPLOY_ACCOUNT` transactions), and signatures * Events, including data and keys of emitted events * ABI, including classes ABI in `DECLARE` transactions (only relevant for `DECLARE` transactions of version ≥ 2) * Casm bytecode (for all available `DECLARE` transactions, where in version \< 2 this refers to the compiled class) * Sierra bytecode (relevant only for `DECLARE` transactions of version ≥ 2) The L1 gas cost of each component in as follows: <Note> When a transaction's L2 cost is paid for by L2 gas, the following numbers are translated via the standard conversion rate of 1 L1 gas = 40K L2 gas. </Note> | Resource | L2 Gas cost | | - | - | | Event key | 10,240 gas/felt | | Event data | 5,120 gas/felt | | Calldata | 5,120 gas/felt | | CASM bytecode | 40,000 gas/felt | | Sierra bytecode | 40,000 gas/felt | | ABI | 1,280 gas/character | # Introduction to Starknet's protocol Source: https://docs.starknet.io/learn/protocol/intro Starknet is a decentralized, permissionless Layer 2 (L2) validity rollup that scales Ethereum by utilizing STARK-based zero-knowledge proofs to bundle thousands of transactions off-chain for verified settlement on the mainnet. As of 2026, the network evolved into a privacy-centric hub with the launch of the [STRK20](/build/starkzap/privacy/strk20) framework, which allows assets like stablecoins to maintain confidential balances and transfers while remaining regulatory-compliant. ## User interactions As with other blockchains, users interact with Starknet by sending [transactions](/learn/protocol/transactions/) from their [account](/learn/protocol/accounts/). On Starknet, accounts are smart contracts, a model known as native account abstraction. This allows for flexible authorization logic such as multisig, session keys, or passkey-based authentication — all without changes to the protocol itself. The transactions users send are usually invoke transactions, which essentially contain a list of \[(contract, selector, parameters)] for execution. Notice that multicall is thus natively supported on Starknet. For more details on invoke transactions as well as rarer types such as declare, see [transactions](/learn/protocol/transactions/) Some transactions may involve communication between Ethereum and Starknet (or even be initiated by an Ethereum transaction), and are handled through [L1↔L2 messaging](/learn/protocol/messaging/). An example is deposits to Starknet from Ethereum through secure bridges such as [StarkGate](/learn/protocol/starkgate/). ## Block production and validation Transactions are arriving in the Starknet sequencer's mempool, and from there are collected and ordered into [blocks](/learn/protocol/blocks/). To ensure that state transitions are valid, Starknet uses [SHARP](/learn/protocol/sharp/) to generate and aggregate proofs that running the [SNOS](/learn/protocol/snos/) program on the set of the block's transactions indeed yields the Starknet state at the end of the block. These proofs (with further proof aggregation, happening inside SHARP), compress many blocks' execution into a succinct artifact, which is submitted to Ethereum to be verified, so that Starknet's execution can be trusted without re-running it. Starknet also ensures access to the data used in the computation via [data availability](/learn/protocol/data-availability/), publishing compressed state diffs to Ethereum so the full state can be reconstructed and verified. ## Tokenomics and consensus [STRK](/learn/protocol/strk/), Starknet's native token, is used to pay [fees](/learn/protocol/fees/) for transaction execution. Minimal fee level is set to cover the cost of using network resources. STRK is also used to power Starknet's [staking protocol](/learn/protocol/staking/), where STRK stakers help secure the sequencing layer and validate block production. This mechanism is designed to support decentralization and provide economic guarantees around block inclusion and ordering. ## Summary All together, these elements form a tightly integrated protocol, enabling scalable and expressive applications with low fees and strong security — all without compromising on decentralization or alignment with Ethereum. Now that you've got the big picture, put on your goggles and deep dive into whichever concept or component intrigues you most! 🤿 # L1 ↔ L2 messaging Source: https://docs.starknet.io/learn/protocol/messaging ## Overview Starknet's ability to interact with L1 is crucial, and is used by bridges (e.g., for depositing your tokens in the L1 bridge contract, and automatically triggers the minting of the same token on L2), [DeFi pooling](https://starkware.co/resource/defi-pooling/) and [more](https://www.starknet.io/en/ecosystem/dapps). Messaging — both [from L1 to L2](/learn/protocol/messaging#l2-→-l1-messages) and from [L2 to L1](/learn/protocol/messaging#l2-→-l1-message-protocol) — is the mechanism that enables this interaction. <Warning> Starknet's messaging mechanism is both *asynchronous* and *asymmetric*. * *Asynchronous*: Your contract code, whether Cairo or Solidity, cannot await the result of the message being sent on the other layer within your contract code's execution. * *Asymmetric*: Sending a message from Ethereum to Starknet, L1→L2, is fully automated by the Starknet sequencer, so the message is automatically delivered to the target contract on L2. However, when sending a message from Starknet to Ethereum, L2→L1, the sequencer only sends the hash of the message. You must then consume the message manually using a transaction on L1. </Warning> Additional resources * [The `send_message_to_L1` syscall](https://book.cairo-lang.org/appendix-08-system-calls.html#send_message_to_l1) * [The Starknet Core contract's `sendMessageToL2` function](https://github.com/starkware-libs/cairo-lang/blob/54d7e92a703b3b5a1e07e9389608178129946efc/src/starkware/starknet/solidity/IStarknetMessaging.sol#L13) * [L1-L2 Messaging in the Cairo Book](https://book.cairo-lang.org/ch16-04-L1-L2-messaging.html) ## L2 → L1 messages ### L2 → L1 message protocol The L2 → L1 message protocol consists of the following stages: 1. During the execution of a transaction, a contract on Starknet sends a message from L2 to L1 by calling the `send_message_to_L1` syscall. 2. The sequencer attaches the message parameters to the block that includes the syscall invocation. The message parameters include the address of the sender on L2, the address of the recipient contract on L1, and the message data. For example: ```cairo theme={null} let mut payload: Array<felt252> = ArrayTrait::new(); let to_address: EthAddress = 1_felt252.try_into().unwrap(); payload.append(1); // potentially add more elements to payload (payload[1], payload[2], etc.) send_message_to_l1_syscall(to_address: to_address.into(), payload: payload.span()); ``` 3. The prover proves the state update that includes this transaction. 4. The sequencer updates the L1 state. 5. The message is stored on L1 in the Starknet Core Contract and a counter on the Core Contract increases by one. 6. The `processMessage` function, which is part of the Starknet Core Contract, emits the `LogMessageToL1` event, which contains the message parameters. 7. The message recipient on L1 can access and consume the message by calling the [`consumeMessageFromL2`](https://github.com/starkware-libs/cairo-lang/blob/4e233516f52477ad158bc81a86ec2760471c1b65/src/starkware/starknet/eth/StarknetMessaging.sol#L119) function, which includes the message parameters within the transaction. This function, which is part of the Starknet Core Contract, verifies the following: * The hashes of the L2 sent message parameters, now stored on the Core Contract, and the L1 received message parameters, are the same. * The entity calling the function is indeed the recipient on L1. In such a case, the counter corresponding to the message hash in the Starknet Core Contract decreases by one. For more information, see the [`consumeMessageFromL2`](https://github.com/starkware-libs/cairo-lang/blob/4e233516f52477ad158bc81a86ec2760471c1b65/src/starkware/starknet/eth/StarknetMessaging.sol#L130C7-L130C7#) function in `StarknetMessaging.sol`. The protocol is summarized in the following illustration: <Frame> <img /> </Frame> ### L2 → L1 message structure The structure of an L2 → L1 message is defined under `MSG_TO_L1` in the [Starknet API JSON RPC](https://github.com/starkware-libs/starknet-specs/blob/master/api/starknet_api_openrpc.json) specification as follows: | | | | - | - | | `from_address` (`felt252`) | The address of the L2 contract sending the message. | | `to_address` (`EthAddress`) | The target L1 address the message is sent to. | | `payload` (`Array<felt252>`) | The payload of the message. | ### L2 → L1 message hashing The hash of an L2 → L1 message is computed on L1 as follows: ``` keccak256( abi.encodePacked( FromAddress, uint256(ToAddress), Payload.length, Payload ) ); ``` <Note> Sending an L2 to L1 message always incurs a fixed cost of 20,000 L1 gas, because the hash of the message being sent must be written to L1 storage in the Starknet Core Contract. </Note> ## L1 → L2 messages ### L1 → L2 message protocol The L1 → L2 message protocol consists of the following stages: 1. An L1 contract induces a message to an L2 contract on Starknet by calling the [`sendMessageToL2`](https://github.com/starkware-libs/cairo-lang/blob/54d7e92a703b3b5a1e07e9389608178129946efc/src/starkware/starknet/solidity/IStarknetMessaging.sol#L13) function on the Starknet Core Contract with the message parameters. The Starknet Core Contract hashes the message parameters and updates the L1→L2 message mapping to indicate that a message with this hash was indeed sent. The L1 contract records the fee that the sender paid. For more information, see [L1 → L2 message fees](#l1-l2-message-fees). 2. The message is then decoded into a Starknet transaction that invokes a function annotated with the `l1_handler` decorator on the target contract. Transactions like this on L2 are called [L1 handler transactions](#l1_handler_transaction). 1. The Starknet sequencer, upon receiving enough L1 confirmations for the transaction that sent the message, initiates the corresponding L2 transaction. 2. The L2 transaction invokes the relevant `l1_handler` function. 3. The L1 Handler transaction that was created in the previous step is added to a proof. 4. The Core Contract receives the state update. 5. The message is cleared from the Core Contract's storage to consume the message. Clearing the Core Contract's storage does the following: * incurs a fixed cost of 5,000 L1 gas * emits an L1 event logging the m
프로젝트로 돌아가기