<?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 Ido Zamir on Medium]]></title>
        <description><![CDATA[Stories by Ido Zamir on Medium]]></description>
        <link>https://medium.com/@idowzamir?source=rss-7777e7df38b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Ido Zamir on Medium</title>
            <link>https://medium.com/@idowzamir?source=rss-7777e7df38b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:44:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@idowzamir/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[Solidity Proxy Pattern: A Beginner’s Tutorial]]></title>
            <link>https://coinsbench.com/solidity-proxy-pattern-a-beginners-tutorial-b0e376ffaa06?source=rss-7777e7df38b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0e376ffaa06</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <dc:creator><![CDATA[Ido Zamir]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 12:04:19 GMT</pubDate>
            <atom:updated>2025-01-13T11:51:54.130Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNK1NATdPNSw6M6wwqI6sQ.jpeg" /><figcaption>Robot operator delegates calls, DALL-E</figcaption></figure><p>The proxy pattern helps solve a key challenge with Ethereum smart contracts: their immutability after deployment. While we can’t modify deployed contracts, we can implement upgradeable systems using proxies. Understanding Proxy pattern is essential for understanding the diamond pattern (<strong>EIP-2535</strong>) which extends proxies to support multiple implementation contracts instead of just one.</p><p>A proxy contract stores the address of an implementation contract and delegates all calls to it. When users interact with the proxy, it forwards their calls to the implementation contract using delegatecall. The implementation executes the logic, but within the proxy&#39;s storage context - meaning all state is stored in and read from the proxy&#39;s storage.</p><p>To upgrade the system, we simply deploy a new implementation contract and update the proxy’s reference. The proxy’s storage remains unchanged, preserving all data while allowing us to modify the business logic.</p><p>This tutorial uses <a href="https://remix.ethereum.org/">Remix IDE</a> without external libraries to demonstrate the core mechanics of the proxy pattern. By implementing it from scratch, we’ll gain deeper insight into how proxies actually work under the hood. We shall begin with the Proxy contract and build a a custom library to aid it. Then we will try it with several contracts. Notice that I will not relate to Transparent Proxy or UUPS (Universal Upgradeable Proxy Standard) at this tutorial but I will say that our proxy will be a Transparent Proxy.</p><h3>Proxy and supporting library</h3><p>In a folder named libraries we shall create a file named StorageSlot.sol.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity &gt;=0.8.0 &lt;0.9.0;<br><br>library StorageSlot {<br>    struct AddressSlot {<br>        address value;<br>    }<br><br>    function getAddressSlot(bytes32 slot)<br>        internal<br>        pure<br>        returns (AddressSlot storage addr)<br>    {<br>        assembly {<br>            addr.slot := slot<br>        }<br>    }<br>}</pre><p>The library’s purpose is to provide a way to access arbitrary storage slots. The bytes32 parameter determines which storage slot to access, and we return an AddressSlot storage reference pointing to that slot. The assembly code addr.slot := slot tells the EVM <em>&quot;this AddressSlot struct should read/write from the storage slot specified by our bytes32 parameter”</em>.</p><pre>contract StorageExample {<br>    uint256 first;         // slot 0<br>    address second;        // slot 1<br>    mapping(address =&gt; uint256) balances; <br>    // declares slot 2, but doesn&#39;t store values there<br>    <br>    // If we store balances[0x123...] = 100<br>    // The value 100 would be stored at: keccak256(abi.encode(0x123..., 2))<br>}</pre><blockquote>Assembly is needed here because Solidity doesn’t allow direct manipulation of arbitrary storage slots in regular code. The assembly block lets us explicitly set which storage slot the AddressSlot struct will use, allowing dynamic storage slot allocation — the ability to assign specific storage slots at runtime, ensuring separate logic and storage layers.</blockquote><p>Create a folder named contracts and inside create a file named Proxy.sol.</p><pre>contract Proxy {<br>    bytes32 private constant IMPLEMENTATION_SLOT =<br>        bytes32(uint256(keccak256(&quot;eip1967.proxy.implementation&quot;)) - 1);<br><br>    function _getImplementation() private view returns (address) {<br>        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;<br>    }<br><br>    function _setImplementation(address _implementation) private {<br>        require(<br>            _implementation.code.length &gt; 0,<br>            &quot;implementation is not contract&quot;<br>        );<br>        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = _implementation;<br>    }<br>}</pre><p>The StorageSlot library provides a structured way to access storage slots using assembly. <a href="https://eips.ethereum.org/EIPS/eip-1967">EIP-1967</a> specifies a standard pattern: take a descriptive string (like &quot;eip1967.proxy.implementation&quot;), hash it with keccak256, subtract 1, and use that as the storage slot. The library defines an AddressSlot struct and uses inline assembly to directly set the slot where the address value will be stored. When setting a new implementation, it writes the address to that slot, and when reading, it retrieves the value from that specific slot in the proxy contract storage</p><p>In _setImplementation, we store _implementation (address of the contract we wish to use) at IMPLEMENTATION_SLOT. Since this slot is derived from a keccak256 hash minus 1, it maps to a very large index in the storage array, making accidental collisions with other state variables virtually impossible.</p><p>Now that we have made sure there will be no collisions with the implementation slot, we need to write a function that will do the following:</p><ol><li>Call a specific function in the implementation contract.</li><li>Execute it within the current contract (Proxy) context.</li><li>All changes made to storage, will reflect only in this contract.</li><li>If it fails, revert.</li></ol><p>In order to achieve it, we will use once again in Assembly which will allow us to use the following functions:</p><ul><li>calldatacopy: Specifically copies calldata from a given offset to memory.</li><li>delegatecall: Delegates the call to the implementation contract and also preserves msg.sender.</li><li>returndatacopy: Copies the return data from a given offset to memory</li></ul><pre>`calldatacopy(t, f, s)`: <br>  Copy s bytes of calldata from position f to memory position t<br><br>`delegatecall(g, a, s, r, o)`: <br>  Execute code at address a with gas g, returning success status<br><br>`returndatacopy(t, f, s)`: <br>  Copy s bytes of return data from position f to memory position t</pre><pre><br>fallback() external payable {<br>    _delegate();<br>}<br><br>receive() external payable {<br>    _delegate();<br>}<br><br>function _delegate() internal virtual {<br>    address _implementation = _getImplementation();<br>    assembly {<br>        calldatacopy(0, 0, calldatasize())<br>        let result := delegatecall(<br>            gas(), // Forward all gas<br>            _implementation, // Implementation contract address<br>            0, // READ input FROM position 0<br>            calldatasize(), // Length of input data<br>            0, // This is just a placeholder - data isn&#39;t actually stored here yet<br>            0 // We&#39;ll determine output size after the call (We don&#39;t know the size yet)<br>        )<br>        returndatacopy(0, 0, returndatasize())<br><br>        switch result<br>        // delegatecall returns 0 on error.<br>        case 0 {<br>            // revert(p, s) - end execution, revert state changes<br>            revert(0, returndatasize())<br>        }<br>        default {<br>            // return(p, s) - end execution<br>            return(0, returndatasize())<br>        }<br>    }<br>}</pre><h4>Counters Contracts</h4><p>In create folder counters within contracts folder with two files: Counter_v1.sol and Counter_v2.sol.</p><pre>contract CounterV1 {<br>    uint256 public count;<br><br>    function inc() external {<br>        count += 1;<br>    }<br>}</pre><pre>contract CounterV2 {<br>    uint256 public count;<br><br>    function inc() external {<br>        count += 1;<br>    }<br><br>    function dec() external {<br>        count -= 1;<br>    }<br>}</pre><p>The only difference between them is dec function which was added to CounterV2.</p><h4>Show time</h4><p>Compile all three files (Counter_v1.sol, Counter_v2.sol and Proxy.sol) and deploy Counter_v1.sol and Proxy.sol. Create a folder names abis, and copy CounterV1 ABI to Counter_v1.abi. Quick look at CounterV1 ABI:</p><pre>[<br> {<br>  &quot;inputs&quot;: [],<br>  &quot;name&quot;: &quot;count&quot;,<br>  &quot;outputs&quot;: [<br>   {<br>    &quot;internalType&quot;: &quot;uint256&quot;,<br>    &quot;name&quot;: &quot;&quot;,<br>    &quot;type&quot;: &quot;uint256&quot;<br>   }<br>  ],<br>  &quot;stateMutability&quot;: &quot;view&quot;,<br>  &quot;type&quot;: &quot;function&quot;<br> },<br> {<br>  &quot;inputs&quot;: [],<br>  &quot;name&quot;: &quot;inc&quot;,<br>  &quot;outputs&quot;: [],<br>  &quot;stateMutability&quot;: &quot;nonpayable&quot;,<br>  &quot;type&quot;: &quot;function&quot;<br> }<br>]</pre><p>As we can see, it is an array which includes count variable and inc function. In Solidity the compiler auto-generates getter functions for every public state-variable in the contract.</p><p>Copy CounterV1 address to Proxy upgradeTo in order to connect the two</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*3q7GKBQmIBbEmygUGiDg5Q.png" /></figure><p>Open Counter_v1.abi, copy Proxy contract address and paste it in ‘At Address’ box. Then this popup should be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqcsO_Wa2B5QmPEmOgXCSg.png" /></figure><p>Notice that we now have a third contract, with the same functions as CounterV1 has.</p><p>Click on inc function a few times and then hit count. In my case, the count shows 3. Go ahead and click on count in CounterV1 contract, the result is 0 since we have not changed anything in its’ state.</p><p>Deploy CounterV2 contract, and use its’ address in the Proxy contract upgradeTo and At Address with CounterV2 ABI. Click on the new &lt;At Address&gt; contract count and you get the same result as you had before.</p><h4>Hows does it look with ether?</h4><p>Create a folder named safe within contracts with two files: Safe_v1.sol and Safe_v2.sol.</p><pre>contract SafeV1 {<br>    mapping(address =&gt; uint256) private balances;<br>    address private owner;<br><br>    event Deposit(address indexed user, uint256 amount);<br>    event Withdrawal(address indexed user, uint256 amount);<br>    event OwnerWithdrawal(address indexed owner, uint256 amount);<br><br>    function initialize(address _owner) public {<br>        require(owner == address(0), &quot;Already initialized&quot;);<br>        owner = _owner;<br>    }<br><br>    modifier onlyOwner() {<br>        require(msg.sender == owner, &quot;Not the owner&quot;);<br>        _;<br>    }<br><br>    function deposit() public payable {<br>        require(msg.value &gt; 0, &quot;Must send some Ether&quot;);<br>        balances[msg.sender] += msg.value;<br>        emit Deposit(msg.sender, msg.value);<br>    }<br><br>    function getBalance() public view returns (uint256) {<br>        return balances[msg.sender];<br>    }<br>}</pre><p>Avoid constructors in implementation contracts because they won’t be called when used via a proxy. Use an initializer function instead (initialize). Compile SafeV1 and Proxy, deploy them and interact as seen earlier. I deposited 1 ether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*ic-67VbT1b7t4_n_BtvNKQ.png" /></figure><p>Whoops, we forgot to include a withdraw function. Luckily we use a Proxy contract.</p><pre>contract SafeV2 {<br>    mapping(address =&gt; uint256) private balances;<br>    address private owner;<br><br>    event Deposit(address indexed user, uint256 amount);<br>    event Withdrawal(address indexed user, uint256 amount);<br><br>    function initialize(address _owner) public {<br>        require(owner == address(0), &quot;Already initialized&quot;);<br>        owner = _owner;<br>    }<br><br>    modifier onlyOwner() {<br>        require(msg.sender == owner, &quot;Not the owner&quot;);<br>        _;<br>    }<br><br>    function deposit() public payable {<br>        require(msg.value &gt; 0, &quot;Must send some Ether&quot;);<br>        balances[msg.sender] += msg.value;<br>        emit Deposit(msg.sender, msg.value);<br>    }<br><br>    function withdraw(uint256 amount) public {<br>        require(amount &gt; 0, &quot;Amount must be greater than zero&quot;);<br>        require(balances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br><br>        balances[msg.sender] -= amount;<br>        payable(msg.sender).transfer(amount);<br>        emit Withdrawal(msg.sender, amount);<br>    }<br><br>    function getBalance() public view returns (uint256) {<br>        return balances[msg.sender];<br>    }<br>}</pre><p>Compile, deploy and upgrade Proxy to use this one. Click on getBalance, Ta-Da, it should 1 ether. Withdraw and click on getBalance. See that has the current amount?</p><h3>Conclusion</h3><p>I hope this tutorial helped you to understand the basics of Proxy contract pattern. It is essential to understand how this works, even in theory if you wish to delve more into Solidity or even blockchain. You can find the full code in my <a href="https://github.com/owolfy/solidity-proxy-tutorial">github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0e376ffaa06" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/solidity-proxy-pattern-a-beginners-tutorial-b0e376ffaa06">Solidity Proxy Pattern: A Beginner’s Tutorial</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router Framework with Authentication: A Short Tutorial]]></title>
            <link>https://medium.com/@idowzamir/react-router-framework-with-authentication-a-short-tutorial-feef4cc5b441?source=rss-7777e7df38b------2</link>
            <guid isPermaLink="false">https://medium.com/p/feef4cc5b441</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ido Zamir]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 14:06:10 GMT</pubDate>
            <atom:updated>2024-12-05T10:26:12.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Router v7 Framework with Authentication: A Quick Guide</h3><h4>Discover how React Router v7’s framework mode streamlines route protection and authentication for React apps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*5fNcgKFz6HgyrXLGDkDmQQ.jpeg" /><figcaption>React Router, DALL-E</figcaption></figure><p>In this tutorial, I’ll demonstrate Firebase authentication with Google sign-in using React Router 7.0.2. The complete code is available in the repository, along with code snippets throughout the guide.</p><p><strong>Setup</strong></p><pre>npx create-react-router@latest my-react-router-app</pre><p>Open the project folder and install Firebase. Then create a firebase folder, firebaseConfig.ts, and .env files.</p><pre>npm install firebase<br>mkdir firebase &amp;&amp; touch firebase/firebaseConfig.ts<br>touch .env</pre><pre># .env<br># Firebase API Keys<br>VITE_FIREBASE_API_KEY=FIREBASE-SECRET<br>VITE_FIREBASE_AUTH_DOMAIN=FIREBASE-SECRET<br>VITE_FIREBASE_PROJECT_ID=FIREBASE-SECRET<br>VITE_FIREBASE_STORAGE_BUCKET=FIREBASE-SECRET<br>VITE_FIREBASE_MESSAGING_SENDER_ID=FIREBASE-SECRET<br>VITE_FIREBASE_APP_ID=FIREBASE-SECRET</pre><p>Import all the keys to firebaseConfig.ts, create a Firebase Auth instance and export it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSTTscCen8cOy8iBdhwChg.png" /></figure><p><em>Optional</em>: Change ssr value to false in react-router.config.ts.</p><p><strong>Context Setup</strong></p><p>We will use context to manage and share user data across the application, ensuring that the user is logged in. It’s a straightforward and effective approach to handle authentication state. Simple as it sounds.</p><pre>// /contexts/auth/authContext.tsx<br>interface AuthContextType {<br>    user: AuthUser | null;<br>    setUser: (user: AuthUser | null) =&gt; void;<br>}<br><br>const AuthContext = createContext&lt;AuthContextType | null&gt;(null);<br><br>export default AuthContext;<br><br>// /contexts/auth/authProvider.tsx<br>export default function AuthProvider({ children }: { children: React.ReactNode }) {<br>    const [user, setUser] = useState&lt;AuthUser | null&gt;(null);<br>    useEffect(() =&gt; {<br>        const unsubscribe = onAuthStateChanged(fbAuth, (user: User | null) =&gt; {<br>            setUser(user ? {<br>                displayName: user.displayName,<br>                email: user.email,<br>                uid: user.uid<br>            } : null);<br>        });<br>        return () =&gt; unsubscribe();<br>    }, []);<br><br>    return (<br>        &lt;AuthContext.Provider value={{ user, setUser }}&gt;<br>            {children}<br>        &lt;/AuthContext.Provider&gt;<br>    );<br>};<br><br>// /contexts/auth/useAuth.tsx<br>export const useAuth = () =&gt; {<br>    const context = useContext(AuthContext);<br>    if (!context) {<br>        throw new Error(&#39;useAuth must be used within an AuthProvider&#39;);<br>    }<br>    return context;<br>};<br><br>export default useAuth;</pre><p><strong>Setting Up the App Structure</strong></p><p>The app consists of a public route and a protected route within the LoggedWrapper layout. I avoided using <a href="https://reactrouter.com/how-to/file-route-conventions">flatRoutes</a> to better illustrate how the app’s routes are structured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeeaYpvDIS14uo6fIAJnNw.png" /></figure><p>Next, we need to define the HydrateFallback component in the root.tsx file (I&#39;ll explain its purpose shortly).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoYaNV5G6zrDRoJKV_qmkw.png" /></figure><p>Quick setup of isAuth function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyP5nOpk9fEJF2nrc1Zzrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GYByMBZpNB8vq8HWGA2Tg.png" /></figure><p>On initial page load, we check the user’s authentication status using clientLoader, which runs only in the browser. This approach eliminates redundancy by avoiding the need to add an isLoading condition and a loading spinner separately for both the index and dashboard routes. Until the clientLoader completes, the component remains unrendered, and the HydrateFallback component is displayed instead.</p><p>For demonstration purposes, I deliberately mocked a slow response from Firebase to showcase the HydrateFallback in action. On the initial page load, it displays a loading spinner, providing a smoother user experience (UX).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKCW0yg201yDu4yagQ6h3A.png" /></figure><p>We’ll create a LoggedWrapper component that acts as a &quot;magic&quot; wrapper to protect its children. It ensures only authenticated users can access the wrapped routes. As before, we use clientLoader to handle the logic in the browser and display the HydrateFallback during the loading phase.</p><p>This time, we’ll use the useEffect hook to monitor the user’s status. If the user is null, the component will redirect them to the app&#39;s entry point. Otherwise, it will render its children using React Router&#39;s Outlet component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnTS_D6jssUdX5y0hLbWDQ.png" /></figure><p>By taking advantage of useEffect in LoggedWrapper, the Loginis minimalist and after successful login, simply navigate the user to route dashboard which lays inside LoggedWrapper layout.</p><pre>// /components/login/login.tsx<br>const handleGoogleLogin = async () =&gt; {<br>    try {<br>      const provider = new GoogleAuthProvider();<br>      await signInWithPopup(fbAuth, provider);<br>      navigate(&#39;/dashboard&#39;);<br>    } catch (err) {<br>      setError(&#39;Failed to login. Please try again.&#39;);<br>      console.error(&#39;Login error:&#39;, err);<br>    }</pre><p>Same goes for Logout, after the user signs out, we set the user in the context to null and navigate the user to the application entry point while the user stop seeing the logout button.</p><pre>// /components/logout/logout.tsx<br>export default function Logout() {<br>  const navigate = useNavigate();<br>  const { user, setUser } = useAuth();<br><br>  const handleLogout = async () =&gt; {<br>    try {<br>      await fbAuth.signOut();<br>      setUser(null);<br>      navigate(&#39;/&#39;);<br>    } catch (error) {<br>      console.error(&#39;Error logging out:&#39;, error);<br>    }<br>  };<br><br>  if (!user) {<br>    return &lt;&gt;&lt;/&gt;;<br>  }<br><br>  return (<br>    &lt;button<br>// rest of the code goes here...<br></pre><p>The Dashboard component re-renders whenever the authentication context changes. For instance, when a user logs out, the user value in the context is updated to null. This triggers a re-render, and the component displays a different template, ensuring the app reflects the user&#39;s current authentication state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WE8IwV2QSltreJOGqNU8hw.png" /></figure><p><strong>Conclusion</strong></p><p>You’ve learned how to integrate Firebase authentication with React Router v7, create protected routes, and manage user login/logout functionality. These concepts are essential for building secure and user-friendly web applications.</p><p><em>I hope you found this tutorial useful! Feel free to share your thoughts or questions in the comments — I’d love to hear your feedback and help with any challenges you face.</em></p><p><em>You can find the complete code for this tutorial in my </em><a href="https://github.com/owolfy/react-router-auth"><em>GitHub repository</em></a><em>. Be sure to check it out for reference or to clone and experiment with the project!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feef4cc5b441" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>