<?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 Bee on Medium]]></title>
        <description><![CDATA[Stories by Bee on Medium]]></description>
        <link>https://medium.com/@0xbees?source=rss-23ef08409897------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x2G6Q3_l_sQeMl2nW6bp3A.png</url>
            <title>Stories by Bee on Medium</title>
            <link>https://medium.com/@0xbees?source=rss-23ef08409897------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:42:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0xbees/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[Rust Concurrency: Threads, Ownership, and Tokio]]></title>
            <link>https://medium.com/@0xbees/rust-concurrency-threads-ownership-and-tokio-40f1496fcb74?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/40f1496fcb74</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[tokio]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 16:57:32 GMT</pubDate>
            <atom:updated>2026-02-10T16:57:32.366Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to run tasks in parallel safely and efficiently.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kol66lJTUoYCtaFxbq5_pw.png" /></figure><p>Concurrency is one of the most challenging topics in software engineering. And, Rust provides powerful tools to handle it safely without sacrificing performance. In this post, we will explore how Rust handles system threads, ownership rules, and the asynchronous model using Tokio.</p><h3>The Standard Threads</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeLEuPoXKYBfUrwKbEpSlA.png" /></figure><p>To start, let’s look at the standard library’s threading model: std::thread.</p><p>Rust uses a <strong>1:1 threading model</strong>. This means that for every thread you spawn in your Rust code, the Operating System creates a corresponding real, kernel-level thread.</p><p>In the example above, we spawn a worker thread inside the main function. While the main thread continues its execution, the worker runs its closure in parallel. However, synchronization is critical. If the main function completes and exits before the worker finishes, the process dies, and the worker is killed. To prevent this, we use handle.join(). This line forces the main thread to block and wait until the worker has finished its execution, ensuring a clean exit.</p><h3>Move Closures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdqpc3wc1z30pArjnELgnQ.png" /></figure><p>In Rust, threads are isolated by default; they do not share memory implicitly. This isolation is a key feature for memory safety.</p><p>Consider a scenario where we create a variable msg in the main thread and want the worker thread to print it. If we simply reference it, we risk a <strong>Use After Free</strong> error. If the main thread finishes and drops msg while the worker is still trying to read it, the program would crash.</p><p>To solve this, Rust employs the move keyword. This physically transfers ownership of msg from the main thread to the worker thread. Once moved, the worker becomes solely responsible for that memory, guaranteeing validity for the thread&#39;s lifetime.</p><h3>Move Closures &amp; Shared Variables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oJ6mP6EZIfUYob0j5r-NA.png" /></figure><p>Moving data works well for isolation, but what if multiple threads need to read the same data? A beginner might reach for Rc (Reference Counting) to enable multiple owners. However, Rc is designed strictly for single-threaded scenarios. Its internal reference counter is <strong>non-atomic</strong>.</p><p>If Thread A and Thread B try to clone or drop the Rc at the exact same nanosecond, a data race occurs. Both might read the counter as 2 and decrease it to 1, when it should be 0. This leads to memory leaks or premature drops. Rust’s compiler is smart enough to catch this, and it will refuse to compile Rc passed between threads.</p><h3>Send Trait</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vF3FOJEQty6zhwlFdNQCXg.png" /></figure><p>To share data across threads, we must upgrade from Rc to <strong>Arc (Atomic Reference Counting)</strong>. Arc functions similarly to Rc, but its reference counter utilizes CPU atomic instructions. These are hardware-level operations that guarantee safety across threads.</p><p>Because Arc is thread-safe, it implements the <strong>Send trait</strong>. This trait is a promise to the compiler: <em>&quot;It is safe to move ownership of this variable from one thread to another.&quot;</em> With Arc, our code compiles, and we can safely share read-only data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hA3TNJc55lE477v7euXHg.png" /></figure><p>You might wonder if you need to manually implement Send for every custom struct you build. The answer is usually no. In Rust, Send is an <strong>Auto Trait</strong>. The compiler automatically inspects your struct by recursively checking every field inside it. If all fields are Send, the struct is automatically marked as Send.</p><p>In the example of Arc&lt;i64&gt;, it contains ArcInner&lt;i64&gt;, which in turn contains Atomic&lt;usize&gt;. Since atomics are Send, Arc inherits this property. You effectively get thread safety verification for free.</p><h3>Send Trait &amp; Interior Mutability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rz3yHcq6NKKu26jL-yIkLg.png" /></figure><p>Arc allows shared <em>reading</em>, but what about <em>writing</em>? A common mistake is attempting to wrap a RefCell inside an Arc to get interior mutability. While Arc is Send, RefCell is not. RefCell performs borrow checking at runtime using normal, non-atomic counters.</p><p>If two threads attempt to call .borrow_mut() simultaneously, RefCell cannot synchronize them, leading to a data race. Consequently, Rust will reject this combination at compile time because RefCell does not satisfy the requirements for thread safety.</p><h3>Sync Trait</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf70WOevOpY27ogIL8yO_g.png" /></figure><p>To mutate shared data, we need the <strong>Sync trait</strong>. A type is Sync if it is safe to <em>share</em> across multiple threads (i.e., multiple threads can hold a reference to it).</p><p>We replace RefCell with <strong>Mutex</strong>. A Mutex ensures mutual exclusion; only one thread can access the inner data at a time. Because Mutex guarantees this safety, it implements Sync.</p><p>The standard pattern for shared mutable state in Rust is Arc&lt;Mutex&lt;T&gt;&gt;. We clone the Arc to share ownership, and use .lock() to safely access and modify the data.</p><h3>Parallelism &amp; Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-s7nvYxB_Ok88ZEZj3QgTg.png" /></figure><p>Up to this point, we have discussed <strong>Parallelism</strong> — using OS threads to do multiple things at once. This 1:1 model is ideal for <strong>CPU-bound tasks</strong> like video encoding or encryption.</p><p>However, for a web server handling 10,000 active connections, OS threads are too heavy. Most of those connections are just waiting (I/O Wait) for a database or network response. Spawning 10,000 OS threads would consume massive amounts of RAM and likely crash the OS.</p><p>This is where <strong>Concurrency (the M:N model)</strong> comes in. We want to run thousands of tasks (M) on a small number of OS threads (N). In Rust, we achieve this via <strong>Async</strong>.</p><h3>Async Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYx3yHRxLq2HwiBHPPGsXQ.png" /></figure><p>Rust achieves efficient concurrency using a <strong>Lazy</strong> model. When you write an async fn, the compiler transforms that function into a State Machine (specifically, an Enum) that implements the <strong>Future trait</strong>.</p><p>Unlike JavaScript Promises, which are <strong>Eager</strong> (start running immediately upon creation), Rust Futures are lazy. They do nothing until they are explicitly polled. A Future is simply a passive piece of data sitting in memory until a runtime drives it forward. This “zero-cost abstraction” is why Rust async is incredibly memory efficient.</p><h3>Runtime (Poller)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2P7LSofk1cEFlhtjiKBiQ.png" /></figure><p>Because Futures are lazy, they need a <strong>Runtime</strong> (or Poller) to execute them. Unlike Go or Java, Rust has <strong>no built-in runtime</strong>. You must choose one, with <strong>Tokio</strong> being the industry standard.</p><p>The #[tokio::main] attribute is a macro that wraps your code. It transforms your async main function into a synchronous function that initializes the Tokio runtime and begins execution.</p><p><em>Note: If you call an async function but forget to add </em><em>.await, the code will do absolutely nothing. The compiler will warn you that the Future is unused.</em></p><h3>Cooperative Multitasking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiimd-hm1hOv8tHhGtqezg.png" /></figure><p>Tokio schedules thousands of tasks using <strong>Cooperative Multitasking</strong>. Tokio creates a small thread pool (usually equal to the number of CPU cores). When a task (Task C) performs an I/O operation and hits .await, it <strong>yields</strong>. It effectively pauses execution and tells the runtime, &quot;I am waiting for data.&quot;</p><p>The thread does not block. Instead, it immediately switches to execute Task B. This differs from <strong>Preemptive Multitasking</strong> (used by OS threads or Go routines), where the scheduler forcibly pauses execution. Cooperative multitasking allows Rust to handle massive throughput with minimal context-switching overhead.</p><h3>Blocking Pools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ArmKgoBd9_cPUbrP_fEtA.png" /></figure><p>There is a catch with Cooperative Multitasking: <strong>Tasks must cooperate. </strong>If you run a heavy CPU calculation inside an async function without yielding, you block the entire OS thread. If that thread is blocked, no other tasks on that thread (like heartbeats or DB requests) can run. This causes “starvation.”</p><p>For CPU-heavy work within an async context, you should use tokio::task::spawn_blocking. This sends the heavy operation to a dedicated <strong>Blocking Pool</strong>, ensuring the main <strong>Async Worker Pool</strong> remains responsive for I/O operations.</p><h3>Shared Variables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9AD2oKVNgiKkf-BXGpi4Q.png" /></figure><p>When mixing async code and threads, choosing the right Mutex is vital:</p><ol><li><strong>std::sync::Mutex</strong>: Blocks the actual OS thread. It is extremely fast but dangerous in async code. Use this only for simple data operations (like updating a HashMap) where the lock is held for a tiny fraction of a second.</li><li><strong>tokio::sync::Mutex</strong>: An async-aware Mutex. When it waits for a lock, it yields the <em>Task</em>, not the <em>Thread</em>.</li></ol><p><strong>The Golden Rule:</strong> Never hold a std::sync::Mutex across an .await point. Doing so will deadlock your thread. If you need to hold a lock while awaiting I/O (e.g., during a database transaction), use the Tokio Mutex.</p><h3>Communication: Channels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stw4C3W_aoN8T4-g6ei4VQ.png" /></figure><p>While sharing memory (Mutex) is common, Rust also embraces the philosophy: <em>“Do not communicate by sharing memory; share memory by communicating.”</em></p><p>In this <strong>Multi-Producer, Single-Consumer</strong> example, we completely decouple our workers from the state:</p><ul><li><strong>Producers:</strong> We clone the transmitter (tx) for each worker. They operate independently, sending a signal (the integer 1) whenever a task is complete.</li><li><strong>Consumer:</strong> A single receiver waits asynchronously using .recv().await. When a signal arrives, it wakes up, increments the local counter, and sleeps again.</li></ul><p><em>Note: Avoid using </em><em>std::sync::mpsc in async code, as receiving from it blocks the OS thread. Always use </em><em>tokio::sync::mpsc within the Tokio runtime.</em></p><p><strong>Is there a faster way?</strong> For simple counters, channels have overhead. For raw speed, we need <strong>Atomics</strong> — coming next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40f1496fcb74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Rust Smart Pointers: Box, Rc, and RefCell]]></title>
            <link>https://medium.com/@0xbees/understanding-rust-smart-pointers-box-rc-and-refcell-a32bb558ab1a?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/a32bb558ab1a</guid>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 07:24:04 GMT</pubDate>
            <atom:updated>2026-02-09T15:45:22.306Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple guide to manage memory without fighting the compiler.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDK5D7FIuxPGIJMpcaeu-w.png" /></figure><p>If you are coming from other programming languages, Rust can feel very different. In languages like C++, you have to manage memory manually. In languages like Go or Java, you have a Garbage Collector to do the work for you. Rust takes a third path. It uses a unique system of <strong>Ownership</strong> and <strong>Smart Pointers</strong> to guarantee memory safety and performance.</p><h3>Ownership &amp; Borrowing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uENXR7B35Ry-Uyy4wp-HIA.png" /></figure><p>Before we look at smart pointers, we must review the three core rules of Rust Ownership and Borrowing. These rules keep our programs safe.</p><p><strong>Rule 1:</strong> Each value in Rust has only one owner. You cannot have two variables owning the same data at the same time. Rust checks this at compile time.</p><p><strong>Rule 2:</strong> Assignment behaves differently depending on where the data lives. Let’s look at the example ‘y = x’.</p><ul><li>If the value is on the Stack (like an integer), Rust performs a bitwise copy. Both x and y are valid and independent.</li><li>But if the value is on the Heap, the data is moved. Ownership transfers to y, and x becomes invalid. You cannot use x anymore. This prevents errors like ‘double free.’</li></ul><p><strong>Rule 3:</strong> We can borrow data using references (the &amp; symbol). But there is a strict rule: you can have either many readers (immutable references) OR one writer (mutable reference). You cannot have both at the same time.</p><p>Smart pointers help us work around these rules when we have complex data structures.</p><h3>Lifetime (‘a)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSd21EfRWBZw5MlRTnFunA.png" /></figure><p>Sometimes, the compiler needs help understanding how long a reference lives. This is called a Lifetime, written as &#39;a (tick a).</p><p>The main goal of a lifetime is to ensure that borrows stay valid for as long as they are being used. We don’t want a reference pointing to memory that has been deleted.</p><p>Look at the function longest. It takes two string slices, x and y. We return the longer one. But the compiler doesn&#39;t know if we are returning x or y. If x is deleted before we use the result, our program crashes.</p><p>By adding the lifetime &#39;a to both inputs and the output, we tell Rust: &quot;The returned reference will live as long as the inputs live&quot;. This guarantees safety at <strong>compile time</strong>.</p><h3>Lifetime &amp; Recursive Struct</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLRLh2AuOm87qE3wf8xMzQ.png" /></figure><p>Now, let’s look at a common problem: <strong>Recursive Structs</strong>. This happens when a struct contains itself, like a Linked List.</p><p>In the first code example, we have a struct Node that contains a next field, which is another Option&lt;Node&gt;.</p><p>The problem is that Rust needs to know the size of the struct at compile time. But if a Node contains a Node, which contains another Node… the size is infinite. Rust marks this as an <strong>Unknown Size</strong> error.</p><p>We could try to use a reference, like &amp;&#39;a Node. This fixes the size issue because a reference has a fixed size. However, it introduces a new problem: <strong>Ownership</strong>. If Node 1 holds a reference to Node 2, who actually <em>owns</em> Node 2? The compiler will complain that &#39;something else must own the next node&#39;. We need a better solution.</p><h3>Smart Pointer: Box</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kv2fAC9hyqfYpodCHqIZkQ.png" /></figure><p>The solution to the recursive size problem is our first smart pointer: <strong>Box</strong>.</p><p>A Box is a smart pointer that forces data to be stored on the Heap instead of the Stack. On the stack, the Box itself is just a small pointer with a fixed size. This makes the compiler happy because it now knows exactly how big the Node struct is.</p><p>In the code, we change the next field to hold Option&lt;Box&lt;Node&gt;&gt;. Look at the example and diagram to see the order of events:</p><ol><li>First, the <strong>Node 1</strong> data is created on the Heap.</li><li>Then, a “box” containing the pointer to Node 1 is created on the Stack.</li><li>Finally, <strong>Node 2</strong> is created on the Stack, and it owns the Node 1 box.</li></ol><p>So, Box gives us two things: It solves the unknown size issue. And it gives us simple, exclusive ownership. Node 2 fully owns Node 1.</p><h3>Box &amp; Graph</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mfcsa4I3eY3qrM7JPEf6Yg.png" /></figure><p>However, Box is not perfect for every situation. It works great for a list or a tree, where parents own children. But what about a Graph?</p><p>In a graph, one node might be pointed to by multiple other nodes. Look at this diagram. We have node 1 at the top. We want both node2 and node3 to point to node1.</p><p>If we use Box, this is impossible. Box enforces exclusive ownership. It says “I am the only owner.” If node2 owns node1, then node3 cannot own it. This violates the rule: 1 owner at a time. If we try this with Box, the compiler will stop us. We need a way to share ownership.</p><h3>Smart Pointer: Rc</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5JPBP3QQZhEzDEG9kGxBA.png" /></figure><p>To solve the graph problem, we use <strong>Rc</strong>, which stands for Reference Counting. Rc allows multiple parts of our program to own the same data. It keeps track of how many owners there are. When the counter reaches zero, the data is cleaned up.</p><p>In the code, we change our struct to use Rc&lt;Node&gt;. Look at the example and diagram to see the order of events:</p><ol><li>First, n1 is created on the Heap. The Rc pointer to it sits on the Stack.</li><li>Then, we create n2. We call n1.clone(). This creates a second pointer on the Stack. This is the important part: Rc::clone does not copy the deep data. It only copies the pointer on the Stack and increases the reference count. This is very fast.</li><li>Finally, we create n3 using n1. Now, both n2 and n3 sit on the stack and share ownership of the exact same memory on the heap.</li></ol><p>So, Rc lets us break the “single owner” rule safely by counting the owners.</p><h3>Rc &amp; Mutability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzJJPB2P39QLNZUJzhLtZQ.png" /></figure><p>So Rc sounds great, right? We can share data everywhere! But there is a catch. Rc only allows <strong>Immutable</strong> (Read-Only) access.</p><p>In this diagram, Rc1 and Rc2 both point to the same node. Because they share it, Rust cannot allow you to change the data. If Rust allowed mutation here, it would violate the borrowing rules we talked about earlier (you can’t have multiple readers and a writer).</p><p>If you try to change the value inside an Rc, the compiler will give you an error. So, Rc solves shared ownership, but we lose the ability to change the data. To fix this, we need one more tool.</p><h3>Interior Mutability: RefCell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHHd3oHmPxNKRXU0axkhaw.png" /></figure><p>To combine shared ownership and the ability to change data, we use Rc with <strong>RefCell</strong>.</p><p>RefCell uses a pattern called <strong>Interior Mutability</strong>. Usually, Rust checks borrowing rules at compile time. RefCell is different: it checks borrow rules at runtime. This means the compiler trusts you, but if you break the rules while the program is running, the program will crash.</p><p>In the code structure, we nest them like this: Rc&lt;RefCell&lt;Node&gt;&gt;.</p><ol><li>Rc handles the shared ownership.</li><li>RefCell handles the ability to change the data.</li></ol><p>This allows us to create n2 and n3 sharing n1, just like before, but now we can modify n1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAs6T3DmmsISQS80MMQQPA.png" /></figure><p>Now, let’s look at how RefCell checks the borrowing rules at runtime with three specific examples.</p><ul><li><strong>Example 1:</strong> Look at the top. We borrow b2 and b3 as readers. The counter sees 2 readers. This is valid.</li><li><strong>Example 2:</strong> Look at the middle. We create a writer inside a scope (the curly braces). When the scope ends, the writer is automatically dropped. Then, we create a new reader. Because the writer is already gone, this is also valid.</li><li><strong>Example 3:</strong> This is the dangerous one. We create a writer, b2. While that writer is still active, we try to create a reader, b3. This breaks the rule: you cannot have a writer and a reader at the same time. Because we are using RefCell, this causes a runtime panic, and the program crashes.</li></ul><h3>Thread-safe Smart Pointers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpIJnYogplQaN8d4jAzQGw.png" /></figure><p>So far, we have focused on Single-threaded programs. The pointers we learned — Rc and RefCell — are fast, but they are not safe if you use multiple threads.</p><p>If you need concurrency, you must switch to the Multi-threaded versions shown in this table.</p><ul><li><strong>For shared ownership:</strong> <strong>Arc</strong> is the thread-safe counterpart to Rc. Arc stands for “Atomic Reference Counting”. It guarantees that the reference counter is accurate even when multiple threads update it at the same time.</li><li><strong>For interior mutability:</strong> <strong>Mutex</strong> (or <strong>RwLock</strong>) is the counterpart to RefCell. Instead of just checking flags, these tools actually “lock” the data. This forces threads to wait their turn before reading or writing.</li></ul><p>I hope this guide helps. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a32bb558ab1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Smart Contracts to Your Favorite Address]]></title>
            <link>https://medium.com/@0xbees/deploy-smart-contracts-to-your-favorite-address-d88fea73b714?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/d88fea73b714</guid>
            <category><![CDATA[remix-ide]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 12:51:19 GMT</pubDate>
            <atom:updated>2025-06-02T12:51:19.031Z</atom:updated>
            <content:encoded><![CDATA[<h4>An easy guide with CREATE2 and Solidity Remix</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vk8VXx2BEUphYIerrneXag.png" /></figure><p>Want to deploy a contract to a specific address? With CREATE2, you can. This quick guide shows you how to use Remix and Go/JS scripts to compute and deploy contracts to predictable, custom addresses—no complex setup needed.</p><h3>Prepare contracts</h3><p>Suppose we want to deploy the Counter.sol contract below:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.27;<br><br>contract Counter {<br>    uint256 public count = 0;<br><br>    constructor(uint256 initCount) {<br>        count = initCount;<br>    }<br><br>    function increase() public {<br>        count++;<br>    }<br>}</pre><p>We use the Deployer.sol contract below to deploy the Counter contract at a predetermined address. The Deployer contract provides:</p><ul><li>getInitCodeHash: Returns the init code hash derived from the Counter contract’s bytecode and constructor parameters.</li><li>getAddr: Computes the deterministic deployment address using a salt and the constructor parameters.</li><li>deploy: Deploys the Counter contract to the calculated address.</li></ul><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.27;<br><br>import {Counter} from &quot;./Counter.sol&quot;;<br><br>contract Deployer {<br>    event Deployed(address addr);<br><br>    function deploy(uint256 salt, uint256 count) external {<br>        Counter counter = new Counter{salt: bytes32(salt)}(count);<br>        emit Deployed(address(counter));<br>    }<br><br>    function getAddr(uint256 salt, uint256 count) public view returns (address) {<br>        bytes32 initCodeHash = getInitCodeHash(count);<br>        bytes32 hash = keccak256(<br>            abi.encodePacked(bytes1(0xff), address(this), salt, initCodeHash)<br>        );<br>        return address(uint160(uint256(hash)));<br>    }<br><br>    function getInitCodeHash(uint256 count) public pure returns (bytes32) {<br>        bytes memory bytecode = type(Counter).creationCode;<br>        return keccak256(abi.encodePacked(bytecode, abi.encode(count)));<br>    }<br>}</pre><h3>Testing with Remix</h3><p>Go to <a href="https://remix.ethereum.org/">https://remix.ethereum.org</a> and create two files — Counter.sol and Deployer.sol — in the <strong>contracts</strong> directory using source code from the previous section. Then, compile Deployer.sol:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTzMwwpQUha_GVCKFjg-og.png" /></figure><p>Next, deploy to the Remix local VM. Go to <strong>Deploy</strong> tab, select <strong>Remix VM</strong> environment, choose <strong>Deployer</strong> contract, and click <strong>Deploy</strong>. Once deployed, you will see a contract instance with three available functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdXQBCwoAmtwSKn6CtSXYQ.png" /></figure><p>Let’s try with salt = 1 and count = 10. First, call getAddr to compute the expected deployment address. Then, call deploy and check if the emitted address from the Deployed event matches the computed one. As shown in the image below, they match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1p0075lDpH8zY9cR4bk6g.png" /></figure><h3>Compute your desired address</h3><p>Given the Deployer contract address and the init code hash (obtained from a Deployer function), each salt produces a unique address. To find a desired address—e.g. starts with 0x123456—we can iterate through different salts.</p><p>For simple address patterns, you can use the JavaScript code below. For more complex patterns, multi-threading is needed — use my Go implementation here: <a href="http://github.com/apeview/compute-contract-address/blob/main/go/main.go">Github</a>.</p><pre>import { ethers } from &quot;ethers&quot;;<br><br>// Deployer contract address<br>const DEPLOYER = &quot;0xa131AD247055FD2e2aA8b156A11bdEc81b9eAD95&quot;;<br><br>// Deployer.getInitCodeHash(...)<br>const INIT_CODE_HASH =<br>  &quot;0x73a3410066034d1f0f4f978e95ccb06f66a8e14fa2c98b5698540bf69503d835&quot;;<br><br>const PREFIX = &quot;0x123456&quot;;<br><br>console.time(&quot;done&quot;)<br>for (let i = 17093206; i &lt; 20000000; i++) {<br>  const salt = ethers.toBeHex(i, 32);<br>  const address = ethers.getCreate2Address(DEPLOYER, salt, INIT_CODE_HASH);<br>  if (address.startsWith(PREFIX)) {<br>    console.log(`address: ${address}, salt: ${i}`);<br>    break;<br>  }<br>}<br><br>console.timeEnd(&quot;done&quot;);</pre><pre># Output<br>address: 0x123456B5524477a67De80925CAee732D17Ff409B, salt: 17093206</pre><p>Finally, call getAddr and deploy again to verify that the deployed contract address matches the precomputed one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrmR0RaH0hmYB5_QY_CQlg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d88fea73b714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Indexed Trees: A Beginner-Friendly Visual Guide]]></title>
            <link>https://medium.com/@0xbees/binary-indexed-trees-a-beginner-friendly-visual-guide-15fc1d77cad1?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/15fc1d77cad1</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 11:12:09 GMT</pubDate>
            <atom:updated>2025-04-15T11:12:09.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>Efficient Data Structures for Range Queries and Updates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GuNl1Q1jUPFgWLdWYSO4w.png" /></figure><p>The Binary Indexed Tree (BIT) efficiently handles range sum queries and updates in logarithmic time. This guide will introduce BIT with visual examples and Python code to help you get started quickly.</p><h3>Introduction</h3><p>Given an array a of n integers, efficiently compute the sum of any range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDSOf1akOdQhJmLYOJxYjQ.png" /></figure><p>Note that sum[i, j) = sum[0, j) - sum[0, i). We pre-calculate sum[0, i), aka <a href="https://en.wikipedia.org/wiki/Prefix_sum">prefix sum</a>, by accumulating values in a loop over array a, allowing O(n) processing and O(1) query time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J67UPB2Fxb8fw98yZm2v7w.png" /></figure><p>What if we need to update a[i]? We’d have to recompute the prefix sum from i to n, keeping the processing and query times at O(n) and O(1), respectively. Is there a middle ground—O(log n) for both updates and queries? The answer is the Binary Indexed Tree (Fenwick Tree).</p><h3>Binary Indexed Tree (BIT)</h3><p>Like prefix sums, a BIT precomputes range sums — but not always from index 0. It breaks the array into overlapping power-of-two segments, allowing prefix sums to be built from partial sums and enabling quick updates without full recalculation.</p><p>We maintain a BIT array bit[1…n], where bit[i] stores the sum of the last 2ᵏ elements of a[0..i], with 2ᵏ being the LSB of i (the largest power of two dividing i).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONXWnABbiuw8tT-f70bdJw.png" /></figure><h4>Query: O(log n)</h4><p>Example: compute sum[0..7).</p><p>Note that: 7 = 2² + 2¹ + 2⁰ = 4 + 2 + 1. So, we need to sum bit at indices [4+2+1, 4+2, 4], which are [7, 6, 4]. We find these indices by repeatedly subtracting the least significant bit (LSB) from the current index until we reach 0: <strong>7</strong> → 7 − LSB(7) = <strong>6</strong> → 6 − LSB(6) = <strong>4</strong> → 4 − LSB(4) = <strong>0</strong>.</p><blockquote>In two’s complement, -i is the inverse of i plus 1. Performing i &amp; -i isolates the lowest set bit, giving you the LSB.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keNKXYYGiD5cS6fgz26-pA.png" /></figure><h4>Update: O(log n)</h4><p>Example: update a[2] = a[2] + delta, where delta = -1</p><p>From the visualization, we need to add delta to bit[2+1], bit[4], and bit[8]. Each bit[i] covers a segment of size LSB(i). Adding LSB(i) to i moves to the next larger segment that includes i—its parent. So, bit[4] is the parent of bit[3], and bit[8] is the parent of bit[4].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6n3Eo6yn7JHAkBikEUCFcA.png" /></figure><h3>Implementation</h3><p>To build the tree, assume a is all zeros and update the BIT by treating each a[i] as a delta.</p><pre>def query(bit, index):<br>    ans = 0<br>    while index &gt; 0:<br>        ans += bit[index]<br>        index -= index &amp; -index<br>    return ans<br><br>def update(bit, index, delta):<br>    while index &lt; len(bit):<br>        bit[index] += delta<br>        index += index &amp; -index<br><br><br># build tree<br>a = [-2, 5, 9, 2, -1, 3, -7, 6]<br>n = len(a)<br>bit = [0] * (n + 1)<br>for index, num in enumerate(a):<br>    # `bit` uses a 1-based index, while `a` is 0-based.<br>    update(bit, index+1, num)<br><br>print(query(bit, 5)- query(bit, 2))</pre><p><strong>Binary Indexed Trees</strong> help solve complex problems efficiently. You can practice them on LeetCode: <a href="https://leetcode.com/problem-list/binary-indexed-tree/">Binary Indexed Tree Problems</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15fc1d77cad1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Tips to make your Go code shorter]]></title>
            <link>https://medium.com/@0xbees/8-tips-to-make-your-go-code-shorter-8e62f0e0e771?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e62f0e0e771</guid>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 11:20:18 GMT</pubDate>
            <atom:updated>2025-02-04T07:42:51.407Z</atom:updated>
            <content:encoded><![CDATA[<h4>Improve readability with Go built-in functions and standard libraries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTQsKjg9YgPozG9wpkQ13w.png" /></figure><p>Go is built for simplicity while delivering good enough performance, but it can sometimes lead to verbose code. Luckily, <a href="https://pkg.go.dev/std">Go standard library</a> makes some tasks easier for us, and they still keep adding more features. Let’s see how builtin, slices, maps, and cmp help us develop high quality code. (Go version is 1.23 at the time of writing)</p><h3>1. Max (or Min) Value</h3><ul><li>Native way:</li></ul><pre>a, b := 1, 2<br><br>maxValue := a<br>if a &lt; b {<br>    maxValue = b<br>}<br><br>minValue := a<br>if a &gt; b {<br>    minValue = b<br>}</pre><ul><li>Concise way: applicable for <a href="https://pkg.go.dev/cmp#Ordered">cmp.Ordered</a> type</li></ul><pre>a, b, c := 1, 2, 3<br>maxValue := max(a, b, c)<br>minValue := min(a, b, c)</pre><h3>2. Slice: Max (or Min) Elements</h3><ul><li>Native way:</li></ul><pre>s := []int{1, 0, 2, -1, 0}<br><br>maxValue := s[0]<br>for i := 1; i &lt; len(s); i++ {<br>    maxValue = max(maxValue, s[i])<br>}<br><br>minValue := s[0]<br>for i := 1; i &lt; len(s); i++ {<br>    minValue = min(minValue, s[i])<br>}</pre><ul><li>Concise way:</li></ul><pre>s := []int{1, 0, 2, -1, 0}<br>maxValue := slices.Max(s)<br>minValue := slices.Min(s)</pre><h3>3. Slice: Process in Chunks</h3><ul><li>Native way:</li></ul><pre>s := []int{1, 0, 2, -1, 0}<br>size := 2<br>for i := 0; i &lt; len(s); i += size {<br>    j := i + size<br>    if j &gt; len(s) {<br>        j = len(s)<br>    }<br>    chunk := s[i:j]<br>    fmt.Print(chunk)<br>}<br>// Output: [1 0][2 -1][0]</pre><ul><li>More concise way:</li></ul><pre>s := []int{1, 0, 2, -1, 0}<br>size := 2<br>for i := 0; i &lt; len(s); i += size {<br>    chunk := s[i:min(i+size, len(s))]<br>    fmt.Print(chunk)<br>}</pre><ul><li>The most concise way:</li></ul><pre>s := []int{1, 0, 2, -1, 0}<br>for chunk := range slices.Chunk(s, 2) {<br>    fmt.Print(chunk)<br>}</pre><h3>4. Map: Keys (or Values) to Slice</h3><ul><li>Native way:</li></ul><pre>m := map[string]int{&quot;a&quot;: 1, &quot;b&quot;: 2}<br><br>keys := make([]string, 0, len(m))<br>for key := range m {<br>    keys = append(keys, key)<br>}<br><br>values := make([]int, 0, len(m))<br>for _, value := range m {<br>    values = append(values, value)<br>}</pre><ul><li>Concise way:</li></ul><pre>m := map[string]int{&quot;a&quot;: 1, &quot;b&quot;: 2}<br>keys := slices.Collect(maps.Keys(m))<br>values := slices.Collect(maps.Values(m))</pre><h3>5. Map: Get or Non-Zero Default</h3><ul><li>Native way:</li></ul><pre>m := map[string]*big.Int{&quot;a&quot;: big.NewInt(1), &quot;b&quot;: big.NewInt(2)}<br>value := m[&quot;c&quot;]<br>if value == nil {<br>    value = big.NewInt(2)<br>}</pre><ul><li>Concise way: be careful with non-pointer type</li></ul><pre>m := map[string]*big.Int{&quot;a&quot;: big.NewInt(1), &quot;b&quot;: big.NewInt(2)}<br>value := cmp.Or(m[&quot;c&quot;], big.NewInt(2))</pre><h3>6. Map: Merge</h3><ul><li>Native way:</li></ul><pre>src := map[string]int{&quot;a&quot;: 1, &quot;b&quot;: 2}<br>dst := map[string]int{&quot;c&quot;: 3, &quot;d&quot;: 4}<br>for k, v := range src {<br>    dst[k] = v<br>}</pre><ul><li>Concise way:</li></ul><pre>src := map[string]int{&quot;a&quot;: 1, &quot;b&quot;: 2}<br>dst := map[string]int{&quot;c&quot;: 3, &quot;d&quot;: 4}<br>maps.Insert(dst, maps.All(src))</pre><h3>7. Map: Shallow Clone</h3><ul><li>Native way:</li></ul><pre>m1 := map[string]int{&quot;a&quot;: 1, &quot;d&quot;: 2}<br>m2 := make(map[string]int, len(m1))<br>for key, value := range m1 {<br>    m2[key] = value<br>}</pre><ul><li>Concise way:</li></ul><pre>m1 := map[string]int{&quot;a&quot;: 1, &quot;d&quot;: 2}<br>m2 := maps.Clone(m1)</pre><h3>8. Handle Multiple Errors</h3><p>Given an error slice after handling multiple requests. If there are any errors, we want to return them all as an error. Otherwise return nil.</p><ul><li>Native way:</li></ul><pre>func processBatch() error {<br>    // after handling requests:<br>    errs := []error{nil, errors.New(&quot;err1&quot;), errors.New(&quot;err2&quot;)}<br><br>    msgs := make([]string, 0, len(errs))<br>    for _, e := range errs {<br>        if e != nil {<br>            msgs = append(msgs, e.Error())<br>        }<br>    }<br><br>    var err error<br>    if len(msgs) &gt; 0 {<br>        err = errors.New(strings.Join(msgs, &quot;\n&quot;))<br>    }<br><br>    return err<br>}<br><br>// fmt.Println(processBatch())<br>// Output:<br>//   err1<br>//   err2<br></pre><ul><li>Concise way:</li></ul><pre>func processBatch() error {<br>    errs := []error{nil, errors.New(&quot;err1&quot;), errors.New(&quot;err2&quot;)}<br>    return errors.Join(errs...)<br>}<br>// errors.Join(nil, nil, nil) --&gt; nil</pre><p>With these tips, we can make our code shorter and improve readability. This will ease the maintenance process and boost the team collaboration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e62f0e0e771" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Logging with Grafana Loki]]></title>
            <link>https://medium.com/@0xbees/golang-logging-with-grafana-loki-71f01a1ec749?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/71f01a1ec749</guid>
            <category><![CDATA[grafana-loki]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 16:11:21 GMT</pubDate>
            <atom:updated>2025-01-23T10:36:42.868Z</atom:updated>
            <content:encoded><![CDATA[<h4>Low-cost logging system with Loki and a lean way to log in Golang</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0cLMxYAThcMoElco5tmZg.png" /></figure><p>When developing with Golang, I usually use context and log at the same time. Passing both these params across functions is ugly. Moreover, storing and querying logs manually on a server is painful. I can use ELK stack, but it consumes a lot of server resources. After researching around, I resolve my pain with this solution: <strong>Golang </strong><a href="https://github.com/rs/zerolog"><strong>zerolog</strong></a> and <strong>Grafana </strong><a href="https://grafana.com/docs/loki"><strong>Loki</strong></a>.</p><h3>Logging with zerolog</h3><p>The zerolog package provides a fast and simple logger by avoiding allocations and reflection. Here are the 3 most useful features:</p><ul><li><strong>Structured logs</strong>: zerolog supports JSON format and can switch to pretty mode in development environment. Structured logs are easier to index, search, and extract meaningful insights.</li></ul><pre>package main<br><br>import (<br>    &quot;os&quot;<br>    &quot;github.com/rs/zerolog&quot;<br>    &quot;github.com/rs/zerolog/log&quot;<br>)<br><br>func main() {<br>    log.Info().Msg(&quot;hello world&quot;)<br>    log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})<br>    log.Info().Msg(&quot;hello world&quot;)<br>    log.Warn().Msg(&quot;some warnings&quot;)<br>    log.Error().Msg(&quot;some errors&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKcNtCk6bGCfwcNBTGXbRg.png" /></figure><ul><li><strong>Contextual sub-loggers</strong>: allow us to add key:value data (context) to logs and pass sub-loggers to child functions. These sub-loggers can be added more data without affecting their parents.</li></ul><pre>func main() { child(log.With().Str(&quot;process&quot;, &quot;main&quot;).Logger()) }<br>func child(logger zerolog.Logger) { logger.Info().Msg(&quot;running&quot;) }<br>// Output: {&quot;level&quot;:&quot;info&quot;,&quot;process&quot;:&quot;main&quot;,&quot;time&quot;:&quot;2025-01-12T21:39:47+08:00&quot;,&quot;message&quot;:&quot;running&quot;}</pre><ul><li><strong>Integration with </strong><strong>context.Context: </strong>The Logger instance can be attached to a Go context, which is commonly passed throughout Go code.</li></ul><pre>logger := log.With().Str(&quot;func&quot;, &quot;run&quot;).Logger()<br>ctx := logger.WithContext(context.Background())<br>log.Ctx(ctx).Info().Msg(&quot;running&quot;)<br>// Output: {&quot;level&quot;:&quot;info&quot;,&quot;func&quot;:&quot;run&quot;,&quot;time&quot;:1736688826,&quot;message&quot;:&quot;running&quot;}</pre><h3>Logging Stack with Grafana Loki</h3><p>Loki is built to index log metadata (labels) only, not full text index. Log data itself is then compressed and stored in chunks in object stores such as S3 or filesystem. This approach is suitable for low-cost products due to low resource consumption.</p><p>Many applications are deployed with Docker. In this example (<a href="https://github.com/apeview/zerolog-loki.git">Github</a>), we will use <strong>Promtail</strong> to ship Go server logs (<strong>zerolog</strong>) in a Docker container to <strong>Loki,</strong> then we query logs with <strong>Grafana</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6inX47_lpzSY_qroYAdg6g.png" /></figure><ul><li><strong>compose.yaml</strong> (Docker): Our Go app has “promtail” label. Promtail will collect logs from the containers having that label only (explain later). We mount /loki in Loki container into filesystem to keep all collected logs. For Promtail, we wire host’s Docker with its container, which enables Promtail to read logs from the others.</li></ul><pre>name: logging<br>services:<br>  app:<br>    build: .<br>    ports: [8080:8080]<br>    labels: { logging: &quot;promtail&quot; }<br><br>  loki:<br>    image: grafana/loki:3.3.2<br>    command: -config.file=/etc/loki/local-config.yaml<br>    volumes: [./data/loki:/loki]<br><br>  promtail:<br>    image: grafana/promtail:3.3.2<br>    command: -config.file=/etc/promtail/docker-config.yaml<br>    volumes:<br>      - ./configs/promtail.yaml:/etc/promtail/docker-config.yaml<br>      - /var/lib/docker/containers:/var/lib/docker/containers:ro<br>      - /var/run/docker.sock:/var/run/docker.sock<br>    depends_on: [loki]<br><br>  grafana:<br>    image: grafana/grafana:11.4.0<br>    ports: [3000:3000]<br>    volumes:<br>      - ./configs/grafana.yaml:/etc/grafana/provisioning/datasources/datasources.yaml</pre><ul><li><strong>configs/promtail.yaml</strong>: We create a job to collect and filter logs from containers having logging=promtail only. We also index 2 labels: container from Docker metadata and level from JSON logs.</li></ul><pre># https://grafana.com/docs/loki/latest/clients/promtail/configuration/<br><br>clients:<br>  - url: http://loki:3100/loki/api/v1/push<br><br>scrape_configs:<br>  - job_name: docker<br>    docker_sd_configs:<br>      - host: unix:///var/run/docker.sock<br>        refresh_interval: 5s<br>        filters:<br>          - name: label<br>            values: [&quot;logging=promtail&quot;]<br>    relabel_configs:<br>      - source_labels: [&quot;__meta_docker_container_name&quot;]<br>        regex: &quot;/(.*)&quot;<br>        target_label: &quot;container&quot;<br>    pipeline_stages:<br>      - json: { expressions: { level: level } }<br>      - labels: { level }</pre><ul><li><strong>configs/grafana.yaml</strong>: Add Loki as datasource.</li></ul><pre>apiVersion: 1<br><br>datasources:<br>  - name: Loki<br>    type: loki<br>    access: proxy<br>    url: http://loki:3100<br>    version: 1<br>    editable: false<br>    isDefault: true</pre><ul><li><strong>main.go</strong> (Go server example): uses go-gin to serve /ping API. We use zerolog to log some infos, warnings and errors with JSON format</li></ul><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;net/http&quot;<br>    &quot;time&quot;<br><br>    &quot;github.com/gin-gonic/gin&quot;<br>    &quot;github.com/rs/zerolog&quot;<br>    &quot;github.com/rs/zerolog/log&quot;<br>)<br><br>func main() {<br>    zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs<br>    gin.SetMode(gin.ReleaseMode)<br>    r := gin.New()<br><br>    // auto log after handling request<br>    r.Use(func(c *gin.Context) {<br>        start := time.Now()<br>        c.Next()<br>        log.Info().<br>            Int(&quot;status&quot;, c.Writer.Status()).<br>            Dur(&quot;latency&quot;, time.Since(start)).<br>            Str(&quot;client_ip&quot;, c.ClientIP()).<br>            Str(&quot;method&quot;, c.Request.Method).<br>            Str(&quot;path&quot;, c.Request.URL.Path).<br>            Msg(&quot;&quot;)<br>    })<br><br>    r.GET(&quot;/ping&quot;, func(c *gin.Context) {<br>        logger := log.With().Str(&quot;path&quot;, c.Request.URL.Path).Logger()<br>        ctx := logger.WithContext(c) // context with sub-logger<br>        check(ctx)<br>        c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;pong&quot;})<br>    })<br><br>    r.Run()<br>}<br><br>func check(ctx context.Context) {<br>    logger := log.Ctx(ctx)<br>    logger.Info().Msg(&quot;checking...&quot;)<br>    logger.Warn().Msg(&quot;there are some warnings&quot;)<br>    logger.Error().Msg(&quot;just minor errors&quot;)<br>    time.Sleep(1 * time.Second)<br>}</pre><p>Finally, go to Grafana dashboard: <a href="http://localhost:3000/explore">http://localhost:3000/explore</a> (login with admin/admin) to query some logs. We can filter by labels (fast), fields in JSON logs (slower), or even by text search (slowest).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFku2ZKPBacnzakGMXmaeg.png" /></figure><p>In summary, we can have a lean, efficient and low-cost logging system with Golang zerolog and Grafana Loki.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f01a1ec749" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get all ticks of Uniswap V3 pools]]></title>
            <link>https://medium.com/@0xbees/get-all-ticks-of-uniswap-v3-pools-7c24db734255?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c24db734255</guid>
            <category><![CDATA[uniswap-v3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[liquidity]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 18:07:27 GMT</pubDate>
            <atom:updated>2024-10-22T09:11:05.284Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to get all ticks, aka liquidity info, of Uniswap V3 pools directly from on-chain data with Javascript and Solidity.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqvCTFdag-oBckmG5ZOk-A.png" /></figure><p>To draw liquidity distribution or calculate quotes of a Uniswap V3 pool, we need to know all ticks’ info. Currently, we use subgraphs or custom indexers to scan the mint/burn events, which can be out of sync and costly. There are no methods to get all the info from pool contracts with ease. So, this blog will show a solution with 1 query to blockchain.</p><h3>Tick bitmap</h3><p>Bitmap is a compact way to index data. Uniswap V3 uses this technique to know which tick has liquidity. When a bitmap’s bit is 1, the corresponding tick has liquidity. Otherwise, there are no liquidity in the tick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mP82A_AkUSmiUVK5urqOQ.png" /></figure><p>We can use bitmap to scan all ticks faster. When a word is zero, we skip entire 256 ticks. Otherwise, we travel each bit. We only get tick info if its corresponding bit is 1. This reduces storage access and saves gas.</p><h3>Get all ticks at once</h3><p>Uniswap V3 provides 2 view functions: tickBitmap() to get a word and ticks() to get a tick info. So, we need tons of queries to RPCs even with the bitmap traveling method, which isn’t good. To avoid this, we will deploy a contract handling all works for us.</p><p>The first half of the below getAllTicks function calculates the number of initialized ticks (ticks with liquidity). This is because we have to know the array length before creating a dynamic array. Then, we travel all bitmaps again to get ticks’ info.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.27;<br><br>interface IPool {<br>    function tickSpacing() external view returns (int24);<br><br>    function tickBitmap(int16 wordPos) external view returns (uint256);<br><br>    function ticks(int24 tick) external view returns (uint128 liquidityGross, int128 liquidityNet);<br>}<br><br>struct Tick {<br>    int24 index;<br>    uint128 liquidityGross;<br>    int128 liquidityNet;<br>}<br><br>contract UniswapV3Lens {<br>    int24 internal constant MIN_TICK = -887272;<br>    int24 internal constant MAX_TICK = -MIN_TICK;<br><br>    function getAllTicks(IPool pool) external view returns (Tick[] memory ticks) {<br>        int24 tickSpacing = pool.tickSpacing();<br>        int256 minWord = int16((MIN_TICK / tickSpacing) &gt;&gt; 8);<br>        int256 maxWord = int16((MAX_TICK / tickSpacing) &gt;&gt; 8);<br><br>        uint256 numTicks = 0;<br>        for (int256 word = minWord; word &lt;= maxWord; word++) {<br>            uint256 bitmap = pool.tickBitmap(int16(word));<br>            if (bitmap == 0) continue;<br>            for (uint256 bit; bit &lt; 256; bit++) if (bitmap &amp; (1 &lt;&lt; bit) &gt; 0) numTicks++;<br>        }<br><br>        ticks = new Tick[](numTicks);<br>        uint256 idx = 0;<br>        for (int256 word = minWord; word &lt;= maxWord; word++) {<br>            uint256 bitmap = pool.tickBitmap(int16(word));<br>            if (bitmap == 0) continue;<br>            for (uint256 bit; bit &lt; 256; bit++) {<br>                if (bitmap &amp; (1 &lt;&lt; bit) == 0) continue;<br>                ticks[idx].index = int24((word &lt;&lt; 8) + int256(bit)) * tickSpacing;<br>                (ticks[idx].liquidityGross, ticks[idx].liquidityNet) = pool.ticks(ticks[idx].index);<br>                idx++;<br>            }<br>        }<br>    }<br>}</pre><p>I deployed the above UniswapV3Lens contract on Arbitrum network. You can check it at <a href="https://arbiscan.io/address/0xf632a03754090B44B605C0bA417Fffe369E26397#code">ArbiScan</a>. Let’s query some pools with Javascript and <a href="https://docs.ethers.org/v6/">ethers.js</a> library:</p><pre>const ethers = require(&quot;ethers&quot;);<br><br>async function main() {<br>  const abi = [&quot;function getAllTicks(address pool) external view returns (tuple(int24 index, uint128 liquidityGross, int128 liquidityNet)[] memory ticks)&quot;];<br>  const provider = new ethers.JsonRpcProvider(&quot;https://arb1.arbitrum.io/rpc&quot;);<br>  const lens = new ethers.Contract(&quot;0xf632a03754090B44B605C0bA417Fffe369E26397&quot;, abi, provider);<br>  await getTicks(lens, &quot;WETH-USDT-0.05%&quot;, &quot;0x641C00A822e8b671738d32a431a4Fb6074E5c79d&quot;);<br>  await getTicks(lens, &quot;USDC-USDT-0.01%&quot;, &quot;0xbE3aD6a5669Dc0B8b12FeBC03608860C31E2eef6&quot;);<br>}<br><br>async function getTicks(lens, name, pool) {<br>  const ticks = await lens.getAllTicks(pool);<br>  console.log(`${name}: ${ticks.length} ticks, ticks[0]: ${ticks[0]}`);<br>}<br><br>main();</pre><pre>WETH-USDT-0.05%: 1792 ticks, ticks[0]: -887270,36881048071624030145431278,36881048071624030145431278<br>USDC-USDT-0.01%: 723 ticks, ticks[0]: -887272,3053998183,3053998183</pre><h3>Get ticks partially</h3><p>Querying all ticks at once will work perfectly if the cost of retrieving all ticks is less than the gas limit. In the future, people will add more liquidity with new ticks, so we need a robust method to query. And, the solution is getting smaller sets of ticks multiple times until having full info.</p><p>We will add a new view function into the contract: getTicks(). This function allows us to get a predefined number of ticks from a tick index. It is nearly the same with getAllTicks(), except that we don’t need to calculate the array length.</p><pre>function getTicks(IPool pool, int24 tickStart, uint256 numTicks) external view returns (Tick[] memory ticks) {<br>    int24 tickSpacing = pool.tickSpacing();<br>    int256 maxWord = int16((MAX_TICK / tickSpacing) &gt;&gt; 8);<br>    tickStart /= tickSpacing;<br>    int256 wordStart = int16(tickStart &gt;&gt; 8);<br>    uint256 bitStart = uint8(uint24(tickStart % 256));<br><br>    ticks = new Tick[](numTicks);<br>    uint256 idx = 0;<br>    for (int256 word = wordStart; word &lt;= maxWord; word++) {<br>        uint256 bitmap = pool.tickBitmap(int16(word));<br>        if (bitmap == 0) continue;<br>        for (uint256 bit = word == wordStart ? bitStart : 0; bit &lt; 256; bit++) {<br>            if (bitmap &amp; (1 &lt;&lt; bit) == 0) continue;<br>            ticks[idx].index = int24((word &lt;&lt; 8) + int256(bit)) * tickSpacing;<br>            (ticks[idx].liquidityGross, ticks[idx].liquidityNet) = pool.ticks(ticks[idx].index);<br>            if (++idx &gt;= numTicks) return ticks;<br>        }<br>    }<br>}</pre><p>In our off-chain script, we query 1000 ticks each time. We only stop when the returned ticks is less than 1000. Here is the example:</p><pre>const ethers = require(&quot;ethers&quot;);<br><br>async function main() {<br>  const abi = [&quot;function getTicks(address pool, int24 tickStart, uint256 maxTicks) external view returns (tuple(int24 index, uint128 liquidityGross, int128 liquidityNet)[] memory ticks)&quot;];<br>  const provider = new ethers.JsonRpcProvider(&quot;https://arb1.arbitrum.io/rpc&quot;);<br>  const lens = new ethers.Contract(&quot;0xf632a03754090B44B605C0bA417Fffe369E26397&quot;, abi, provider);<br>  await getTicks(lens, &quot;WETH-USDT-0.05%&quot;, &quot;0x641C00A822e8b671738d32a431a4Fb6074E5c79d&quot;);<br>  await getTicks(lens, &quot;USDC-USDT-0.01%&quot;, &quot;0xbE3aD6a5669Dc0B8b12FeBC03608860C31E2eef6&quot;);<br>}<br><br>async function getTicks(lens, name, pool) {<br>  const step = 1000;<br>  let tickStart = -887272; // MIN_TICK<br>  let results = [];<br>  while (true) {<br>    let ticks = await lens.getTicks(pool, tickStart, step);<br>    ticks = ticks.filter((t) =&gt; t.liquidityGross &gt; 0n);<br>    console.log(`&gt;&gt;&gt; ${name}: got ${ticks.length} ticks`);<br>    results = results.concat(ticks);<br>    tickStart = results[results.length - 1].index + 1n;<br>    if (ticks.length &lt; step) break;<br>  }<br><br>  console.log(`${name}: ${results.length} ticks, ticks[0]: ${results[0]}`);<br>}<br><br>main();</pre><pre>&gt;&gt;&gt; WETH-USDT-0.05%: got 1000 ticks<br>&gt;&gt;&gt; WETH-USDT-0.05%: got 792 ticks<br>WETH-USDT-0.05%: 1792 ticks, ticks[0]: -887270,36881048071624030145431278,36881048071624030145431278<br>&gt;&gt;&gt; USDC-USDT-0.01%: got 723 ticks<br>USDC-USDT-0.01%: 723 ticks, ticks[0]: -887272,3053998183,3053998183</pre><p>This method helps retrieving liquidity of a Uniswap V3 pool faster and more efficient. We can draw liquidity distribution and calculate quotes without custom indexers or subgraphs. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c24db734255" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust Crash Course]]></title>
            <link>https://medium.com/@0xbees/rust-crash-course-359ba6c3a057?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/359ba6c3a057</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 05:31:20 GMT</pubDate>
            <atom:updated>2026-02-10T17:02:12.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quickstart tutorial for beginners</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9AGcxnZSVdxh3bOMFdmBw.png" /></figure><p>Rust is a multi-paradigm, general-purpose programming language, and it is used widely in recent years, especially in the blockchain world. Polkadot and Near smart contracts use Rust. Subgraph will Rust to build a server indexing data from blockchains. It is reasonable to explore Rust features.</p><h3>Cargo</h3><p>Cargo is Rust’s build system and the package manager. Cargo is installed together with Rust by the official installer. There are some CLI Cargo commands we can use, but the most common ones are:</p><ul><li>cargo new creates a new executable project with --bin flag or a new library project with --lib. Executables are binaries used to perform some tasks, e.g. server, commands. Libraries are common codes for other to use. For example, we develop NEAR smart contracts as libraries, then NEAR runtime will run our libs.</li><li>cargo run builds and run the program. If we develop libraries, we can use cargo build.</li></ul><p>A project created by Cargo will have the following scheme:</p><ul><li>src/ contains all our source code.</li><li>target/ contains all build output. It is ignored in .gitignore file.</li><li>Cargo.toml is the manifest containing metadata and dependencies of the project.</li><li>Cargo.lock is generated by Cargo automatically. It locks the versions of all dependencies.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wdgsVYGOSpUJ63Oy" /></figure><h3>Package structure</h3><p>We are all confused when reading a large project in a language we don’t know well, e.g. what is the entry point, this file is submodule of what file, etc. So, it’s reasonable to talk about package structure first.</p><h4>Executables</h4><p>After creating an executable with Cargo, we will have 1 file, main.rs, in the src/ directory. This main.rs is the default executable, which we can run it by cargo run --bin {project_name}. The function named main is the project entry point.</p><p>A project can have multiple commands. Each extra command is a .rs file in bin/ directory. For example, if we want a command named another-exe, we will need a main function in bin/another-exe.rs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kghPPJywdHY1Kd82" /></figure><p>At some points in development, we need to restructure large files into smaller ones. We cannot put a file named some_module.rs at bin/ level because Cargo will perceive it as a new some_module command created. If we want to create a multi-file-exe command, we need to create a directory named multi-file-exe in bin/. We will add bin/multi-file-exe/main.rs as the entry point and as many modules we need like bin/multi-file-exe/some_module.rs.</p><h4>Libraries</h4><p>After creating a library with Cargo, we will have 1 file, lib.rs, in the src/ directory. We can put anything like funtions in lib.rs, or group functions in namespaces. In Rust, namespaces is modules (mod).</p><p>At some points in development, there are some super large modules in single file lib.rs, and we may need seperate them into other files. To do this, we only need to create a file with the named of the module and put everything of this module into the created file. Then, include this module in lib.rs, for example use pub mod some_module to include everything of some_module module in some_module.rs.</p><p>If we want to seperate modules recursively, we need to create a directory. For example, if we want to seperate some_submodule in nested_module.rs, we will create nested_module directory. Then, put everything of some_submodule into some_submodule.rs, and the left code in nested_module/mod.rs. Remember to include pub mod some_submodule in mod.rs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*69nntskwo1G3odOZ" /></figure><h3>Common concepts</h3><p>This section will cover some notes about common concepts. For full details, refer to <a href="https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html">https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html</a></p><p>We can use let to declare a variable. By default, variables in Rust are immutable. If we want to mutate the value, we can use let mut. In most common cases, we don&#39;t need to specify type, because the complier will do this for us.</p><p>Native data types in Rust is divided into two main groups: Scalar and Compound. Scalar contains integer, float, boolean and character. Compound type contains tuple and array. Like Python, tuple can hold multiple types of its elements. Note that array in Rust is fixed size.</p><p>Rust distinguishes statements and expressions very clearly. Statements perform actions, while expressions only evaluate and return value. Morover, the last expression is the returned value of its block. For exapmle, in the below image, x is the returned value of the function. If we change return x+1; to x+1, Cargo won&#39;t compile. Because x+1 will be the returned value of if block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zre0idGuObCSL9e3" /></figure><h3>Ownership</h3><p>Ownership is the most interesting topic of Rust. It may be unfamiliar at first, but later, we will thank Rust for this feature. The idea of Rust is “memory safety without garbage collector”. In C, we have to clean up ourselves. In Go or JS, there are garbage collector, but this may cost runtime.</p><h4>Principles</h4><p>We will use stack and heap to explain the ownership feature. Stack are LIFO and used for fixed-size variables while heap contains growable variables or unknown size variables at the compiled time.</p><p>When we declare a number let num = 9;, the program will allocate an integer slot on stack. If we declare a growable vector, like let vector = vec![1, 2, 3, 5];, the program will ask for memory allocation on heap, then create a management variable (pointer, length, and capacity) on stack to point to data on heap.</p><p>And the below trick helps me understand ownership feature</p><ul><li>Owners are “on stack”, e.g. num, vector in the below image</li><li>Data has 1 owner. Data on stack own its self, and there cannot be multiple owner. In other languages, data on head can have multiple owner pointing to it, e.g. vector2, vector3, but Rust won’t allow that.</li><li>Owner dropped, so data dropped. No need for garbage collector.</li><li>In assignment, data is “moved” to new owner if it does not implement the Copy trait (interface). Let&#39;s move to the example section for clearer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kMDXJSNL6FJgs5qj" /></figure><h4>Examples</h4><p>After declaring num, we make an assignment let n = num. Because all native data types implement Copy trait, the data is copied from num to n. So, num still owns 9, and n owns a different 9.</p><p>After declaring vector, we make an assignment let own_v = vector. Because Vector does not implement Copy trait, the data is moved to the new owner own_v. If we try to use vector variable after this, we will receive compiling errors. We can &quot;borrow&quot; the data by making a reference let ref_v = &amp;own_v.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pivZG3kuhFjltmjT" /></figure><h3>Structs</h3><p>In Rust, there are 3 types of struct: named field, tuple-like, unit-like. Named field structs are like other languages. Tuple structs are useful to specify tuple type and remove too verbose field names. And, unit structs are useful to implement traits but not requiring data. Not that functions not requiring an object to call are associated functions, and they can be used as constructors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bigtyB2R2huh0Bex" /></figure><h3>Traits and Derive</h3><p>Traits in Rust are like interfaces in other languages. We can specify placeholder functions in traits or even define default implementation for them. To implement traits for struct, use impl {trait} for {struct}. We can override default implementation too.</p><p>Derive macros is the code that generate Rust code. Rust exports some useful traits and its implementation for us, e.g. Copy, Clone, Debug, etc. With Copy implementation, struct assignments are not moved to the new owner anymore. However, the Copy trait can be applied only for structs with all fields implementing Copy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OEp55s8u8I5UMgpj" /></figure><h3>Enums</h3><p>Like C/C++, enums in Rust are used to list variations of a type. But in Rust, enums are more powerful. Generally, we can define 3 types of struct as enum variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zHIZv0OKzVEmTo6L" /></figure><h3>Error handling</h3><p>Rust have two types of errors: unrecoverable using panic! and recoverable using Result enum. In smart contracts, people prefer unrecoverable one. In server development, they all use recoverable version, because Rust don&#39;t have something like try ... catch .... Rust defines ? for the common Result enum handling. For example, let f = File::open(&quot;hello.txt&quot;)?; is equivalent to</p><pre>let f = File::open(&quot;hello.txt&quot;);<br>let mut f = match f {<br>    Ok(file) =&gt; file,<br>    Err(e) =&gt; return Err(e),<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GI6Hee6_mhXkATNv" /></figure><p>Reference: <a href="https://doc.rust-lang.org/book/">doc.rust-lang.org/book</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=359ba6c3a057" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilize CPUs with Golang]]></title>
            <link>https://medium.com/codex/utilize-cpus-with-golang-050813e62522?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/050813e62522</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 12:16:01 GMT</pubDate>
            <atom:updated>2024-08-12T19:51:27.699Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimize multi-threads with Goroutines</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sz-bgyR7tML3cxJc-S-D0A.png" /></figure><p>Running jobs efficiently is an important part when developing large scale products. This post will show 4 methods which are usually used: sequence, burst all, burst n, and worker pool. These approaches can be done via various programming languages, but we will use Golang for demonstration. Golang has wonderful features supporting for concurrency natively. So, let’s go.</p><h3>Level 1: Sequence</h3><p>This method processes all jobs sequentially. It is very simple and perfectly fit for jobs having short processing time. However, it will waste a lot of CPU resource with IO bound jobs. The below program simulates job handling by delaying a specific time according to Duration data in item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bivRKRkW2azR239f" /></figure><ul><li>sequence.go</li></ul><pre>package main<br><br>import (<br>    &quot;log&quot;<br>    &quot;time&quot;<br>)<br><br>type item struct {<br>    ID       string<br>    Duration time.Duration<br>}<br><br>func main() {<br>    items := []item{{&quot;A&quot;, 1}, {&quot;B&quot;, 2}, {&quot;C&quot;, 1}, {&quot;D&quot;, 3}, {&quot;E&quot;, 2}}<br><br>    start := time.Now()<br>    for _, data := range items {<br>        process(data)<br>    }<br>    log.Print(&quot;processed time: &quot;, time.Since(start))<br>}<br><br>func process(i item) {<br>    log.Print(i.ID, &quot; start&quot;)<br>    time.Sleep(i.Duration * time.Second)<br>    log.Print(i.ID, &quot; end&quot;)<br>}</pre><pre>$ go run sequence.go<br>2022/03/18 18:37:47 A start<br>2022/03/18 18:37:48 A end<br>2022/03/18 18:37:48 B start<br>2022/03/18 18:37:50 B end<br>2022/03/18 18:37:50 C start<br>2022/03/18 18:37:51 C end<br>2022/03/18 18:37:51 D start<br>2022/03/18 18:37:54 D end<br>2022/03/18 18:37:54 E start<br>2022/03/18 18:37:56 E end<br>2022/03/18 18:37:56 processed time: 9.005201125s</pre><h3>Level 2: Burst all jobs</h3><p>This method will handle all jobs at the same time. It may cause a pike of CPU usage, but it guarantees the shortest processing time. It is perfectly fit for small size of items. However, it will face problems with IO rate limit due to issuing a huge number of requests to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TAjmqGP9HB9BAuAv" /></figure><ul><li>burst_all.go</li></ul><pre>package main<br><br>import (<br>    &quot;log&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)<br><br>type item struct {<br>    ID       string<br>    Duration time.Duration<br>}<br><br>func main() {<br>    items := []item{{&quot;A&quot;, 1}, {&quot;B&quot;, 2}, {&quot;C&quot;, 1}, {&quot;D&quot;, 3}, {&quot;E&quot;, 2}}<br>    start := time.Now()<br><br>    var wg sync.WaitGroup<br>    wg.Add(len(items))<br>    for _, data := range items {<br>        go func(i item) {<br>            defer wg.Done()<br>            process(i)<br>        }(data)<br>    }<br>    wg.Wait()<br><br>    log.Print(&quot;processed time: &quot;, time.Since(start))<br>}<br><br>func process(i item) {<br>    log.Print(i.ID, &quot; start&quot;)<br>    time.Sleep(i.Duration * time.Second)<br>    log.Print(i.ID, &quot; end&quot;)<br>}</pre><pre>$ go run burst_all.go<br>2022/03/18 18:38:30 E start<br>2022/03/18 18:38:30 A start<br>2022/03/18 18:38:30 D start<br>2022/03/18 18:38:30 C start<br>2022/03/18 18:38:30 B start<br>2022/03/18 18:38:31 C end<br>2022/03/18 18:38:31 A end<br>2022/03/18 18:38:32 E end<br>2022/03/18 18:38:32 B end<br>2022/03/18 18:38:33 D end<br>2022/03/18 18:38:33 processed time: 3.001483041s</pre><h3>Level 3: Burst n jobs sequentially</h3><p>This method will handle n jobs at the same time, then processes next n jobs until finishing all jobs. It solves rate limit problems of burst all method. It suits the case when n jobs have equal processing time. However, it will waste resources if one of n jobs has much longer processing time than others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W0eJmTyYLIGfBs_z" /></figure><ul><li>burst_n.go</li></ul><pre>package main<br><br>import (<br>    &quot;log&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)<br><br>type item struct {<br>    ID       string<br>    Duration time.Duration<br>}<br><br>func main() {<br>    items := []item{{&quot;A&quot;, 1}, {&quot;B&quot;, 2}, {&quot;C&quot;, 1}, {&quot;D&quot;, 3}, {&quot;E&quot;, 2}}<br>    n := 2<br>    start := time.Now()<br>    for s := 0; s &lt; len(items); s += n {<br>        e := s + 2<br>        if s+n &gt; len(items) {<br>            e = len(items)<br>        }<br>        processN(items[s:e])<br>    }<br>    log.Print(&quot;processed time: &quot;, time.Since(start))<br>}<br><br>func processN(items []item) {<br>    var wg sync.WaitGroup<br>    wg.Add(len(items))<br>    for _, data := range items {<br>        go func(i item) {<br>            defer wg.Done()<br>            process(i)<br>        }(data)<br>    }<br>    wg.Wait()<br>}<br><br>func process(i item) {<br>    log.Print(i.ID, &quot; start&quot;)<br>    time.Sleep(i.Duration * time.Second)<br>    log.Print(i.ID, &quot; end&quot;)<br>}</pre><pre>$ go run burst_n.go<br>2022/03/18 18:39:06 B start<br>2022/03/18 18:39:06 A start<br>2022/03/18 18:39:07 A end<br>2022/03/18 18:39:08 B end<br>2022/03/18 18:39:08 C start<br>2022/03/18 18:39:08 D start<br>2022/03/18 18:39:09 C end<br>2022/03/18 18:39:11 D end<br>2022/03/18 18:39:11 E start<br>2022/03/18 18:39:13 E end<br>2022/03/18 18:39:13 processed time: 7.003122542s</pre><h3>Level 4: Worker pool</h3><p>This method is like “burst n” method but solves unequal processing time cases. It has nice performance in most cases, but may make the code more complex. Like greedy algorithm, be careful about the order of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LM7mE7muD-ccHA6z" /></figure><ul><li>worker_n.go</li></ul><pre>package main<br><br>import (<br>    &quot;log&quot;<br>    &quot;time&quot;<br>)<br><br>type item struct {<br>    ID       string<br>    Duration time.Duration<br>}<br><br>func main() {<br>    items := []item{{&quot;A&quot;, 1}, {&quot;B&quot;, 2}, {&quot;C&quot;, 1}, {&quot;D&quot;, 3}, {&quot;E&quot;, 2}}<br>    n := 2<br>    data := make(chan item, len(items))<br>    results := make(chan error, len(items))<br>    start := time.Now()<br><br>    for w := 1; w &lt;= n; w++ {<br>        go worker(data, results)<br>    }<br><br>    for _, d := range items {<br>        data &lt;- d<br>    }<br>    close(data)<br><br>    for i := 1; i &lt;= len(items); i++ {<br>        &lt;-results<br>    }<br><br>    log.Print(&quot;processed time: &quot;, time.Since(start))<br>}<br><br>func worker(data &lt;-chan item, results chan&lt;- error) {<br>    for d := range data {<br>        process(d)<br>        results &lt;- nil<br>    }<br>}<br><br>func process(i item) {<br>    log.Print(i.ID, &quot; start&quot;)<br>    time.Sleep(i.Duration * time.Second)<br>    log.Print(i.ID, &quot; end&quot;)<br>}</pre><pre>$ go run worker_n.go<br>2022/03/18 18:39:33 A start<br>2022/03/18 18:39:33 B start<br>2022/03/18 18:39:34 A end<br>2022/03/18 18:39:34 C start<br>2022/03/18 18:39:35 B end<br>2022/03/18 18:39:35 D start<br>2022/03/18 18:39:35 C end<br>2022/03/18 18:39:35 E start<br>2022/03/18 18:39:37 E end<br>2022/03/18 18:39:38 D end<br>2022/03/18 18:39:38 processed time: 5.002048s</pre><p>That’s all. Use 4 approaches wisely — trade off between complexity and performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=050813e62522" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/utilize-cpus-with-golang-050813e62522">Utilize CPUs with Golang</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Pancake V3 Pool and Farm works with visualization]]></title>
            <link>https://medium.com/@0xbees/how-pancake-v3-farm-works-with-visualization-235e5e25d701?source=rss-23ef08409897------2</link>
            <guid isPermaLink="false">https://medium.com/p/235e5e25d701</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[dex]]></category>
            <category><![CDATA[farming]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[pancakeswap]]></category>
            <dc:creator><![CDATA[Bee]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 10:37:10 GMT</pubDate>
            <atom:updated>2024-08-01T10:44:32.529Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explain Pancake V3 Farm architecture in simple figures</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmjwYQKytYZ6Fu4XOcZojg.png" /></figure><p>PancakeSwap is one of the most popular DEX on BSC. It provides liquidity protocol and farming tools for users. Pancake V3 inherits a lot from Uniswap V3. So, if you have some Uniswap knowledge, it would be easier for you to explore how Pool and Farm V3 on Pancake works.</p><h3>Pool Factory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSzpbmFvnBH33EOAtGSM9g.png" /></figure><p>Pancake V3 Factory inherits Uniswap V3 Factory and adds features related to TickSpacing and FeeTier. The Pancake’s owner can add/remove fee tiers besides 4 default ones: 0.01%, 0.05%, 0.25%, and 1%. They can limit addresses to create pools for special tiers too. For ProtocolFee, we will discuss in next sections.</p><p>Users can create a V3 pool through the factory with parameters: token0, token1, tick spacing and fee tier. Actually, they only need to specify fee tier, because tick spacing is predefined for a specific tier. The higher fee, the more volatile a pool, which means its token prices change quickly. So, we need larger tick spacing to save gas when jumping wider price range. For example, (FeeTier, TickSpacing) = (0.01%,1) or (1%, 200).</p><h3>Pool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-biaMyqMkkHDq2yJGXL2A.png" /></figure><p>After a pool is created, LPers can add/remove liquidity to/from the pool by using mint()/burn() methods. The Pool contract will store LPer’s position info: owner (LPer), tick lower and upper (min and max price), liquidity (a number indicating how much amount of token0 and token1). To utilize NFT standard, they wraps the position under an NFT, which can be transferred and traded on marketplace, with NonfungiblePositionManager contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cYsCBggU1_xCqbAECVlxg.png" /></figure><p>When a swap occurs in a pool, swappers will pay fees for LPers based on the FeeTier. If Pancake sets ProtocolFee &gt; 0, the contract will split this fee into 2 parts: one for LPers and one for protocol itself.</p><h3>LmPool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3jR4WcILyNhB69T83ohjw.png" /></figure><p>To attract liquidity, Pancake incentivizes LPers with extra rewards — CAKE. Given the CAKE amount, Pancake distributes this reward to LPers like the way of distributing fee with LmPool (liquidity mining pool) contract. You can learn more about UniswapV3 fee at this <a href="https://www.youtube.com/watch?v=dT_FoDW1EQg&amp;list=PLO5VPQH6OWdXp2_Nk8U7V-zh7suI05i0E&amp;index=29">video</a>. Note that LmPool only calculates reward for staked positions.</p><h3>MasterchefV3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_Wsy5OcjdbPU7MwbdvNeQ.png" /></figure><p>MasterchefV3 is used to manage LmPool. Only the owner can add and set allocation for a pool. The mechanism of Masterchef V3 is nearly the same with V2: use rewardsPerSecond and allocation to calculate total pool reward. By contrast with V2, which needs CAKE minting permission, Pancake’s owner can send CAKE to V3 and update the reward rates.</p><p>After NFT’s deposited into MasterchefV3, users no longer have direct access to their NFT, but still “own” it. To increase/decrease liquidity or collect trading fees, users have to interact with MasterchefV3. The CAKE rewards are claimed during these operation too. When users don’t want to farm anymore, they can just withdraw the NFT to their account.</p><p>In summary, the whole system is like the below image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zye0a_kZSGuG8hbPv5c0Cw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235e5e25d701" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>