Abstract
This article presents the transactions batcher used in Metacube to send NFTs earned by players instantly. It explains the batcher's scalable actor-based architecture and provides a detailed implementation in Go.
All the code snippets are available in the associated GitHub repository.
Architecture
The Batcher is composed of two main actors:
- The Builder receives the transactions, batches them into a single multicall transaction, and sends it to the Sender actor.
- The Sender finalizes the transaction with appropriate fields (nonce, max fee, etc.), signs it, sends it to the Starknet network, and monitors its status.
This actor separation allows for a scalable and efficient batcher. The builder prepares the transactions while the sender sends them, allowing for a continuous and efficient flow of transactions.
Implementation
The following implementation is specific to Go, but the concepts can easily be adapted to other languages, as the functionalities remain the same.
Moreover, note that this implementation is specific to sending NFTs from the same contract. However, a more generic approach is mentioned later in the article.
Lastly, the code is based on the starknet.go library developed by Nethermind.
Batcher
Let's start with the Batcher itself:
type Batcher struct { accnt *account.Account contractAddress *felt.Felt maxSize int inChan <p>The account (accnt) is the one holding the NFTs, it will be used to sign the transactions that transfer them. These NFTs are part of the same contract, hence the contractAddress field. The maxSize field is the maximum size of a batch, and inChan is the channel where the transactions are sent to the Batcher. The failChan is used to send back the transactions that failed to be sent.</p> <p>Note that, in this implementation, the later-called transaction data ([]string) is an array of two elements: the recipient address and the NFT ID.</p> <p>The Batcher runs both the Builder and the Sender actors concurrently:<br> </p> <pre class="brush:php;toolbar:false">type TxnDataPair struct { Txn rpc.BroadcastInvokev1Txn Data [][]string } func (b *Batcher) Run() { txnDataPairChan := make(chan TxnDataPair) go b.runBuildActor(txnDataPairChan) go b.runSendActor(txnDataPairChan) }
The defined channel txnDataPairChan sends the transaction data pairs from the Builder to the Sender. Each transaction data pair comprises the batch transaction, and the data for each transaction is embedded in it. The data for each transaction is sent with the batch transaction so that the failed transactions can be sent back to the entity that instantiates the Batcher.
Builder
Let's analyze the Build actor. Note that the code is simplified for better readability (full code):
type Batcher struct { accnt *account.Account contractAddress *felt.Felt maxSize int inChan <p>The runBuildActor function is the Builder actor's event loop. It waits for transactions to be sent to the Batcher and builds a batch transaction when the batch is full, or a timeout is reached. The batch transaction is then sent to the Sender actor.</p> <h3> Sender </h3> <p>Let's now analyze the Sender actor. Note that the code is simplified for better readability (full code):<br> </p> <pre class="brush:php;toolbar:false">type TxnDataPair struct { Txn rpc.BroadcastInvokev1Txn Data [][]string } func (b *Batcher) Run() { txnDataPairChan := make(chan TxnDataPair) go b.runBuildActor(txnDataPairChan) go b.runSendActor(txnDataPairChan) }
The runSendActor function is the sender actor's event loop. It waits for the Builder to send batch transactions, signs them, sends them to the Starknet network, and monitors their status.
A note on fee estimation: one could estimate the fee cost of the batch transaction before sending it. The following code can be added after signing the transaction:
// This function builds a function call from the transaction data. func (b *Batcher) buildFunctionCall(data []string) (*rpc.FunctionCall, error) { // Parse the recipient address toAddressInFelt, err := utils.HexToFelt(data[0]) if err != nil { ... } // Parse the NFT ID nftID, err := strconv.Atoi(data[1]) if err != nil { ... } // The entry point is a standard ERC721 function // https://docs.openzeppelin.com/contracts-cairo/0.20.0/erc721 return &rpc.FunctionCall{ ContractAddress: b.contractAddress, EntryPointSelector: utils.GetSelectorFromNameFelt( "safe_transfer_from", ), Calldata: []*felt.Felt{ b.accnt.AccountAddress, // from toAddressInFelt, // to new(felt.Felt).SetUint64(uint64(nftID)), // NFT ID new(felt.Felt).SetUint64(0), // data -> None new(felt.Felt).SetUint64(0), // extra data -> None }, }, nil } // This function builds the batch transaction from the function calls. func (b *Batcher) buildBatchTransaction(functionCalls []rpc.FunctionCall) (rpc.BroadcastInvokev1Txn, error) { // Format the calldata (i.e., the function calls) calldata, err := b.accnt.FmtCalldata(functionCalls) if err != nil { ... } return rpc.BroadcastInvokev1Txn{ InvokeTxnV1: rpc.InvokeTxnV1{ MaxFee: new(felt.Felt).SetUint64(MAX_FEE), Version: rpc.TransactionV1, Nonce: new(felt.Felt).SetUint64(0), // Will be set by the send actor Type: rpc.TransactionType_Invoke, SenderAddress: b.accnt.AccountAddress, Calldata: calldata, }, }, nil } // Actual Build actor event loop func (b *Batcher) runBuildActor(txnDataPairChan chan= b.maxSize { // The batch is full, trigger the building trigger = true } // We don't want a smaller batch to wait indefinitely to be full, so we set a timeout to trigger the building even if the batch is not full case 0 { trigger = true } } if trigger { builtTxn, err := b.buildBatchTransaction(functionCalls) if err != nil { ... } else { // Send the batch transaction to the Sender txnDataPairChan <p>This might be useful to ensure the fee is not too high before sending the transaction. If the estimated fee is higher than expected, one might also need to re-adjust the max fee field of the transaction if the estimated fee is higher than expected. But note that when any change is made to the transaction, it must be signed again!</p> <p>However, note that you might get some issues when estimating fees if the throughput of transactions is quite high. This is because when a given transaction is just approved, there is a bit of delay in updating the account's nonce. Therefore, when estimating the fee for the next transaction, it might fail, thinking that the nonce is still the previous one. So, if you still want to estimate fees, then you might need to provide some sleep between each transaction to avoid such problems.</p> <h2> Towards a generic batcher </h2> <p>The batcher presented is specific to sending NFTs from the same contract. However, the architecture can easily be adapted to send any type of transaction.</p> <p>First, the transaction data sent to the Batcher must be more generic and, therefore, contain more information. They must contain the contract address, the entry point selector, and the call data. The buildFunctionCall function must then be adapted to parse this information.</p> <p>One could also go one step further by making the sender account generic. This would require more refactoring, as the transactions must be batched per sender account. However, it is feasible and would allow for a more versatile batcher.</p> <p>However, remember that premature optimization is the root of all evil. Therefore, if you just need to send NFTs or a specific token such as ETH or STRK, the batcher presented is more than enough.</p> <h2> CLI tool </h2> <p>The repository code can be used as a CLI tool to send a bunch of NFTs by batch. The tool is easy to use, and you should be able to adapt it to your needs after reading this article. Please refer to the README for more information.</p><h2> Conclusion </h2> <p>I hope that this article helped you to better understand how Metacube sends NFTs to its players. The batcher is a key infrastructure component, and we are happy to share it with the community. If you have any questions or feedback, feel free to comment or reach out to me. Thank you for reading!</p>
The above is the detailed content of A Starknet transactions batcher. For more information, please follow other related articles on the PHP Chinese website!

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools