<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by xiaohuo ren on Medium]]></title>
        <description><![CDATA[Stories by xiaohuo ren on Medium]]></description>
        <link>https://medium.com/@xiaohuo200?source=rss-51731e1d4599------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UiOMQjJs0NVvpLwB</url>
            <title>Stories by xiaohuo ren on Medium</title>
            <link>https://medium.com/@xiaohuo200?source=rss-51731e1d4599------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:09:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xiaohuo200/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Arbitrum Orbit — transaction lifecycle #1]]></title>
            <link>https://medium.com/@xiaohuo200/arbitrum-orbit-transaction-lifecycle-1-b25aa18b230d?source=rss-51731e1d4599------2</link>
            <guid isPermaLink="false">https://medium.com/p/b25aa18b230d</guid>
            <category><![CDATA[orbit]]></category>
            <category><![CDATA[rollup]]></category>
            <category><![CDATA[altlayer]]></category>
            <category><![CDATA[arbitrum]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[xiaohuo ren]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 17:55:38 GMT</pubDate>
            <atom:updated>2024-04-28T17:57:49.344Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arbitrum Orbit — transaction lifecycle #1</h3><p>Arbitrum official has a very nice overview doc for this topic, you might just skip this one and go to check <a href="https://docs.arbitrum.io/tx-lifecycle">https://docs.arbitrum.io/tx-lifecycle</a> directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*r7KfzL77tSM8bul8.jpeg" /></figure><p><strong>How your transaction get accepted</strong></p><p>Basically it is sequencer who constantly receives transactions, but with two forms:</p><ol><li>offchain method, one can send transaction to sequencer rpc, or fullnode rpc, the latter one just forward any upcoming transactions to sequencer. Either one implemented standard ethereum json-rpc you can check here: <a href="https://ethereum.org/en/developers/docs/transactions/">https://ethereum.org/en/developers/docs/transactions/</a>. You may wonder why orbit node has the capability that server ethereum rpcs: simply because orbit node is some kind of wrapper of go-ethereum: <a href="https://github.com/OffchainLabs/nitro/blob/master/arbnode/node.go#L252">https://github.com/OffchainLabs/nitro/blob/master/arbnode/node.go#L252</a> there is no much difference here</li><li>on-chain method, or from parent chain (depends on where your orbit chain lives, it may come from l2 arbitrum or l1 ethereum). That might sounds like a magic for you, how come you can send l2/l3 transaction via l1/l2 rpc? This is because EVM transaction essentially just a signed payload, or more general, a byte array. As long the sequencer can get that payload, it can be submitted via orbit chain rpc, or you can send it (with a specific prefix to indicate transaction type) to delayed inbox <a href="https://github.com/OffchainLabs/nitro-1/blob/fc2dab11320831e85a40d9f6bd11a2b8bd146d7f/contracts/src/bridge/Inbox.sol#L147">https://github.com/OffchainLabs/nitro-1/blob/fc2dab11320831e85a40d9f6bd11a2b8bd146d7f/contracts/src/bridge/Inbox.sol#L147</a> Your sequencer will get it and execute it as well.</li></ol><p>At this point, you are trusting the sequencer in submitting your transaction later (in a batch) to parent chain, even you get some transaction receipt and it feels like your transaction has been confirmed immediately.</p><p><strong>How batch poster works</strong></p><p>Recall the introduction article on nitro/orbit node <a href="https://medium.com/@xiaohuo200/arbitrum-orbit-introduction-nitro-contracta-and-node-605723fb2ea1">https://medium.com/@xiaohuo200/arbitrum-orbit-introduction-nitro-contracta-and-node-605723fb2ea1</a> There is a node type called “batch poster” that collects transactions, put them in some batches, and push batch data to parent chain as `calldata`, or to any DAC (and then push data pointer from DAC to parent chain).</p><p><strong>SHOW YOU CODE</strong></p><p>While a batch poster is running, the function `maybePostSequencerBatch` is called in a fixed interval (nitro uses a function CallIteratively to achieve that, conceptually it is a timer)</p><pre>b.CallIteratively(func(ctx context.Context) time.Duration {<br>  var err error<br>  if common.HexToAddress(b.config().GasRefunderAddress) != (common.Address{}) {<br>   gasRefunderBalance, err := b.l1Reader.Client().BalanceAt(ctx, common.HexToAddress(b.config().GasRefunderAddress), nil)<br>   if err != nil {<br>    log.Warn(&quot;error fetching batch poster gas refunder balance&quot;, &quot;err&quot;, err)<br>   } else {<br>    batchPosterGasRefunderBalance.Update(arbmath.BalancePerEther(gasRefunderBalance))<br>   }<br>  }<br>  if b.dataPoster.Sender() != (common.Address{}) {<br>   walletBalance, err := b.l1Reader.Client().BalanceAt(ctx, b.dataPoster.Sender(), nil)<br>   if err != nil {<br>    log.Warn(&quot;error fetching batch poster wallet balance&quot;, &quot;err&quot;, err)<br>   } else {<br>    batchPosterWalletBalance.Update(arbmath.BalancePerEther(walletBalance))<br>   }<br>  }<br>  couldLock, err := b.redisLock.CouldAcquireLock(ctx)<br>  if err != nil {<br>   log.Warn(&quot;Error checking if we could acquire redis lock&quot;, &quot;err&quot;, err)<br>   // Might as well try, worst case we fail to lock<br>   couldLock = true<br>  }<br>  if !couldLock {<br>   log.Debug(&quot;Not posting batches right now because another batch poster has the lock or this node is behind&quot;)<br>   b.building = nil<br>   resetAllEphemeralErrs()<br>   return b.config().PollInterval<br>  }<br>  posted, err := b.maybePostSequencerBatch(ctx)</pre><p>inside `maybePostSequencerBatch` there are several steps to be noted:</p><p><em>Get batch poster’s nonce, and batch position</em></p><pre>nonce, batchPositionBytes, err := b.dataPoster.GetNextNonceAndMeta(ctx)<br> if err != nil {<br>  return false, err<br> }<br> var batchPosition batchPosterPosition<br> if err := rlp.DecodeBytes(batchPositionBytes, &amp;batchPosition); err != nil {<br>  return false, fmt.Errorf(&quot;decoding batch position: %w&quot;, err)<br> }</pre><p>Ultimately batch poster need to send transaction to parent chain, so it is natural we get its nonce here.</p><p>batchPosterPosition is a simple struct here</p><pre>type batchPosterPosition struct {<br> MessageCount        arbutil.MessageIndex<br> DelayedMessageCount uint64<br> NextSeqNum          uint64<br>}</pre><p>`NextSeqNum` indicats the next batch number we want to post to parent chain.</p><p>`MessageCount` is something very similar to Block, actually there is a simple formula: orbit block num = message count + parent chain block num when orbit chain got genesised</p><p><em>Check batch count</em></p><pre>dbBatchCount, err := b.inbox.GetBatchCount()<br> if err != nil {<br>  return false, err<br> }<br> if dbBatchCount &gt; batchPosition.NextSeqNum {<br>  return false, fmt.Errorf(&quot;attempting to post batch %v, but the local inbox tracker database already has %v batches&quot;, batchPosition.NextSeqNum, dbBatchCount)<br> }</pre><p>so here we get batch count from local inbox (the data originated from Inbox contract on parent chain), to make sure the batch poster is not posting some historical data.</p><p><em>Check message count</em></p><p>Besides, we also check message count here, make sure there is something to post:</p><pre>msgCount, err := b.streamer.GetMessageCount()<br> if err != nil {<br>  return false, err<br> }<br> if msgCount &lt;= batchPosition.MessageCount {<br>  // There&#39;s nothing after the newest batch, therefore batch posting was not required<br>  return false, nil<br> }</pre><p><em>hasL1Bound</em></p><p>We ignore this in this post, will explain it in detail in another one.</p><p><em>Build segments</em></p><pre>for b.building.msgCount &lt; msgCount {<br>  msg, err := b.streamer.GetMessage(b.building.msgCount)<br>  if err != nil {<br>   log.Error(&quot;error getting message from streamer&quot;, &quot;error&quot;, err)<br>   break<br>  }<br> ...<br>  success, err := b.building.segments.AddMessage(msg)<br>  if err != nil {<br>   // Clear our cache<br>   b.building = nil<br>   return false, fmt.Errorf(&quot;error adding message to batch: %w&quot;, err)<br>  }<br>  if !success {<br>   // this batch is full<br>   if !config.WaitForMaxDelay {<br>    forcePostBatch = true<br>   }<br>   b.building.haveUsefulMessage = true<br>   break<br>  }<br>  if msg.Message.Header.Kind != arbostypes.L1MessageType_BatchPostingReport {<br>   b.building.haveUsefulMessage = true<br>  }<br>  b.building.msgCount++<br> }<br>sequencerMsg, err := b.building.segments.CloseAndGetBytes()</pre><ol><li>get message from streamer</li><li>include message into segments</li><li>close segments and get bytes</li></ol><p><em>DAC</em></p><pre>if b.daWriter != nil {<br>  if !b.redisLock.AttemptLock(ctx) {<br>   return false, errAttemptLockFailed<br>  }<br><br>  gotNonce, gotMeta, err := b.dataPoster.GetNextNonceAndMeta(ctx)<br>  if err != nil {<br>   return false, err<br>  }<br>  if nonce != gotNonce || !bytes.Equal(batchPositionBytes, gotMeta) {<br>   return false, fmt.Errorf(&quot;%w: nonce changed from %d to %d while creating batch&quot;, storage.ErrStorageRace, nonce, gotNonce)<br>  }<br><br>  cert, err := b.daWriter.Store(ctx, sequencerMsg, uint64(time.Now().Add(config.DASRetentionPeriod).Unix()), []byte{}) // b.daWriter will append signature if enabled<br>  if errors.Is(err, das.BatchToDasFailed) {<br>   if config.DisableDasFallbackStoreDataOnChain {<br>    return false, errors.New(&quot;unable to batch to DAS and fallback storing data on chain is disabled&quot;)<br>   }<br>   log.Warn(&quot;Falling back to storing data on chain&quot;, &quot;err&quot;, err)<br>  } else if err != nil {<br>   return false, err<br>  } else {<br>   sequencerMsg = das.Serialize(cert)<br>  }<br> }</pre><p>once we have the raw batch data here, we can send it to parent chain directly, or if we have a DAC running e.g. Anytrust, we can send the raw data to DAC first, get some certification, and serialize it as new data to be posted.</p><p><em>4844</em></p><pre> data, kzgBlobs, err := b.encodeAddBatch(new(big.Int).SetUint64(batchPosition.NextSeqNum), batchPosition.MessageCount, b.building.msgCount, sequencerMsg, b.building.segments.delayedMsg, b.building.use4844)</pre><pre>if use4844 {<br>  kzgBlobs, err = blobs.EncodeBlobs(l2MessageData)<br>  if err != nil {<br>   return nil, nil, fmt.Errorf(&quot;failed to encode blobs: %w&quot;, err)<br>  }<br>  // EIP4844 transactions to the sequencer inbox will not use transaction calldata for L2 info.<br>  calldata, err = method.Inputs.Pack(<br>   seqNum,<br>   new(big.Int).SetUint64(delayedMsg),<br>   b.config().gasRefunder,<br>   new(big.Int).SetUint64(uint64(prevMsgNum)),<br>   new(big.Int).SetUint64(uint64(newMsgNum)),<br>  )<br> } else {<br>  calldata, err = method.Inputs.Pack(<br>   seqNum,<br>   l2MessageData,<br>   new(big.Int).SetUint64(delayedMsg),<br>   b.config().gasRefunder,<br>   new(big.Int).SetUint64(uint64(prevMsgNum)),<br>   new(big.Int).SetUint64(uint64(newMsgNum)),<br>  )<br> }</pre><p>If the chain enable 4844, the batch data would be posted as blob, otherwise it is posted as calldata.</p><p><em>Last stage: send transaction out</em></p><pre>accessList := b.accessList(int(batchPosition.NextSeqNum), int(b.building.segments.delayedMsg))<br> // On restart, we may be trying to estimate gas for a batch whose successor has<br> // already made it into pending state, if not latest state.<br> // In that case, we might get a revert with `DelayedBackwards()`.<br> // To avoid that, we artificially increase the delayed messages to `lastPotentialMsg.DelayedMessagesRead`.<br> // In theory, this might reduce gas usage, but only by a factor that&#39;s already<br> // accounted for in `config.ExtraBatchGas`, as that same factor can appear if a user<br> // posts a new delayed message that we didn&#39;t see while gas estimating.<br> gasLimit, err := b.estimateGas(ctx, sequencerMsg, lastPotentialMsg.DelayedMessagesRead, data, kzgBlobs, nonce, accessList)<br> if err != nil {<br>  return false, err<br> }<br> newMeta, err := rlp.EncodeToBytes(batchPosterPosition{<br>  MessageCount:        b.building.msgCount,<br>  DelayedMessageCount: b.building.segments.delayedMsg,<br>  NextSeqNum:          batchPosition.NextSeqNum + 1,<br> })<br> if err != nil {<br>  return false, err<br> }<br> tx, err := b.dataPoster.PostTransaction(ctx,<br>  firstMsgTime,<br>  nonce,<br>  newMeta,<br>  b.seqInboxAddr,<br>  data,<br>  gasLimit,<br>  new(big.Int),<br>  kzgBlobs,<br>  accessList,<br> )</pre><p>So here we call estimateGas before we actually send it out.</p><p>By now we have our batch data posted to parent chain (or DAC). Next we will go though how validator make assertion, how the batch data become valid or under a challenge if there is something wrong.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b25aa18b230d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deterministic deployment and EIP155]]></title>
            <link>https://medium.com/@xiaohuo200/deterministic-deployment-and-eip155-d70b816e3384?source=rss-51731e1d4599------2</link>
            <guid isPermaLink="false">https://medium.com/p/d70b816e3384</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[safe]]></category>
            <dc:creator><![CDATA[xiaohuo ren]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 17:16:15 GMT</pubDate>
            <atom:updated>2024-04-27T17:16:15.728Z</atom:updated>
            <content:encoded><![CDATA[<p>A short article for explaining how deterministic deployment works and things we need pay attention on with EIP155.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fR26HFYKPiZ-GxNG1-oxng.jpeg" /></figure><p><strong>Deterministic Deployment</strong></p><p>The initial idea comes from <a href="https://github.com/Arachnid/deterministic-deployment-proxy">https://github.com/Arachnid/deterministic-deployment-proxy</a>, we can ensure that a given contract will exist at the exact same address on every EVM-Compatible chain by:</p><ol><li>prepare a fresh EOA account as signer</li><li>use the signer private key pre-sign a payload (take <a href="https://github.com/Arachnid/deterministic-deployment-proxy">Arachnid</a> repo as a example here, actually we can make our own proxy contract and generate our own pre-signed payload) 0xf8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222</li><li>whenever one submit the payload from #2 to any EVM-Compatible chain e.g. using `cast publish`, it deploys a simple Proxy contract that can be used to deploy other contracts using Create2, source code here: <a href="https://github.com/Arachnid/deterministic-deployment-proxy/blob/master/source/deterministic-deployment-proxy.yul">https://github.com/Arachnid/deterministic-deployment-proxy/blob/master/source/deterministic-deployment-proxy.yul</a></li><li>With Create2 <a href="https://eips.ethereum.org/EIPS/eip-1014">https://eips.ethereum.org/EIPS/eip-1014</a> as long we provide a same salt and a same bytecode for contract about to be deployed, the calculated and actual address would always remain the same across different EVM chains</li></ol><p><strong>EIP155 and Replay Attack Protection</strong></p><p>Things would be a bit subtle if your chain apply EIP155 <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md">https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md</a></p><p>Since the signed transaction payload need a chain id now, the pre-signed transaction for deploying Proxy contract would be different for different chains. To solve this, one idea we can borrow from gnosis safe <a href="https://github.com/safe-global/safe-singleton-factory/tree/main">https://github.com/safe-global/safe-singleton-factory/tree/main</a> is:</p><ol><li>for any EVM chain we can generate a specific pre-signed payload using the same signer account</li><li>submit it to that chain</li></ol><p>The idea quite trivial but it also brings us an extra benefice: we can adjust gas fee and gas limit as well for different chains now. check <a href="https://github.com/safe-global/safe-singleton-factory/tree/main/artifacts">https://github.com/safe-global/safe-singleton-factory/tree/main/artifacts</a> as example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d70b816e3384" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EigenLayer Contract Introduction #2— Middleware]]></title>
            <link>https://medium.com/@xiaohuo200/eigenlayer-contract-introduction-2-middleware-9d43e9ddfbf2?source=rss-51731e1d4599------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d43e9ddfbf2</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[rollup]]></category>
            <category><![CDATA[staking]]></category>
            <category><![CDATA[eigenlayer]]></category>
            <dc:creator><![CDATA[xiaohuo ren]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 05:02:37 GMT</pubDate>
            <atom:updated>2024-04-25T07:33:08.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>EigenLayer Contract Introduction #2 — Middleware</h3><p>DISCLAIMER #1 : 本文基于公开仓库和文档进行编译，不涉及任何商业机密和投资建议，仅供学习交流使用</p><p>DISCLAIMER #2: 不保证语句通顺，纠错和反馈请联系 wechat: xiaohuo0x or telegram: @xiaohuo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hsobrw5yliCjPBy3.png" /></figure><p><a href="https://medium.com/@xiaohuo200/eigenlayer-contract-introduction-8f2a5d250bff">https://medium.com/@xiaohuo200/eigenlayer-contract-introduction-8f2a5d250bff</a> 这篇主要讲解了 EigenLayer Core Contract 的总体逻辑和设计，这一篇主要讲解 EigenLayer Middleware Contract 以及其如何赋能 AVS 项目方，以及简化 AVS 合约的研发（同时也意味着更高的安全性和更小的审计成本）。</p><p><strong>EigenLayer Middleware Components</strong></p><p>EigenLayer 把 AVS 的功能抽象成以下几部分：</p><ol><li>BLSApkRegistry： 负责追踪各个 operator 的 BLS public key 以及聚合 key</li><li>IndexRegistry：负责维护有顺序的 operator list （for each quorum）</li><li>StakeRegistry：负责追踪每个 operator 的 stakes 数目以及总数 （for each quorum）</li><li>RegistryCoordinator：入口合约</li><li>OperatorStateRetriever：状态读取合约(数据来源为上述几个 registry)</li><li>ServiceManagerBase AVS 业务逻辑的最小实现，AVS 项目方真正需要编写的业务合约 ServiceManager 最好是直接继承该抽象合约</li></ol><p><strong>RegistryCoordinator</strong></p><p>为了更好的理解 EigenLayer Middleware 和 Registry 体系，我们可以从 RegistryCoordinator 入手。</p><p>首先看它的构造方法：</p><pre>constructor(<br>    IServiceManager _serviceManager,<br>    IStakeRegistry _stakeRegistry,<br>    IBLSApkRegistry _blsApkRegistry,<br>    IIndexRegistry _indexRegistry<br>)</pre><p>可以看到，作为入口合约，它记录了所有其他 registry 合约以及业务合约 service manager 的地址，相应的在 RegistryCoordinatorStorage 中它们都是以 immutable 的形式直接和合约代码存储在一起而不占用 storage 空间，这样设计的好处是初始化和升级会比较方便，storage layout 也会比较简洁。</p><p>作为 <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/transparent/TransparentUpgradeableProxy.sol">TransparentUpgradeableProxy</a> 的通用范式，我们一般不在 constructor 方法中初始化 storage 变量，所有的初始化动作会在一个叫 initialize 的方法中进行：</p><pre>/**<br> * @param _initialOwner will hold the owner role<br> * @param _churnApprover will hold the churnApprover role, which authorizes registering with churn<br> * @param _ejector will hold the ejector role, which can force-eject operators from quorums<br> * @param _pauserRegistry a registry of addresses that can pause the contract<br> * @param _initialPausedStatus pause status after calling initialize<br> * Config for initial quorums (see `createQuorum`):<br> * @param _operatorSetParams max operator count and operator churn parameters<br> * @param _minimumStakes minimum stake weight to allow an operator to register<br> * @param _strategyParams which Strategies/multipliers a quorum considers when calculating stake weight<br> */<br>function initialize(<br>    address _initialOwner,<br>    address _churnApprover,<br>    address _ejector,<br>    IPauserRegistry _pauserRegistry,<br>    uint256 _initialPausedStatus,<br>    OperatorSetParam[] memory _operatorSetParams,<br>    uint96[] memory _minimumStakes,<br>    IStakeRegistry.StrategyParams[][] memory _strategyParams<br>) external initializer {<br>    require(<br>        _operatorSetParams.length == _minimumStakes.length &amp;&amp; _minimumStakes.length == _strategyParams.length,<br>        &quot;RegistryCoordinator.initialize: input length mismatch&quot;<br>    );<br><br>    // Initialize roles<br>    _transferOwnership(_initialOwner);<br>    _initializePauser(_pauserRegistry, _initialPausedStatus);<br>    _setChurnApprover(_churnApprover);<br>    _setEjector(_ejector);<br><br>    // Add registry contracts to the registries array<br>    registries.push(address(stakeRegistry));<br>    registries.push(address(blsApkRegistry));<br>    registries.push(address(indexRegistry));<br><br>    // Create quorums<br>    for (uint256 i = 0; i &lt; _operatorSetParams.length; i++) {<br>        _createQuorum(_operatorSetParams[i], _minimumStakes[i], _strategyParams[i]);<br>    }<br>}</pre><p>modifier initializer 保证了该方法最多只能被调用一次。讲一下这里的参数和其背后有关的设计：</p><ol><li>_initialOwner 比较容易理解，主要负责合约的治理，包括关键参数的修改，多数情况下我们应该用多签钱包去充当 owner 角色</li><li>_churnApprover 根据 EigenLayer 的设计，一个 AVS 中 operator 的数目一般会有一个上限值（受制于 BLS 的效率等现实因素）所以当 AVS 中 operator 数目达到该最大值之后，新的 operator 想加入网络必须得到 churn approver 的签名，之后再去调用 registerOperatorWithChurn 便可以将一个已经 opt-in 的 operator 踢出网络取而代之。churn approver 在签名前会做一些基本检查比如申请 opt-in 的 operator stake 数目等。</li><li>_ejector 比较暴力和中心化的角色，直接将 operator 从某个 quorum 踢出，一般用多签钱包</li><li>_pauserRegistry 暂停该 AVS 合约的角色，用于某些紧急情况下的治理</li><li>_initialPausedStatus 合约初始化之后的状态，应需而定</li><li>_operatorSetParams 设置每个 quorum 的 operator 集合参数，主要是最大 operator 数目和踢出规则，之所以是个数组是因为一个 AVS 可以由不同的 quorum 提供安全，一个 quorum（委员会）可以看成是一个子网络</li><li>_minimumStakes 也是一个数组，规定每个 quorum 最小 stake 数目</li><li>_strategyParams 一个 quorum 不仅仅可以选择由哪些 strategy 去 secure 也可以指定它们之前的权重，一般和各个 LST/LRT 的市场价格相关（后面可以单独出篇幅讲解）</li></ol><p><strong>Operator opt-in/opt-out</strong></p><p>当节点商（或个人）在 EigenLayer Core 那边注册为 operator 之后，他可以选择 opt-in 进某一个或者某些 AVS，主要是通过调用该 AVS 的 RegistryCoordinator 下面的方法：</p><pre>function registerOperator(<br>    bytes calldata quorumNumbers,<br>    string calldata socket,<br>    IBLSApkRegistry.PubkeyRegistrationParams calldata params,<br>    SignatureWithSaltAndExpiry memory operatorSignature<br>) external onlyWhenNotPaused(PAUSED_REGISTER_OPERATOR) {</pre><p>参数解释如下：</p><ol><li>quorumNumbers 希望 opt-in 的 quorum，每个字节代表一个 quorum id 因此理论上一个 AVS 可以有 256 个 quorum 但是合约有一个常量去限制 max quorum count 目前是 192</li><li>socket operator 的 IP/Domain</li><li>params operator 的 BLS Public Key 信息以及可以证明所有权的签名</li><li>operatorSignature 是调用 AVSDirectory.registerOperatorToAVS 所需要的参数，多数情况下 operator 在 opt-in 到某个 AVS 之前，已经在 EigenLayer Core 合约那边注册好了，所以在这里这个参数可以忽略</li></ol><p>opt-in 过程逻辑总体上不复杂：（_registerOperator）</p><ol><li>调用 _getOrCreateOperatorId 获取或者创建 operator id，即 operator 在该 AVS 的唯一标识；如果是第一次 opt-in 合约还会将该 operator 的 BLS Public Key 记录在 blsApkRegistry 中</li><li>前置检查，包括是否已经 opt-in 进某些 quorum，是否需要 forward registerOperatorToAVS 信息去 EigenLayer Core 合约那边</li><li>调用 serviceManager.registerOperatorToAVS 这部分逻辑由 AVS 自己定义，比如进行一些白名单的检查，但是一般会转发 operator 的信息去 avsDirectory 从而让 EigenLayer Core Contract 知道 该operator 注册到该 AVS 上</li><li>调用 blsApkRegistry.registerOperator 主要是更新 BLS Aggregate Key</li><li>调用 stakeRegistry.registerOperator 该方法会从 DelegationManager （详见 <a href="https://medium.com/@xiaohuo200/eigenlayer-contract-introduction-8f2a5d250bff">https://medium.com/@xiaohuo200/eigenlayer-contract-introduction-8f2a5d250bff</a>）将该 operator 的在每个 strategy 的 share 获取到，再根据 AVS 的权重配置（上面的 _strategyParams）进行计算，得到最终的 stake 数目，并以此判断 operator 是否满足 minimum stake 需求</li><li>调用 indexRegistry.registerOperator 记录该 operator 在 quorum 的位置信息</li></ol><pre>function registerOperatorWithChurn(<br>    bytes calldata quorumNumbers,<br>    string calldata socket,<br>    IBLSApkRegistry.PubkeyRegistrationParams calldata params,<br>    OperatorKickParam[] calldata operatorKickParams,<br>    SignatureWithSaltAndExpiry memory churnApproverSignature,<br>    SignatureWithSaltAndExpiry memory operatorSignature<br>) external onlyWhenNotPaused(PAUSED_REGISTER_OPERATOR) {</pre><p>上面提到过，每个 quorum 都会有一个 operator max count 一旦达到这个值，新的 operator 再想 opt-in 进去需要从 churn approve 获取一个签名（可以是程序化的）再将某一个 operator 踢出，不再赘述</p><p>opt-out 方法很简单，只需要提供相应的 quorum ids 就可以</p><pre> function deregisterOperator(bytes calldata quorumNumbers) external onlyWhenNotPaused(PAUSED_DEREGISTER_OPERATOR)</pre><p><strong>AVS householding functions</strong></p><p>单独出篇幅讲解</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d43e9ddfbf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EigenLayer Contract Introduction]]></title>
            <link>https://medium.com/@xiaohuo200/eigenlayer-contract-introduction-8f2a5d250bff?source=rss-51731e1d4599------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f2a5d250bff</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[staking]]></category>
            <category><![CDATA[eigenlayer]]></category>
            <dc:creator><![CDATA[xiaohuo ren]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 16:01:45 GMT</pubDate>
            <atom:updated>2024-04-25T05:01:14.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>EigenLayer Contract Introduction # 1 — Core</h3><p>DISCLAIMER #1 : 本文基于公开仓库和文档进行编译，不涉及任何商业机密和投资建议，仅供学习交流使用</p><p>DISCLAIMER #2: 不保证语句通顺，纠错和反馈请联系 wechat: xiaohuo0x or telegram: @xiaohuo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hRY22fiNkM7uW0sfYfeYA.png" /></figure><p><strong>EigenLayer Core</strong></p><p>EigenLayer Core 的代码其实很简洁，但是在理解代码之前我们需要理清 EigenLayer 的顶层设计，这里归纳了几点希望可以帮助大家理解：</p><ol><li>EigenLayer 的生态大体上可以分成三类角色：<br>a) 拥有 LST 资产的终端用户<br>b) 拥有节点运行能力的节点商/矿池<br>c) 需要网络效应的 AVS 应用方</li><li>各个角色的关系如下：<br>a) AVS 应用方定义 PoS 网络规则，包括节点软件，健康检查和监控指标，以及网络支持的 strategy list 和其权重，最小 stake 数目，最大节点数目，踢出规则等等<br>b) 节点商/矿池通过注册为 operator 从而进一步 opt-in 到某些特定的 AVS 网络中，运行其节点以获得奖励<br>c) 终端用户只需将自己的 LST delegate 到 operator 即可</li></ol><p><em>IStrategy and StrategyBase</em></p><p>每一个被 EigenLayer 生态支持的 LST 都被抽象成一个叫 Strategy 的合约，它在概念上和 ERC4624 <a href="https://eips.ethereum.org/EIPS/eip-4626">https://eips.ethereum.org/EIPS/eip-4626</a> 非常相似，只是不会发行新的 token 而已。</p><p>掌握 EigenLayer 的 Strategy 合约或者说 ERC4624 合约的重点其实不难，单纯的把它看成一种记账的方法就行：</p><ol><li>每一个 Strategy 合约都会关联一个底层 ERC20 资产合约，比如 StrategyBase(stETH) <a href="https://etherscan.io/address/0x93c4b944D05dfe6df7645A86cd2206016c51564D#readProxyContract">https://etherscan.io/address/0x93c4b944D05dfe6df7645A86cd2206016c51564D#readProxyContract</a> 的底层合约地址是 <a href="https://etherscan.io/address/0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84">https://etherscan.io/address/0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84</a> 也就是 stETH 详见：<a href="https://lido.fi/">https://lido.fi/</a></li><li>用户向 Strategy 合约 deposit 底层资产之后，会被分配一定量的 share</li><li>用户向 Strategy 合约 withdraw 一定量的 share 之后，会收到相对应的底层资产 ERC20</li><li>无论是 deposit 还是 withdraw share 的单价总是 total share/ total underlying asset 比如 deposit 如果想存入的 amount 是 X，那么用户得到的 share 将会是:<br>a) 先计算 share 的单价 x = total asset before depositing / total share before depositing <br>b) 再计算用户将获取的 share 数量 X / x</li><li>用户想 withdraw Y share<br>a) 先计算 share 的单价 x = total asset before withdrawing / total share before withdrawing<br>b) 再计算用户将获取的 asset 数量 Y * x</li></ol><p><em>StrategyManager</em></p><p><em>StrategyManager</em> 管理着所有的 Strategy 合约，目前 EigenLayer 所支持的 strategy 是白名单机制，实现方式也很直接：</p><pre>/// @notice Mapping: strategy =&gt; whether or not stakers are allowed to deposit into it<br>mapping(IStrategy =&gt; bool) public strategyIsWhitelistedForDeposit;<br><br>modifier onlyStrategiesWhitelistedForDeposit(IStrategy strategy) {<br>    require(<br>        strategyIsWhitelistedForDeposit[strategy],<br>        &quot;StrategyManager.onlyStrategiesWhitelistedForDeposit: strategy not whitelisted&quot;<br>    );<br>    _;<br>}<br><br>/**<br> * @notice Owner-only function that adds the provided Strategies to the &#39;whitelist&#39; of strategies that stakers can deposit into<br> * @param strategiesToWhitelist Strategies that will be added to the `strategyIsWhitelistedForDeposit` mapping (if they aren&#39;t in it already)<br> * @param thirdPartyTransfersForbiddenValues bool values to set `thirdPartyTransfersForbidden` to for each strategy<br> */<br>function addStrategiesToDepositWhitelist(<br>    IStrategy[] calldata strategiesToWhitelist,<br>    bool[] calldata thirdPartyTransfersForbiddenValues<br>) external;<br><br>/**<br> * @notice Owner-only function that removes the provided Strategies from the &#39;whitelist&#39; of strategies that stakers can deposit into<br> * @param strategiesToRemoveFromWhitelist Strategies that will be removed to the `strategyIsWhitelistedForDeposit` mapping (if they are in it)<br> */<br>function removeStrategiesFromDepositWhitelist(IStrategy[] calldata strategiesToRemoveFromWhitelist) external;</pre><p>同时 <em>StrategyManager</em> 也是用户进行 LST deposit 的入口：</p><pre><br>/// @notice Mapping: staker =&gt; Strategy =&gt; number of shares which they currently hold<br>mapping(address =&gt; mapping(IStrategy =&gt; uint256)) public stakerStrategyShares;<br><br>/**<br> * @notice Deposits `amount` of `token` into the specified `strategy`, with the resultant shares credited to `msg.sender`<br> * @param strategy is the specified strategy where deposit is to be made,<br> * @param token is the denomination in which the deposit is to be made,<br> * @param amount is the amount of token to be deposited in the strategy by the staker<br> * @return shares The amount of new shares in the `strategy` created as part of the action.<br> * @dev The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf.<br> *<br> * WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended.  This can lead to attack vectors<br> *          where the token balance and corresponding strategy shares are not in sync upon reentrancy.<br> */<br>function depositIntoStrategy(IStrategy strategy, IERC20 token, uint256 amount)<br>    external<br>    onlyWhenNotPaused(PAUSED_DEPOSITS)<br>    nonReentrant<br>    returns (uint256 shares)<br>{<br>    shares = _depositIntoStrategy(msg.sender, strategy, token, amount);<br>}<br><br></pre><p>除此之外 <em>StrategyManager</em> 也会全局的记录下每个用户在各个 strategy 合约里面拥有的 share 数目。</p><p><em>DelegationManager</em></p><p>如果说 <em>StrategyManager </em>处理了用户如何将 LST/LSR 带入 EigenLayer 生态，那么 <em>DelegationManager </em>则着重处理：</p><ol><li>如何注册为 operator</li><li>delegate/undelegate to/from operator</li></ol><p>注册为 operator 的操作只需要 invoke 一个合约方法：</p><pre>/**<br> * @notice Registers the caller as an operator in EigenLayer.<br> * @param registeringOperatorDetails is the `OperatorDetails` for the operator.<br> * @param metadataURI is a URI for the operator&#39;s metadata, i.e. a link providing more details on the operator.<br> *<br> * @dev Once an operator is registered, they cannot &#39;deregister&#39; as an operator, and they will forever be considered &quot;delegated to themself&quot;.<br> * @dev This function will revert if the caller attempts to set their `earningsReceiver` to address(0).<br> * @dev Note that the `metadataURI` is *never stored * and is only emitted in the `OperatorMetadataURIUpdated` event<br> */<br>function registerAsOperator(OperatorDetails calldata registeringOperatorDetails, string calldata metadataURI)</pre><p>OperatorDetails 定义了 earning receiver，delegation approver (通常为 address(0)) 以及 opt-out 时间窗后（以后再讲）</p><p>metadataURI 则定义了 operator 的基本信息，会被 EigenLayer 的 indexer 索引到并在 UI 上显示，模版如下：</p><pre>{<br>  &quot;name&quot;: &quot;EigenLabs&quot;,<br>  &quot;website&quot;: &quot;https://www.eigenlayer.xyz/&quot;,<br>  &quot;description&quot;: &quot;Shared Security To Hyperscale Ethereum&quot;,<br>  &quot;logo&quot;: &quot;https://goerli-operator-metadata.s3.amazonaws.com/eigenlayer.png&quot;,<br>  &quot;twitter&quot;: &quot;https://twitter.com/eigenlayer&quot;<br>}</pre><p>相应的 <em>StrategyManager </em>也提供两个方法更改上述信息：</p><pre>function modifyOperatorDetails(OperatorDetails calldata newOperatorDetails) external {<br>    require(isOperator(msg.sender), &quot;DelegationManager.modifyOperatorDetails: caller must be an operator&quot;);<br>    _setOperatorDetails(msg.sender, newOperatorDetails);<br>}<br><br>function updateOperatorMetadataURI(string calldata metadataURI) external {<br>    require(isOperator(msg.sender), &quot;DelegationManager.updateOperatorMetadataURI: caller must be an operator&quot;);<br>    emit OperatorMetadataURIUpdated(msg.sender, metadataURI);<br>}</pre><p>当节点商注册为 operator 之后，用户就可以通过 delegateTo 将自己的 LST delegate 到该节点：</p><pre>function delegateTo(address operator, SignatureWithExpiry memory approverSignatureAndExpiry, bytes32 approverSalt)<br>    external<br>{<br>    // go through the internal delegation flow, checking the `approverSignatureAndExpiry` if applicable<br>    _delegate(msg.sender, operator, approverSignatureAndExpiry, approverSalt);<br>}</pre><p>根据目前 EigenLayer 的代码，delegate 是 all or no 的设计，也就是说，一个 staker 地址只能 delegate 到一个 operator 上：</p><pre>function _delegate(<br>    address staker,<br>    address operator,<br>    SignatureWithExpiry memory approverSignatureAndExpiry,<br>    bytes32 approverSalt<br>) internal onlyWhenNotPaused(PAUSED_NEW_DELEGATION) {<br>    require(!isDelegated(staker), &quot;DelegationManager._delegate: staker is already actively delegated&quot;);<br>    require(isOperator(operator), &quot;DelegationManager._delegate: operator is not registered in EigenLayer&quot;);</pre><p>delegate 在 EigenLayer 合约 <em>StrategyManager </em>里面并没有实际的 token 转移，而只是记账，也充分和 AVS 的代码解耦，后面会讲到这种设计的好处。</p><pre><br>// record the delegation relation between the staker and operator, and emit an event<br>delegatedTo[staker] = operator;<br>emit StakerDelegated(staker, operator);<br><br>(IStrategy[] memory strategies, uint256[] memory shares) = getDelegatableShares(staker);<br><br>for (uint256 i = 0; i &lt; strategies.length;) {<br>    _increaseOperatorShares({operator: operator, staker: staker, strategy: strategies[i], shares: shares[i]});<br><br>    unchecked {<br>        ++i;<br>    }<br>}</pre><p><em>StrategyManager</em> 还有很大一部分代码在阐述如果 undelegate 和 withdraw：</p><ol><li>用户选择 undelegate share 会立马从 staker/operator 上被移除并转移到 pending queue</li><li>一定的 delay 期限过后，用户可以选择 completeQueuedWithdrawal，delay 算法如下：（都是由 owner 去设置）</li></ol><pre>max(minWithdrawalDelayBlocks, strategyWithdrawalDelayBlocks[strategy])</pre><p><em>AVSDirectory</em></p><p><em>AVSDirectory</em> 合约则专注于 AVS 的注册和信息处理，逻辑相对简单</p><ol><li>AVS 合约通过 invoke updateAVSMetadataURI 方法来发布自己的 metadata 信息，从而 EigenLayer indexer 可以索引到 AVS 的基础信息并在 UI 上展示（目前是白名单制）</li><li>Operator 可以通过 invoke registerOperatorToAVS 或者 deregisterOperatorFromAVS 来 opt-in/opt-out 特定的 AVS，从而加入网络或者退出网络</li></ol><p><strong>EigenLayer Middleware</strong></p><p>EigeLayer Middleware 是一套帮助 AVS 项目方进行研发的工具合约，类似于智能合约版本的 sdk，之后出篇幅单独讲。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2a5d250bff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arbitrum Orbit Introduction — nitro contracts and node]]></title>
            <link>https://medium.com/@xiaohuo200/arbitrum-orbit-introduction-nitro-contracta-and-node-605723fb2ea1?source=rss-51731e1d4599------2</link>
            <guid isPermaLink="false">https://medium.com/p/605723fb2ea1</guid>
            <category><![CDATA[arbitrum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rollup]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[xiaohuo ren]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 19:02:06 GMT</pubDate>
            <atom:updated>2024-04-18T19:34:27.450Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arbitrum Orbit Introduction — nitro contracts and node</h3><p>DISCLAIMER #1 : 本文基于公开仓库和文档进行编译，不涉及任何商业机密和投资建议，仅供学习交流使用</p><p>DISCLAIMER #2: 不保证语句通顺，纠错和反馈请联系 wechat: xiaohuo0x or telegram: @xiaohuo</p><p>Arbitrum 作为当下比较卓越的 l2/l3 平台和解决方案，其技术栈包含：</p><ol><li>节点部分，包括大家熟知的负责同步 parent chain 数据的 sequencer，负责向 parent chain post batch 数据的 batch poster，以及负责确认 state root 以及对潜在的 fruad 进行 challenge 的 staker，除此之外，节点部分还包含提供 rpc 服务的 fullnode/archive node 等等。其主要仓库位于 <a href="https://github.com/OffchainLabs/nitro">https://github.com/OffchainLabs/nitro</a> 在后续文章讨论中，我们用 nitro 来代替节点部分的阐述，更详细的节点角色及其运行机制，后续用单独的文章篇幅来进行阐述</li><li>Anytrust 这部分也是在 nitro 仓库中，但是由于 DAC 的特殊角色，我们可以分开阐述。AnyTrust 的工作机制相对比较简单，动机也很明确：减少往 parent chain post 的 calldata 大小，从而降低费用。使用 Anytrust 的 l2/l3 的 orbit chain 会将 calldata 的 post 流程分为两步： a) 将原始数据 post 到 da server，得到 da certification（包括 da 委员会的签名和数据指针）b) 将 da certification 作为 calldata 上传到 parent chain，nitro 合约会对 da cert 进行验证。同类型的技术栈目前有 celestia 和 eigenda</li><li>与 nitro 配合工作的合约部分主要集中在仓库 <a href="https://github.com/OffchainLabs/nitro-contracts">https://github.com/OffchainLabs/nitro-contracts</a> 例如：</li></ol><p>a. 用来接收 batch poster 提交的数据的 SequencerInbox 合约</p><pre>/**<br> * @title  Accepts batches from the sequencer and adds them to the rollup inbox.<br> * @notice Contains the inbox accumulator which is the ordering of all data and transactions to be processed by the rollup.<br> *         As part of submitting a batch the sequencer is also expected to include items enqueued<br> *         in the delayed inbox (Bridge.sol). If items in the delayed inbox are not included by a<br> *         sequencer within a time limit they can be force included into the rollup inbox by anyone.<br> */<br>contract SequencerInbox is DelegateCallAware, GasRefundEnabled, ISequencerInbox {</pre><p>只有成功提交到这个合约的 batch 数据才能被确认和验证，或者被提出挑战。</p><p>b. 用来让 staker/validator 进行 assert 的 Rollup 合约</p><pre>function stakeOnNewNode(<br>    Assertion memory assertion,<br>    bytes32 expectedNodeHash,<br>    uint256 prevNodeInboxMaxCount<br>) external;    <br>function confirmNextNode(bytes32 blockHash, bytes32 sendRoot) external;<br>function rejectNextNode(address stakerAddress) external;</pre><p>如果 assertion 在 challenge period 结束之后（arbitrum one 的时间是一周，l3 orbit 可以自行设置）没有被成功挑战，那么本次 state root 会被确认，相应的资金在 parent chain 上可以被 withdraw 成功。</p><p>c. 用来进行挑战 PVP 的 ChallengeManager 合约</p><pre>function createChallenge(<br>    bytes32 wasmModuleRoot_,<br>    MachineStatus[2] calldata startAndEndMachineStatuses_,<br>    GlobalState[2] calldata startAndEndGlobalStates_,<br>    uint64 numBlocks,<br>    address asserter_,<br>    address challenger_,<br>    uint256 asserterTimeLeft_,<br>    uint256 challengerTimeLeft_<br>) external override returns (uint64) {}</pre><pre>function bisectExecution(<br>    uint64 chalxlengeIndex,<br>    ChallengeLib.SegmentSelection calldata selection,<br>    bytes32[] calldata newSegments<br>) external takeTurn(challengeIndex, selection, ChallengeModeRequirement.ANY) {}</pre><pre>function challengeExecution(<br>    uint64 challengeIndex,<br>    ChallengeLib.SegmentSelection calldata selection,<br>    MachineStatus[2] calldata machineStatuses,<br>    bytes32[2] calldata globalStateHashes,<br>    uint256 numSteps<br>) external takeTurn(challengeIndex, selection, ChallengeModeRequirement.BLOCK) {</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFh-iH7FprjgVBmGoXw6Ow.png" /><figcaption>challenge 流程示意图，来自官方文档</figcaption></figure><p>4. 由于 rollup 的特性，nitro/nitro contract 天生就自带 bridge 功能，同时实现了协议定义的 arbitrary cross-chain messaging system 因此除了 nitro contract 之外，arbitrum team 借助 arbitrary cross-chain messaging system 实现了一套专门针对 ERC20 的跨链协议，其仓库地址位于：<a href="https://github.com/OffchainLabs/token-bridge-contracts">https://github.com/OffchainLabs/token-bridge-contracts</a></p><p>Rollup creator 和 Bridge creator</p><p>Abirtrum team 为了简化 rollup 和 bridge 合约的部署，并没有提供很复杂的 hardhat 或者 foundry 脚本，相反，针对每个发型版本，官方都会提供两个工厂合约：</p><p>RollupCreator:</p><pre>/**<br> * @notice Create a new rollup<br> * @dev After this setup:<br> * @dev - UpgradeExecutor should be the owner of rollup<br> * @dev - UpgradeExecutor should be the owner of proxyAdmin which manages bridge contracts<br> * @dev - config.rollupOwner should have executor role on upgradeExecutor<br> * @dev - Bridge should have a single inbox and outbox<br> * @dev - Validators and batch poster should be set if provided<br> * @param deployParams The parameters for the rollup deployment. It consists of:<br> *          - config        The configuration for the rollup<br> *          - batchPoster   The address of the batch poster, not used when set to zero address<br> *          - validators    The list of validator addresses, not used when set to empty list<br> *          - nativeToken   Address of the custom fee token used by rollup. If rollup is ETH-based address(0) should be provided<br> *          - deployFactoriesToL2 Whether to deploy L2 factories using retryable tickets. If true, retryables need to be paid for in native currency.<br> *                          Deploying factories via retryable tickets at rollup creation time is the most reliable method to do it since it<br> *                          doesn&#39;t require paying the L1 gas. If deployment is not done as part of rollup creation TX, there is a risk that<br> *                          anyone can try to deploy factories and potentially burn the nonce 0 (ie. due to gas price spike when doing direct<br> *                          L2 TX). That would mean we permanently lost capability to deploy deterministic factory at expected address.<br> *          - maxFeePerGasForRetryables price bid for L2 execution.<br> *          - dataHashReader The address of the data hash reader used to read blob hashes<br> * @return The address of the newly created rollup<br> */<br>function createRollup(RollupDeploymentParams memory deployParams)<br>    public<br>    payable<br>    returns (address){}</pre><p>BridgeCreator:</p><pre>function createBridge(<br>    address adminProxy,<br>    address rollup,<br>    address nativeToken,<br>    ISequencerInbox.MaxTimeVariation calldata maxTimeVariation<br>) external returns (BridgeContracts memory) {}</pre><p>其原理也不复杂，arbitrum team 会把各个组件合约提前部署好作为 template，当 rollup 项目方或者 RaaS 平台去调用 createRollup 的时候，实际被部署的是一系列 TransparentUpgradeableProxy 合约。熟悉 solidity 的朋友应该知道 solidity 有一个 delegatecall 的特性，从而使透明和可升级的合约成为可能。</p><p>Rollup 部署参数</p><pre>struct RollupDeploymentParams {<br>    Config config;<br>    address[] validators;<br>    uint256 maxDataSize;<br>    address nativeToken;<br>    bool deployFactoriesToL2;<br>    uint256 maxFeePerGasForRetryables;<br>    //// @dev The address of the batch poster, not used when set to zero address<br>    address[] batchPosters;<br>    address batchPosterManager;<br>}</pre><pre>struct Config {<br>    uint64 confirmPeriodBlocks;<br>    uint64 extraChallengeTimeBlocks;<br>    address stakeToken;<br>    uint256 baseStake;<br>    bytes32 wasmModuleRoot;<br>    address owner;<br>    address loserStakeEscrow;<br>    uint256 chainId;<br>    string chainConfig;<br>    uint64 genesisBlockNum;<br>    ISequencerInbox.MaxTimeVariation sequencerInboxMaxTimeVariation;<br>}</pre><p>rollup 部署参数其实蕴含着 l2/l3 chain 的所有重要信息，这里列举说明：</p><ol><li>validators 包含可以对 state root 进行 assert 和 challenge 的验证节点地址</li><li>batchPoster 提交 batch 的节点地址</li><li>maxDataSize 提交的 batch data 的最大值</li><li>nativeToken 一般用 0x0000000000000000000000000000000000000000 即 $ETH 作为 gas 结算货币，也支持自定义的 ERC20 token</li><li>confirmPeriodBlocks 和 extraChallengeTimeBlocks 定义了 challenge period/dispute window 注意无论是 l2 orbit 还是 l3 orbit 这里的 block 都是以 l1 ethereum block 进行计量，具体原因设计到 orbit chain 的出块机制，以后再讲</li><li>stakeToken validator 节点的策略有很多种，比如只验证不声明的 watchtower 策略，发现错误只会记录一条本地日志，不声明但是发现错误会进行 challenge 的 defensive 策略，但是为了 orbit chain 能正常往前运作，协议规定每一个 orbit chain 至少有用一个策略为 makenodes 的 validator 节点，就是定时会往 parent chain 发布/声明 state root 以及接受潜在的挑战。为了防止该策略的节点进行作恶，协议会要求其 deposit 一定的 token，主要是用于作恶情况下的 slash 和我们一般理解的 staking 有所不同</li><li>baseStake 需要 deposit stakeToken 的最小 stake 要求</li><li>wasmModuleRoot 这部分很有意思，值得单独开篇幅讨论，总而言之 validator 无论处于何种策略，其验证过程都是在 wasm 虚拟机里面进行的，它是一个状态机模型，而状态机的初始值由 replay.go 编译后的 wasm 决定 docker run --rm --entrypoint cat nitro-node-dev target/machines/latest/module-root.txt并且由 wasmModuleRoot 传入 rollup 合约。由于每个 nitro 版本的源代码都会发生变更，module root 会相应改变，所以可能会和合约里面匹配不上从而导致 block validation 无法工作，这个时候我们可以选择走 arbos 的升级流程，或者利用 nitro 的一些 dangerous 操作修复。后面会展开讲解</li><li>chainId orbit chain id</li><li>其他</li></ol><p>节点配置</p><p>通过官方 playgound 我们可以很快 launch 一条 orbit chain 部署成功之后我们可以看一眼节点配置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wSKUWAHV96P5i7QO_e-Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l15GUzdqdAoTRc7BEPJi0g.png" /></figure><pre>{<br>  &quot;chain&quot;: {<br>    &quot;info-json&quot;: &quot;[{\&quot;chain-id\&quot;:14011710374,\&quot;parent-chain-id\&quot;:421614,\&quot;parent-chain-is-arbitrum\&quot;:true,\&quot;chain-name\&quot;:\&quot;My Arbitrum L3 Chain\&quot;,\&quot;chain-config\&quot;:{\&quot;homesteadBlock\&quot;:0,\&quot;daoForkBlock\&quot;:null,\&quot;daoForkSupport\&quot;:true,\&quot;eip150Block\&quot;:0,\&quot;eip150Hash\&quot;:\&quot;0x0000000000000000000000000000000000000000000000000000000000000000\&quot;,\&quot;eip155Block\&quot;:0,\&quot;eip158Block\&quot;:0,\&quot;byzantiumBlock\&quot;:0,\&quot;constantinopleBlock\&quot;:0,\&quot;petersburgBlock\&quot;:0,\&quot;istanbulBlock\&quot;:0,\&quot;muirGlacierBlock\&quot;:0,\&quot;berlinBlock\&quot;:0,\&quot;londonBlock\&quot;:0,\&quot;clique\&quot;:{\&quot;period\&quot;:0,\&quot;epoch\&quot;:0},\&quot;arbitrum\&quot;:{\&quot;EnableArbOS\&quot;:true,\&quot;AllowDebugPrecompiles\&quot;:false,\&quot;DataAvailabilityCommittee\&quot;:true,\&quot;InitialArbOSVersion\&quot;:11,\&quot;GenesisBlockNum\&quot;:0,\&quot;MaxCodeSize\&quot;:24576,\&quot;MaxInitCodeSize\&quot;:49152,\&quot;InitialChainOwner\&quot;:\&quot;0x65575427C6fc742B97Ccb5ebDEc4251552d2c8d2\&quot;},\&quot;chainId\&quot;:14011710374},\&quot;rollup\&quot;:{\&quot;bridge\&quot;:\&quot;0xB79Dc8D26586AbafcAce60611ED6BD51D004C0A8\&quot;,\&quot;inbox\&quot;:\&quot;0x3f7EaC603c1DaE3102a63b2C7381BE4c103AA97d\&quot;,\&quot;sequencer-inbox\&quot;:\&quot;0x14A903C34d9313ce2a3B6A513DF3BA7FE5D4A73a\&quot;,\&quot;rollup\&quot;:\&quot;0x8c5A2942Fb718c6327d2388D9bBc39A28B51Caae\&quot;,\&quot;validator-utils\&quot;:\&quot;0xB11EB62DD2B352886A4530A9106fE427844D515f\&quot;,\&quot;validator-wallet-creator\&quot;:\&quot;0xEb9885B6c0e117D339F47585cC06a2765AaE2E0b\&quot;,\&quot;deployed-at\&quot;:35041948}}]&quot;,<br>    &quot;name&quot;: &quot;My Arbitrum L3 Chain&quot;<br>  },<br>  &quot;parent-chain&quot;: {<br>    &quot;connection&quot;: {<br>      &quot;url&quot;: &quot;https://sepolia-rollup.arbitrum.io/rpc&quot;<br>    }<br>  },<br>  &quot;http&quot;: {<br>    &quot;addr&quot;: &quot;0.0.0.0&quot;,<br>    &quot;port&quot;: 8449,<br>    &quot;vhosts&quot;: [<br>      &quot;*&quot;<br>    ],<br>    &quot;corsdomain&quot;: [<br>      &quot;*&quot;<br>    ],<br>    &quot;api&quot;: [<br>      &quot;eth&quot;,<br>      &quot;net&quot;,<br>      &quot;web3&quot;,<br>      &quot;arb&quot;,<br>      &quot;debug&quot;<br>    ]<br>  },<br>  &quot;node&quot;: {<br>    &quot;sequencer&quot;: true,<br>    &quot;delayed-sequencer&quot;: {<br>      &quot;enable&quot;: true,<br>      &quot;use-merge-finality&quot;: false,<br>      &quot;finalize-distance&quot;: 1<br>    },<br>    &quot;batch-poster&quot;: {<br>      &quot;max-size&quot;: 90000,<br>      &quot;enable&quot;: true,<br>      &quot;parent-chain-wallet&quot;: {<br>        &quot;private-key&quot;: &quot;&quot;<br>      }<br>    },<br>    &quot;staker&quot;: {<br>      &quot;enable&quot;: true,<br>      &quot;strategy&quot;: &quot;MakeNodes&quot;,<br>      &quot;parent-chain-wallet&quot;: {<br>        &quot;private-key&quot;: &quot;&quot;<br>      }<br>    },<br>    &quot;dangerous&quot;: {<br>      &quot;no-sequencer-coordinator&quot;: true<br>    },<br>    &quot;data-availability&quot;: {<br>      &quot;enable&quot;: true,<br>      &quot;sequencer-inbox-address&quot;: &quot;0x14A903C34d9313ce2a3B6A513DF3BA7FE5D4A73a&quot;,<br>      &quot;parent-chain-node-url&quot;: &quot;https://sepolia-rollup.arbitrum.io/rpc&quot;,<br>      &quot;rest-aggregator&quot;: {<br>        &quot;enable&quot;: true,<br>        &quot;urls&quot;: [<br>          &quot;http://localhost:9877&quot;<br>        ]<br>      },<br>      &quot;rpc-aggregator&quot;: {<br>        &quot;enable&quot;: true,<br>        &quot;assumed-honest&quot;: 1,<br>        &quot;backends&quot;: &quot;[{\&quot;url\&quot;:\&quot;http://localhost:9876\&quot;,\&quot;pubkey\&quot;:\&quot;YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==\&quot;,\&quot;signermask\&quot;:1}]&quot;<br>      }<br>    }<br>  },<br>  &quot;execution&quot;: {<br>    &quot;forwarding-target&quot;: &quot;&quot;,<br>    &quot;sequencer&quot;: {<br>      &quot;enable&quot;: true,<br>      &quot;max-tx-data-size&quot;: 85000,<br>      &quot;max-block-speed&quot;: &quot;250ms&quot;<br>    },<br>    &quot;caching&quot;: {<br>      &quot;archive&quot;: true<br>    }<br>  }<br>}</pre><p>可以看到，官方推荐的运行模式是一个进程同时担任三种角色，即：</p><ol><li>sequencer</li><li>batch poster</li><li>staker</li></ol><p>batch poster 和 staker 由于要发送交易，所以需要提供私钥，另外我们还可以看到 dac 的相关配置。这个配置很简洁，也隐去了很多重要的参数（nitro 节点在启动的时候会给默认值）以后我们在讨论具体协议机制的时候会详细讲解。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=605723fb2ea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>