<?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 Milaabl on Medium]]></title>
        <description><![CDATA[Stories by Milaabl on Medium]]></description>
        <link>https://medium.com/@milaabl2405?source=rss-6f3d497ef646------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Milaabl on Medium</title>
            <link>https://medium.com/@milaabl2405?source=rss-6f3d497ef646------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:21:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milaabl2405/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[Building a secure 2-step E2E encryption system for .zip]]></title>
            <link>https://medium.com/@milaabl2405/building-a-secure-2-step-e2e-encryption-system-for-zip-3292d934661f?source=rss-6f3d497ef646------2</link>
            <guid isPermaLink="false">https://medium.com/p/3292d934661f</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[e2e]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[e2ee]]></category>
            <dc:creator><![CDATA[Milaabl]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 12:15:29 GMT</pubDate>
            <atom:updated>2024-03-05T12:15:29.530Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a secure 2-step E2E encryption system for .zip files with React, crypto-js, Web Crypto API on front-end AND native Shell on the back-end</h3><p>Let’s design and build a secure 2-step multi-end (a.k.a. E2E) encryption/decryption system that utilizes the AES-256-bit and RSA-OAEP cryptographic algorithms.</p><h4>❗It’s worth noting that this is actually a <strong>quasi-E2EE</strong> project, and is rather a <strong>Proof-Of-Concept</strong> demonstrating a working and multi-end compatible <em>symmetric</em> and <em>asymmetric</em> encryption system <em>(because the Shell’s native decryption commands are </em><strong><em>oh so tightly-coupled</em></strong><em> to the ones used on the front-end)</em>.</h4><p>The <strong>biggest challenge</strong> of building a multi-end <strong>(a.k.a. E2E, i.e. end-to-end)</strong> encryption/decryption system is making sure that the algorithms used for the encryption and decryption are 100% compatible, to make sure the original input and the decrypted output stay the same after a series of encryption and decryption operations, and, most importantly, do not corrupt.</p><p>Before moving on to a technical walk-through, consider the following architecture diagram as a preface:</p><figure><img alt="The architecture of the system, for reference" src="https://cdn-images-1.medium.com/max/750/1*4sbcduHHADrvakY0UPTGRQ.png" /><figcaption>The architecture of this encryption and decryption system</figcaption></figure><h3>Why do we need to build an E2E encryption system?</h3><ol><li>That is the only way to build a secure cryptographic encryption system that is both <strong>time-efficient</strong> enough <strong><em>(thanks to the combination of a symmetric and an asymmetric encryption algorithm)</em></strong> to be used in a <em>real-world</em> <strong>production</strong> application, and <strong>secure </strong>enough to be used for protecting sensitive user data <em>(at the same time)</em>;</li><li><em>[With the help of a </em><strong><em>E2EE</em></strong><em> key system]</em>, messages are protected from being opened by unauthorized devices. Malicious attackers just do not have the needed keys to decipher the data <em>even if it has been intercepted or accessed</em>;</li></ol><h3>But there’re some cons to E2EE, too…</h3><p>With the <strong>E2EE</strong>, the approach to storing the necessary encryption keys creates a major problem — the fact that the keys can be <em>coincidentally</em> erased from the user’s browser, and then the access to the <em>ciphered data</em> will be lost… <strong>forever</strong>.</p><p><strong>That is because the encryption key should be stored on the end device to decrypt the ciphered contents.</strong></p><h3>Still, the main difference between the E2EE and plain encryption is…</h3><p>That E2E encryption allows for secure <strong>data transfers between multiple ends</strong> (e.g. front-end and back-end <strong>data communication</strong>).</p><p>While plain encryption can be secure too, <strong>not using E2EE</strong> is the most common mistake that creates a weakness in the system, such systems often fall as a target of <strong>rainbow table attacks</strong>.</p><h3>How this system works in practice?</h3><ul><li>The user uploads a file to encrypt <em>(on the front-end);</em></li><li>The raw file contents are converted to the <strong>Base64</strong> format <em>(on the front-end);</em></li><li>A random password is generated <strong>(that is later used as the key for the AES encryption) </strong><em>(on the front-end);</em></li><li>The <strong>AES256-bit</strong> encryption algorithm is used to encrypt the <strong>Base64</strong> contents with the password that was generated in the previous step <em>(on the front-end);</em></li><li>The the <em>(universal)</em>public key of the <strong>RSA</strong> key pair is used to encrypt the <strong>PASSWORD that was used during the AES256 encryption step </strong><em>(that was generated </em><strong><em>randomly</em></strong><em>, on the front-end);</em></li><li>The result of the RSA encryption is converted to the <strong>Base64</strong> format to make sure special characters are not corrupted later during transmission <em>(this step done on the front-end);</em></li><li>Finally, the <strong>AES-ciphered file contents</strong> are saved as a .txt file (ciphered_file_contents.txt), and the <strong>RSA-protected password [that was used for the AES encryption in the previous steps]</strong> is saved in a .txt file on the user’s end, too (cipher_to_retrieve_aes_password.txt) <em>(on the front-end)</em>;</li></ul><p><strong><em>Then on the back-end side the process is as follows:</em></strong></p><ul><li>First, decode the Base64-encoded cipher_to_retrieve_aes_password.txt ; the <strong>output</strong> of this step is saved in the cipher_to_retrieve_aes_password_binary.txt file;</li><li>We do have the 2nd part of the RSA key-pair on the server side, and that is the <strong>RSA private key </strong>; use it to decrypt the cipher_to_retrieve_aes_password_binary.txt file’s contents; [this step utilizes the <strong>openssl</strong> library’s <strong><em>rsautl</em></strong> module]</li><li>The original password that we retrieved after decrypting the RSA cipher contents is then saved to the key_to_decrypt_aes.txt file;</li><li>Then we <em>Base64-decode</em> the ciphered_file_contents.txt file, and the binary data is saved to the ciphered_file_contents_base64_decoded.txt file;</li><li><strong>We’re almost there!</strong></li><li>Now run key_to_decrypt_aes.txt against the openssl <em>“AES-decrypt” command</em> <em>(</em><em>enc module)</em> to <strong>&quot;AES-decrypt”</strong> the ciphered_file_contents_base64_decoded.txt file; the result is saved as original_file_contents.txt;</li><li>This decryption command result is saved as a <em>Base64-encoded file</em>, so we need to do the last thing in our process: <strong>Base64-decode</strong> the <em>decrypted</em> output to get the original file contents;</li><li>You can now find the original file contents (binary or UTF-8 compatible, based on the file type that you have passed down to the system on the front-end originally) in original_file_contents_base64_decoded.txt;</li></ul><h3><em>Bravo!</em></h3><p>You can now find the full source code for the whole process and the system below:</p><pre>// src/components/FileInput/FileInput.tsx<br>import { FileInputProps } from &quot;./FileInput.types&quot;;<br>import { useRef, FC } from &quot;react&quot;;<br><br>const fileToBase64 = (file: File): Promise&lt;string&gt; =&gt; {<br>  return new Promise&lt;string&gt;((resolve, reject) =&gt; {<br>    const reader = new FileReader();<br>    reader.readAsDataURL(file);<br>    reader.onload = () =&gt; resolve(reader.result?.toString() || &quot;&quot;);<br>    reader.onerror = (error) =&gt; reject(error);<br>  });<br>};<br><br>const FileInput: FC&lt;FileInputProps&gt; = ({<br>  setUploadedFileName,<br>  setUploadedFileBase64,<br>}) =&gt; {<br>  const inputElement = useRef&lt;HTMLInputElement&gt;(null);<br>  return (<br>    &lt;section&gt;<br>      &lt;input<br>        ref={inputElement}<br>        onChange={async (e) =&gt; {<br>          if (!e.target?.files?.[0]) {<br>            return;<br>          }<br><br>          const _fileSizeInMb = (<br>            e.target.files[0].size /<br>            (1024 * 1024)<br>          ).toFixed(2);<br><br>          if (+_fileSizeInMb &gt; 10) {<br>            alert(&quot;File is larger than 10 MB&quot;);<br>            e.target.value = &quot;&quot;;<br>            if (!/safari/i.test(navigator.userAgent)) {<br>              e.target.type = &quot;&quot;;<br>              e.target.type = &quot;file&quot;;<br>            }<br>            return;<br>          }<br>          setUploadedFileName(e.target.files[0].name);<br>          setUploadedFileBase64(await fileToBase64(e.target.files[0]));<br>        }}<br>        type=&quot;file&quot;<br>      /&gt;<br>    &lt;/section&gt;<br>  );<br>};<br><br>export default FileInput;<br><br>// src/components/FileInput/FileInput.types.ts<br>export interface FileInputProps {<br>  setUploadedFileBase64: (value: string) =&gt; void;<br>};</pre><pre>// App.tsx<br>import CryptoJS from &#39;crypto-js&#39;;<br>import &#39;./app.css&#39;;<br>import FileInput from &quot;./components/FileInput/FileInput&quot;;<br>import { FC, useEffect, useState } from &quot;react&quot;;<br><br>const getAESEncrypted = (secret: string, password: string) =&gt; {<br>  const encrypted = CryptoJS.AES.encrypt(secret, password);<br><br>  return encrypted.toString();<br>}<br><br>const fromBase64 = (base64String : string) =&gt; Uint8Array.from(atob(base64String), c =&gt; c.charCodeAt(0));<br><br>const getPkciDer = (pkciPem : string) =&gt; {<br>  console.log(pkciPem);<br>  const pkciPemHeader = &quot;-----BEGIN PUBLIC KEY-----&quot;;<br>  const pkciPemFooter = &quot;-----END PUBLIC KEY-----&quot;;<br>  console.log(pkciPem);<br>  pkciPem = pkciPem.substring(pkciPemHeader.length, pkciPem.length - pkciPemFooter.length);<br>  console.log(pkciPem);<br>  return fromBase64(pkciPem);<br>}<br><br>const importPublicKey = async (pkciPem : string) =&gt; {<br>    return await window.crypto.subtle.importKey(<br>        &quot;spki&quot;,<br>        getPkciDer(pkciPem),<br>        {<br>            name: &quot;RSA-OAEP&quot;,<br>            hash: &quot;SHA-1&quot;,<br>        },<br>        true,<br>        [&quot;encrypt&quot;]<br>    );<br>}<br><br>const encryptRSA = async (key : CryptoKey, text : string) =&gt; {<br>    const enc = new TextEncoder();<br>    const encrypted = await window.crypto.subtle.encrypt(<br>        {<br>            name: &quot;RSA-OAEP&quot;<br>        },<br>        key,<br>        enc.encode(text)<br>    );<br>    return encrypted;<br>}<br>const ab2str = (buf : ArrayBuffer) =&gt; {<br>  //@ts-ignore<br>  return String.fromCharCode.apply(null, new Uint8Array(buf));<br>}<br>const getRSAEncrypted = async (text : string) =&gt; {<br>if (!process.env.REACT_APP_PUBLIC_RSA_KEY) {<br>  throw new Error(&#39;No public key provided in the .env&#39;);<br>}<br>  const key =<br>  await importPublicKey(process.env.REACT_APP_PUBLIC_RSA_KEY);<br>  const encrypted = await encryptRSA(key, text);<br>  download(createTextFile(window.btoa(ab2str(encrypted))), &#39;cipher_to_retrieve_aes_password.txt&#39;);<br>}<br><br>const dec2hex = (dec: number): string =&gt; {<br>  return dec.toString(16).padStart(2, &quot;0&quot;);<br>};<br><br>const generateId = (len?: number): string =&gt; {<br>  let arr = new Uint8Array((len || 32) / 2);<br>  window.crypto.getRandomValues(arr);<br>  return Array.from(arr, dec2hex).join(&quot;&quot;);<br>};<br><br>const download = (url: string, filename: string): void =&gt; {<br>  let elm = document.createElement(&quot;a&quot;);<br>  elm.href = url;<br>  elm.setAttribute(&quot;download&quot;, filename);<br>  elm.click();<br>  document.body.append(elm);<br>};<br><br>const encrypt = async (fileBase64: string): Promise&lt;string&gt; =&gt; {<br>  const key = generateId();<br><br>  await getRSAEncrypted(key);<br><br>  const aesEncryptedPayload = await getAESEncrypted(fileBase64, key);<br><br>  download(createTextFile(aesEncryptedPayload), &#39;ciphered_file_contents.txt&#39;);<br><br>  return aesEncryptedPayload;<br>};<br><br>const createTextFile = (text : string) : string =&gt; {<br>   const data = new Blob([text], {type: &#39;text/plain&#39;});<br>   const textFile = window.URL.createObjectURL(data);<br>   return textFile;<br> };<br><br>const App: FC = () =&gt; {<br>  const [uploadedFileName, setUploadedFileName] = useState&lt;string&gt;();<br>  const [uploadedFileBase64, setUploadedFileBase64] = useState&lt;string&gt;();<br>  useEffect(() =&gt; {<br>    if (!(uploadedFileBase64 &amp;&amp; uploadedFileName)) return;<br><br>    (async function () {<br>      await encrypt(uploadedFileBase64.split(&quot;,&quot;)[1]);<br>    })();<br>  }, [uploadedFileName, uploadedFileBase64]);<br>  return (<br>    &lt;main&gt;<br>      &lt;FileInput<br>        setUploadedFileName={setUploadedFileName}<br>        setUploadedFileBase64={setUploadedFileBase64}<br>      /&gt;<br>    &lt;/main&gt;<br>  );<br>};<br><br>export default App;</pre><pre>base64 --decode cipher_to_retrieve_aes_password.txt &gt; cipher_to_retrieve_aes_password_binary.txt<br>openssl rsautl -decrypt -oaep -inkey private_key.pem -in cipher_to_retrieve_aes_password_binary.txt -out key_to_decrypt_aes.txt<br><br>RANDOM_KEY=$(cat key_to_decrypt_aes.txt)<br><br>base64 --decode ciphered_file_contents.txt &gt; ciphered_file_contents_base64_decoded.txt<br><br>openssl enc -d -aes-256-cbc -in ciphered_file_contents_base64_decoded.txt -k ${RANDOM_KEY} -md MD5 -out original_file_contents.txt<br><br>base64 --decode original_file_contents.txt &gt; original_file_contents_base64_decoded.txt<br><br>read</pre><h4>Here it is!</h4><p><em>P.S. Constructive criticism and suggestions about optimization are always very welcome! 😉</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3292d934661f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[✔ Best practices for front-end dApp development: On-Chain dApp Game with Solidity, React…]]></title>
            <link>https://coinsbench.com/rock-paper-scissors-lizard-spock-game-with-solidity-react-typescript-wagmi-viem-commit-reveal-8d5a1f8c3230?source=rss-6f3d497ef646------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d5a1f8c3230</guid>
            <category><![CDATA[wagmi]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[viem]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Milaabl]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 07:37:53 GMT</pubDate>
            <atom:updated>2023-08-24T12:20:12.960Z</atom:updated>
            <content:encoded><![CDATA[<h3>✔ Best practices for front-end dApp development: On-Chain dApp Game with Solidity, React, Typescript &amp; Wagmi/Viem (“Commit/reveal” w/ keccak256, “Clone factory” patterns)</h3><h4>The dApp we’ll be building today is an on-chain rock paper scissors lizard spock game built with React, Typescript, Wagmi/Viem, Sepolia &amp; integrated with Solidity smart contracts (“Clone factory”, “commit/reveal” patterns). The game supports multiple (an unlimited № of…) playing rounds, each supporting input from roughly 2 players.</h4><h4>The 1st player can create a new game (bypassing deployContract thanks to the “Clone factory” pattern), submit his first move by signing the commitment &amp; hashing it w/ keccak256 encryption, and staking some ETH. Then invite the 2nd player — the opponent — who must submit his move within 5 minutes.</h4><h4>Then the game can be resolved by the 1st player, or automatically give refunds if the 1st player fails to resolve the game in 5 minutes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HMWx3yR6T8qMhMOR.png" /></figure><p><strong>You can find the code in my GitHub repo: </strong><a href="https://github.com/milaabl/rpsls-medium-tutorial"><strong>https://github.com/milaabl/rpsls-medium-tutorial</strong></a><strong>.</strong></p><p>We’ll utilize the best practices, follow the Solidity security patterns &amp; the reusable components approach to React and Typescript development.</p><p><strong>The final version of the dApp we’ll be building in this tutorial looks like this: </strong><a href="https://rpsls-medium-tutorial.vercel.app/"><strong>https://rpsls-medium-tutorial.vercel.app</strong></a></p><p>You can try it out yourself before going deeper in the implementation details, because it’ll help you with better understanding the user flows &amp; logic of the game.</p><p>I’ll also show you how to implement common Solidity patterns such as:</p><ul><li>commit-reveal;</li><li>contract clone factory;</li></ul><p>We’ll focus on security, and also adhere to modern Solidity security and follow security recommendations<strong><em> (think checks -&gt; effects -&gt; interactions </em></strong>pattern).</p><p>I’ll start off by scaffolding a new React &amp; Typescript project:</p><pre>yarn create react-app rpsls-game --template typescript</pre><p>Next we need to install the necessary NPM dependencies:</p><pre>cd rpsls-game<br>yarn add @mui/material @mui/styled-engine-sc styled-components @fontsource/red-hat-display viem wagmi react-router-dom react-timer-hook</pre><p>Now let’s build a contract that we’ll be using as a jury:</p><pre>// SPDX-License-Identifier: Unlicensed<br><br>pragma solidity ^0.8.12;<br><br>contract RPSLS {<br>    enum Move {<br>        Null, Rock, Paper, Scissors, Lizard, Spock<br>    }<br>    address public player1;<br>    address public player2;<br><br>    bytes32 move1Hash;<br><br>    Move public move1;<br>    Move public move2;<br><br>    uint256 public stake;<br><br>    uint256 public TIMEOUT_IN_MS = 5 minutes;<br>    uint256 public lastTimePlayed;<br><br>    modifier onlyOwner() {<br>        require(msg.sender == player1);<br>        _;<br>    }<br><br>    event Player2Played(address indexed _player2, Move indexed _move2);<br>    event GameSolved(address indexed winner);<br>    event GameTied();<br>    event GameTimedOut(address indexed fallbackWinner);<br><br>    constructor(bytes32 _move1Hash, address _player1, address _player2) payable {<br>        stake = msg.value;<br>        move1Hash = _move1Hash;<br>        player1 = _player1;<br>        player2 = _player2;<br>        lastTimePlayed = block.timestamp;<br>    }<br><br>    function play (Move _move2) external payable {<br>        require(msg.value == stake, &quot;Insufficient funds for move. Make sure you stake the required amount of ETH for the transaction to succeed.&quot;);<br>        require(msg.sender == player2);<br>        require(move2 == Move.Null, &quot;Move already played&quot;);<br><br>        move2 = _move2;<br>        lastTimePlayed = block.timestamp;<br><br>        emit Player2Played(player2, _move2);<br>    }<br><br>    function solve(Move _move1, string calldata _salt) onlyOwner external {<br>        require(player2 != address(0), &quot;Player 2 should make his move in order to solve the round.&quot;);<br>        require(move2 != Move.Null, &quot;Player 2 should move first.&quot;);<br>        require(keccak256(abi.encodePacked(_move1, _salt)) == move1Hash, &quot;The exposed value is not the hashed one!&quot;);<br>        require(stake &gt; 0, &quot;Winner is already determined.&quot;);<br><br>        move1 = _move1;<br><br>        uint256 _stake = stake;<br><br>        if (win(move1, move2)) {<br>            stake = 0;<br>            (bool _success) = payable(player1).send(2 * _stake);<br>            if (!_success) {<br>                stake = _stake;<br>            }<br>            else {<br>                emit GameSolved(player1);<br>            }<br>        }<br>        else if (win(move1, move2)) {<br>            stake = 0;<br>            (bool _success) = payable(player2).send(2 * _stake);<br>            if (!_success) {<br>                stake = _stake;<br>            }<br>            else {<br>                emit GameSolved(player2);<br>            }<br>        }<br>        else {<br>            stake = 0;<br>            (bool _success1) = payable(player2).send(_stake);<br>            (bool _success2) = payable(player1).send(_stake);<br>            if (!(_success1 || _success2)) {<br>                stake = _stake;<br>            }<br>            else {<br>                emit GameTied();<br>            }<br>        }<br>    }<br><br>    function win(Move _move1, Move _move2) public pure returns (bool) {<br>        if (_move1 == _move2)<br>            return false; // They played the same so no winner.<br>        else if (_move1 == Move.Null)<br>            return false; // They did not play.<br>        else if (uint(_move1) % 2 == uint(_move2) % 2) <br>            return (_move1 &lt; _move2);<br>        else<br>            return (_move1 &gt; _move2);<br>    }<br><br>    function claimTimeout() external {<br>        require(msg.sender == player1 || msg.sender == player2, &quot;You&#39;re not a player of this game.&quot;);<br><br>        require(block.timestamp &gt; lastTimePlayed + TIMEOUT_IN_MS, &quot;Time has not run out yet.&quot;);<br><br>        uint256 _stake = stake;<br>        stake = 0;<br><br>        if (player2 == address(0)) {<br>            (bool _success) = payable(player1).send(_stake);<br>            if (!_success) {<br>                stake = _stake;<br>            }<br>            else {<br>                emit GameTimedOut(player1);<br>            }<br>        }<br>        else if (move2 != Move.Null) {<br>         (bool _success) = payable(player2).send(_stake * 2);<br>            if (!_success) {<br>                stake = _stake;<br>            }<br>            else {<br>                emit GameTimedOut(player2);<br>            }   <br>        }<br>    }<br>}</pre><p>To make sure the game cannot be cheated by a front-running attack or block explorer attack, I’m using the commit-reveal startegy pattern.</p><p>The first player’s move will remain hashed until the second player makes his move &amp; the player 1 solves the game by revealing his move. There’s a good <a href="https://www.oreilly.com/library/view/mastering-blockchain-programming/9781839218262/3cca669b-430c-4cc7-9019-4562ecad87b5.xhtml">article</a> about that pattern from the O’Reilly Team. The algoritgm uses the <strong>keccak256 </strong>hasher implementation.</p><p>Now take a look at our contract’s code.</p><h3>Did you notice what’s missing?</h3><p>Currently the main game contract can only be deployed with a method like <em>viem’s</em> publicClient.deployContract().</p><p>However, the address of the deployed contract will not be stored anywhere, and the only way the user can retrieve the deployed contract’s address after further leaving the page is by exloring the transactions tab of his Metamask wallet.</p><p>It’s definitely not user-friendly.</p><p>Let’s write an additional contract that will act as a factory producing &amp; storing new game session contracts, each attached to the players’ addresses.</p><pre>// SPDX-License-Identifier: Unlicensed<br><br>pragma solidity ^0.8.12;<br>import &quot;./RPSLS.sol&quot;<br><br>contract RPSLSFactory {<br>    RPSLS[] private gameSessions;<br>    mapping (address =&gt; RPSLS[]) private userGameSessions;<br><br>    event NewGameSession(address indexed gameSession);<br>    function createGameSession(<br>        bytes32 _move1Hash,<br>        address _player2<br>    ) external payable {<br>        RPSLS gameSession = (new RPSLS){value: msg.value}(<br>            _move1Hash,<br>            msg.sender,<br>            _player2<br>        );<br>        gameSessions.push(gameSession);<br>        userGameSessions[msg.sender].push(gameSession);<br>        userGameSessions[_player2].push(gameSession);<br><br>        emit NewGameSession(address(gameSession));<br>    }<br>    function getGameSessions()<br>        external<br>        view<br>        returns (RPSLS[] memory _gameSessions)<br>    {<br>        return userGameSessions[msg.sender];<br>    }<br>}</pre><p>✅ I’ll be using the Sepolia 🐬testnet for the further development &amp; contract deployment.</p><h3>👉 OK, now when we have implemented the necessary Solidity code, we can continue with our React app.</h3><p>❗Make sure you save the deployed address of the RPSLSFactory.sol contract &amp; add it to your .env file.</p><pre>// .env<br><br>REACT_APP_PUBLIC_RPSLS_FACTORY_ADDRESS=&lt;your factory&#39;s deployed address&gt;<br>REACT_APP_PUBLIC_ALCHEMY_API_KEY=&lt;your alchemy provider&#39;s api key&gt;<br></pre><pre>import React from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import { WagmiConfig, configureChains, createConfig } from &#39;wagmi&#39;<br>import { sepolia } from &#39;wagmi/chains&#39;<br>import { publicProvider } from &#39;wagmi/providers/public&#39;<br>import { InjectedConnector } from &#39;wagmi/connectors/injected&#39;<br> <br>const { chains, publicClient } = configureChains(<br>  [sepolia],<br>  [publicProvider()]<br>)<br><br>const connector = new InjectedConnector({<br>  chains,<br>})<br><br>const config = createConfig({<br>  publicClient,<br>  connectors: [connector],<br>  autoConnect: true,<br>});<br><br>function App() {<br>  return (<br>    &lt;WagmiConfig config={config}&gt;<br><br>    &lt;/WagmiConfig&gt;<br>  );<br>}</pre><p>The basic config for your App.tsx file should look like this 👆.</p><p>I figured out that using the publicProvider with a testnet might sometimes be a <a href="https://github.com/wagmi-dev/viem/issues/923"><strong>culprit</strong></a> when fetching pending transaction details, so I switched to using the alchemyProvider &amp; separated the wagmi config to a new file:</p><pre>// wagmi.ts ~ App.tsx<br><br>import { configureChains, createConfig } from &#39;wagmi&#39;<br>import { sepolia } from &#39;wagmi/chains&#39;<br>import { alchemyProvider } from &#39;wagmi/providers/alchemy&#39;<br>import { MetaMaskConnector } from &#39;wagmi/connectors/metaMask&#39;<br> <br>const { chains, publicClient, webSocketPublicClient } = configureChains(<br>  [sepolia],<br>  [alchemyProvider({<br>    apiKey: process.env.REACT_APP_PUBLIC_ALCHEMY_API_KEY<br>  })]<br>)<br><br>const connector = new MetaMaskConnector({<br>  chains,<br>})<br><br>export const wagmiConfig = createConfig({<br>  publicClient,<br>  webSocketPublicClient,<br>  connectors: [connector]<br>});</pre><p>👉 Let’s create a contracts.ts file in the src/ directory. It’ll be used to store the address of the factory contract, as well as its ABI — so that we connect the contract the <em>reusable way,</em> so we don’t reference the process.env.REACT_APP_PUBLIC_RPSLS_FACTORY_ADDRESS variable each time.</p><h3>💪 There’s a powerful feature that Wagmi/Viem provides: ABI type inference. Contrary to when building dApps with web3.js or ethers.js (you can use ABIType alongside these though!), Viem provides automatic type interference. Learn more: <a href="https://viem.sh/docs/typescript.html#contract-abis">https://viem.sh/docs/typescript.html#contract-abis</a></h3><pre>// contracts.ts<br><br>// https://wagmi.sh/core/typescript — Const assertion is required for Typescript to process ABI safely<br>// Note: JSON ABIs don&#39;t work with const assertion &amp; thus are not supported by the type-safe Wagmi hooks (https://github.com/wagmi-dev/wagmi/discussions/1084)<br><br>export const contracts = {<br>  factory: {<br>    address: process.env.REACT_APP_PUBLIC_RPSLS_FACTORY_ADDRESS,<br>    abi: [<br>      ...factoryContractAbi<br>    ] as const // replace with the ABI from the compiler&#39;s output<br>  },<br>  rpslsGame: {<br>    abi: [...rpslsContractAbi] as const // replace with the ABI from the compiler&#39;s output<br>  },<br>};</pre><p><strong>Note: To avoid arbitrary type casting (aka </strong><strong>as T), make sure you declare your Environment variables types in vite-env.d.ts or react-app-env.d.ts. My react-app-env.d.ts looks like this:</strong></p><pre>// react-app-env.d.ts<br><br>/// &lt;reference types=&quot;react-scripts&quot; /&gt;<br><br>declare namespace NodeJS {<br>  interface ProcessEnv {<br>    REACT_APP_PUBLIC_RPSLS_FACTORY_ADDRESS: `0x${string}`;<br>    REACT_APP_PUBLIC_ALCHEMY_API_KEY: string;<br>  }<br>}</pre><p>💎 I’m using @mui/material &amp; styled-components for my project, you can use any components library you wish. For the purposes of this tutorial, I’ll mainly omit the stylization code so that it doesn’t mess with the Web3 integration part. Remember that you can see the code of the project here on my GitHub: <a href="https://github.com/milaabl/rpsls-medium-tutorial">https://github.com/milaabl/rpsls-medium-tutorial</a>.</p><p><strong>We’ll need the </strong><strong>useAccount, </strong><strong>useSwitchNetwork, </strong><strong>useConnect, </strong><strong>useNetwork, </strong><strong>useDisconnect, </strong><strong>useContractWrite, </strong><strong>useContractRead, </strong><strong>useContractReads&amp; </strong><strong>useWaitForTransaction hooks provided by the Wagmi package.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyalW3x4MwrMrGjXb4bmsQ.png" /><figcaption>@mui/material, styled-components, React, Typescript basic layout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnT0c9TwiFyKt2hWGGq4Og.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEZFm_be3aNf04Z5zESpGg.png" /><figcaption>Network switch component &amp; indicator</figcaption></figure><ol><li>Let’s first build the wallet connection functionality &amp; UI like the above 👆👆👆. The header will have:</li></ol><ul><li>a connect button</li><li>a loading indicator</li><li>a connected account label.</li></ul><p>The best practice is to also have a &lt;SwitchNetwork /&gt; component that will offer the user the ability to switch his current network to one of the dApp’s supported networks.</p><p><em>The </em><em>Header.tsx component:</em></p><pre>// Header.tsx<br><br>import React from &quot;react&quot;;<br>import { useAccount, useConnect, useDisconnect } from &quot;wagmi&quot;;<br>import CancelIcon from &#39;@mui/icons-material/Cancel&#39;;<br>import * as S from &quot;./Header.styles&quot;;<br>import logoIcon from &#39;assets/icons/logo.svg&#39;;<br>import AccountCircleIcon from &#39;@mui/icons-material/AccountCircle&#39;;<br>import SwitchNetwork from &#39;./SwitchNetwork&#39;;<br>import { IconButton } from &quot;@mui/material&quot;;<br><br>function Header () {<br>    const { isLoading : isConnectingWallet, connectors, connect } = useConnect();<br>    const { address } = useAccount();<br>    const { disconnect } = useDisconnect();<br>    return &lt;&gt;<br>        &lt;S.Header&gt;<br>            &lt;S.Logo alt=&quot;Logo&quot; src={logoIcon} /&gt;<br>            { !address ? &lt;S.Button loading={isConnectingWallet} onClick={() =&gt; connect({<br>                connector: connectors[0]<br>            })} startIcon={&lt;AccountCircleIcon /&gt;}&gt;Connect wallet&lt;/S.Button&gt; : &lt;S.AccountAddress&gt;<br>                &lt;IconButton size=&quot;small&quot; onClick={() =&gt; disconnect()}&gt;<br>                    &lt;CancelIcon color=&quot;error&quot; fontSize=&quot;inherit&quot; /&gt;<br>                &lt;/IconButton&gt;<br>                &lt;span&gt;{address}&lt;/span&gt;&lt;/S.AccountAddress&gt; }<br>        &lt;/S.Header&gt;<br>        &lt;SwitchNetwork /&gt;<br>    &lt;/&gt;<br>};<br><br>export default Header;</pre><p><em>The </em><em>SwitchNetwork.tsx component:</em></p><pre>// SwitchNetwork.tsx<br><br>import React from &quot;react&quot;;<br>import { useSwitchNetwork, useNetwork, Chain } from &quot;wagmi&quot;;<br>import * as S from &#39;./SwitchNetwork.styles&#39;;<br><br>function SwitchNetwork () {<br>    const { switchNetwork, chains } = useSwitchNetwork();<br>    const { chain } = useNetwork();<br>    return &lt;S.Container&gt;<br>        {chains &amp;&amp; switchNetwork &amp;&amp; !chains.find((supportedChain : Chain) =&gt; supportedChain.id === chain?.id) ? &lt;S.SwitchButton onClick={<br>            () =&gt; switchNetwork(chains[0]?.id)<br>        }&gt;Switch to {chains[0]?.name}&lt;/S.SwitchButton&gt; : &lt;&gt;&lt;/&gt;}<br>    &lt;/S.Container&gt;<br>}<br><br>export default SwitchNetwork;</pre><p>2. OK. The user can now connect his Metamask wallet, disconnect it if he wants, switch the network of his Metamask account if the network he’s using is not on the dApp’s supported networks list.</p><p><strong>Let’s now start the work on our front-end </strong><strong>RPSLSFactory.sol integration by building the components for the </strong><strong>new-game page.</strong> The user will be able to set a game’s bid, select his first move, hash it &amp; create a new instance of game by inviting the 2nd player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YH-jhZZ_-xGs9CHVqJQKQ.png" /><figcaption>Create a new rock paper scissars lizard spock game session page 🎮</figcaption></figure><p>The request to write a contract looks like the following in Wagmi:</p><pre>const {<br>    error,<br>    isLoading: isNewGameSessionLoading,<br>    write: createNewGameSession,<br>    data: createNewGameSessionData,<br>  } = useContractWrite({<br>    ...contracts.factory,<br>    functionName: &quot;createGameSession&quot;,<br>    value: parseEther(bid),<br>  });</pre><p>Note that I’m not passing the “args” param in the useContractWrite hook because I’ll pass it later when making a call. As the move hash is generated asynchronously, I found that it’s a more convenient way.</p><blockquote><strong><em>👋 It’s a good practice to let the user paste the opponent’s address clicking on the button.</em></strong></blockquote><p>Let’s also add the move icons so the user can select his move by clicking on the icon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*ZvrI6c3dJn4pf9_xj8Ht1Q.png" /><figcaption>Decentralized rock paper scissors lizard spock game in React, Typescript, Web3</figcaption></figure><p>🔐🔐🔐 Now I’ll show you how to securely encrypt the user’s move. As our Solidity contract is using the keccak256 function, we’ll be using an equivalent function provided by viem.</p><blockquote><strong><em>🦉 I used to reference the ethers’ </em></strong><strong><em>solidityKeccak256 function, but I later found out that viem has its own alternative. Let’s find out how to generate a secret key &amp; hash it.</em></strong></blockquote><p>That’s basically the main commitment encryption code we’ll need in order to call the factory contract’s function:</p><pre>const salt = crypto.randomUUID();<br><br>const _move1Hash = keccak256(<br>  encodePacked([&quot;uint8&quot;, &quot;string&quot;], [selectedMove, salt]),<br>);<br><br>_salt.current = salt;<br><br>createNewGameSession({<br>  args: [_move1Hash, player2],<br>});</pre><p>Here I’m using the <strong>Browser Subtle Crypto API</strong> &amp; the keccak256 from the viem library.</p><p>But first let’s make sure that the user signs our actions &amp; verifies his commitment. We’ll need to use the useSignMessage hook to verify that the user is OK with using a randomly generated salt to initiate a new game.</p><pre>const { signMessage, data: signData } = useSignMessage();<br><br>...<br><br>signMessage({ message: `Your game move is: ${selectedMove}. Your game salt is: ${_salt.current}. Keep it private! It&#39;ll automatically be stored in your local storage.` });</pre><p>The final code of the “Create new game” page looks like this:</p><pre>// pages/create-game/index.tsx<br><br>import { ChangeEvent, useContext, useEffect, useRef, useState } from &#39;react&#39;;<br><br>import { isAddress } from &#39;viem&#39;;<br>import { Address, Hash, encodePacked, keccak256, parseEther } from &#39;viem&#39;;<br>import { useAccount, useContractWrite, useSignMessage } from &#39;wagmi&#39;;<br><br>import TransactionHistory from &#39;../../components/TransactionHistory/TransactionHistory&#39;;<br>import { AppContext } from &#39;../../context/AppContext&#39;;<br>import { contracts } from &#39;../../contracts&#39;;<br>import { useLocalStorage } from &#39;../../hooks/useLocalStorage&#39;;<br>import { Move, moveIcons, moves } from &#39;../../moves&#39;;<br>import { validateAddress } from &#39;../../utils/validators&#39;;<br>import * as S from &#39;./styles&#39;;<br><br>function NewGamePage() {<br>  const { address } = useAccount();<br><br>  const [player2, setPlayer2] = useState&lt;Address | undefined&gt;();<br>  const [bid, setBid] = useState&lt;string&gt;(&#39;0&#39;);<br><br>  const [, setSalt] = useLocalStorage(&#39;salt&#39;);<br>  const [, setMove1] = useLocalStorage(&#39;move&#39;);<br><br>  const [selectedMove, setSelectedMove] = useState&lt;Move&gt;(Move.Null);<br><br>  const [isMoveCommitted, setIsMoveCommitted] = useState&lt;boolean&gt;(false);<br><br>  const {<br>    error,<br>    isLoading: isNewGameSessionLoading,<br>    write: createNewGameSession,<br>    data: createNewGameSessionData,<br>  } = useContractWrite({<br>    ...contracts.factory,<br>    functionName: &#39;createGameSession&#39;,<br>    value: parseEther(bid),<br>  });<br><br>  // eslint-disable-next-line @typescript-eslint/naming-convention<br>  const _salt = useRef&lt;string | undefined&gt;();<br><br>  // eslint-disable-next-line @typescript-eslint/naming-convention<br>  const _move1Hash = useRef&lt;Hash | undefined&gt;();<br><br>  const { signMessage, data: signData } = useSignMessage();<br><br>  useEffect(() =&gt; {<br>    if (createNewGameSessionData?.hash &amp;&amp; !error) {<br>      setIsMoveCommitted(true);<br>    }<br>  }, [createNewGameSessionData?.hash]);<br><br>  const [gameSessionHash, setGameSessionHash] = useState&lt;Hash&gt;();<br><br>  useEffect(() =&gt; {<br>    if (!createNewGameSessionData &amp;&amp; signData &amp;&amp; _move1Hash.current &amp;&amp; player2)<br>      createNewGameSession({<br>        args: [_move1Hash.current, player2],<br>      });<br>  }, [signData]);<br><br>  useEffect(() =&gt; {<br>    if (gameSessionHash &amp;&amp; _salt.current) {<br>      setSalt(_salt.current, `salt-${gameSessionHash}`);<br>      setMove1(String(selectedMove), `move-${gameSessionHash}`);<br>    }<br>  }, [gameSessionHash]);<br><br>  const { setErrorMessage, setIsLoading } = useContext(AppContext);<br><br>  useEffect(() =&gt; {<br>    if (error?.message) setErrorMessage?.(error.message);<br>  }, [error?.message]);<br><br>  useEffect(() =&gt; {<br>    setIsLoading?.(isNewGameSessionLoading);<br>  }, [isNewGameSessionLoading]);<br><br>  return !isMoveCommitted ? (<br>    &lt;S.Container&gt;<br>      &lt;S.MovesContainer&gt;<br>        {moves.map((move: Move) =&gt; (<br>          &lt;S.MoveItem<br>            className={selectedMove === move ? &#39;selected&#39; : &#39;&#39;}<br>            onClick={() =&gt; setSelectedMove(move)}<br>          &gt;<br>            &lt;img src={moveIcons[move - 1]} alt={`Move №${move}`} /&gt;<br>          &lt;/S.MoveItem&gt;<br>        ))}<br>      &lt;/S.MovesContainer&gt;<br>      &lt;S.Heading&gt;Create a new game session 🎮&lt;/S.Heading&gt;<br>      &lt;S.Form&gt;<br>        &lt;S.Input&gt;<br>          &lt;S.TextField<br>            inputProps={{<br>              maxLength: 42,<br>            }}<br>            InputLabelProps={{ shrink: true }}<br>            label=&quot;Address of player2&#39;s wallet&quot;<br>            helperText=&quot;Invite your opponent 🪖&quot;<br>            value={player2}<br>            onChange={({ target: { value } }: ChangeEvent&lt;HTMLInputElement&gt;) =&gt;<br>              isAddress(value) &amp;&amp; setPlayer2(value)<br>            }<br>          /&gt;<br>          &lt;S.PasteWalletAddressButton<br>            label=&quot;Paste&quot;<br>            onClick={() =&gt; {<br>              navigator.clipboard<br>                .readText()<br>                .then((value) =&gt; isAddress(value) &amp;&amp; setPlayer2(value));<br>            }}<br>          /&gt;<br>        &lt;/S.Input&gt;<br>        &lt;S.Input&gt;<br>          &lt;S.TextField<br>            inputProps={{<br>              step: &#39;0.01&#39;,<br>            }}<br>            type=&quot;number&quot;<br>            label=&quot;Bid (in ETH)&quot;<br>            helperText=&quot;Please enter the bid 🎲 for the game&quot;<br>            value={bid}<br>            onChange={({ target: { value } }: ChangeEvent&lt;HTMLInputElement&gt;) =&gt;<br>              setBid(value)<br>            }<br>          /&gt;<br>        &lt;/S.Input&gt;<br>      &lt;/S.Form&gt;<br>      &lt;S.SubmitButton<br>        disabled={<br>          !(<br>            address &amp;&amp;<br>            selectedMove !== Move.Null &amp;&amp;<br>            Number(bid) &gt; 0 &amp;&amp;<br>            validateAddress(player2)<br>          )<br>        }<br>        onClick={() =&gt; {<br>          const salt = crypto.randomUUID();<br><br>          _move1Hash.current = keccak256(<br>            encodePacked([&#39;uint8&#39;, &#39;string&#39;], [selectedMove, salt]),<br>          );<br><br>          _salt.current = salt;<br><br>          signMessage({<br>            message: `Your game move is: ${selectedMove}. Your game salt is: ${_salt.current}. Keep it private! It&#39;ll automatically be stored in your local storage.`,<br>          });<br>        }}<br>      &gt;<br>        Submit session ✅<br>      &lt;/S.SubmitButton&gt;<br>    &lt;/S.Container&gt;<br>  ) : createNewGameSessionData?.hash ? (<br>    &lt;TransactionHistory<br>      setGameSessionHash={setGameSessionHash}<br>      transactionHash={createNewGameSessionData?.hash}<br>    /&gt;<br>  ) : (<br>    &lt;&gt;&lt;/&gt;<br>  );<br>}<br><br>export default NewGamePage;</pre><p>⚠️ <strong>We are storing the salt &amp; player’s move in the localStorage.</strong> Currently the auth stuff is a bit complicated in the Web3, but the use of localStorage in case of our game helps us further solve the game by revealing the first player’s commitment, so that he doesn’t need to store it himself.</p><p><strong>Optionally, you can incorporate Metamask’s recent feature that allows storing passwords in the local self-custodial wallet the safe way: </strong><a href="https://github.com/ritave/snap-passwordManager"><strong>https://github.com/ritave/snap-passwordManager</strong></a><strong>.</strong></p><p>I thought of implementing it in this tutorial application, but not every user has the development version of the Metamask extension installed, so I might leave it for the next article. 😉</p><p>You can checkout the Metamask’s Snap edition: <a href="https://metamask.io/news/developers/invisible-keys-snap-multi-cloud-private-key-storage/">https://metamask.io/news/developers/invisible-keys-snap-multi-cloud-private-key-storage</a>.</p><blockquote><strong><em>❗Notice that as the dApp alllows multiple game session at a time, we have to store the salt &amp; move values attached to more specific keys like “salt” -&gt; “salt-0x3800429c6cFB510602eb9545D133b046B9d19535”, “move” -&gt; “move-0x3800429c6cFB510602eb9545D133b046B9d19535”. Otherwise, it’d be hard to figure out which salt &amp; move are related to a particular game session.</em></strong></blockquote><p><strong>Note that: To convert an Epoch timestamp to a valid ms date that the </strong><strong>react-timer-hook will be able to parse sufficiently, we need to multiply it by 1000. It’s important to keep such nuances in mind when developing dApps, because some Solidity types are not like the ones in Javascript. Take that Epoch timestamp issue as an example.</strong></p><pre>const { seconds, minutes, restart } = useTimer({<br>    expiryTimestamp: new Date(<br>      (Number(lastTimePlayed || 0) + Number(TIMEOUT_IN_MS || 0)) * 1000, // Convert Epoch timestamp to ms (https://dev.to/iamephraim/how-to-convert-epoch-timestamp-to-date-using-javascript-352f)<br>    ),<br>    autoStart: true,<br>    onExpire: () =&gt; setIsEligibleForTimeout(true),<br>  });</pre><p>💁‍♀️ I also created a context with the React Context API in order to have the loading spinner functionality in the app, <em>for better UX.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tYkSoz9pRTMajz8cMvZRg.png" /><figcaption>Wagmi useContractWrite, useWaitForTransaction, usePrepareContractWrite loader</figcaption></figure><p>Let’s also add a <strong>&lt;TransactionHistory /&gt;</strong> component.</p><p>It’ll wait for the transaction to complete &amp; show the details.</p><pre>// components/TransactionHistory/TransactionHistory.tsx<br><br>import React, { Dispatch, useContext, useEffect, useState } from &#39;react&#39;;<br>import { useNavigate } from &#39;react-router-dom&#39;;<br><br>import { useTheme } from &#39;@mui/material&#39;;<br>import successTickIcon from &#39;assets/icons/success-tick.svg&#39;;<br>import { AppContext } from &#39;context/AppContext&#39;;<br>import { Hash, decodeAbiParameters } from &#39;viem&#39;;<br>import { Address, useWaitForTransaction } from &#39;wagmi&#39;;<br><br>import * as S from &#39;./TransactionHistory.styles&#39;;<br><br>interface TransactionHistoryProps {<br>  transactionHash: Hash;<br>  setGameSessionHash: Dispatch&lt;Hash&gt;;<br>}<br><br>function TransactionHistory({<br>  setGameSessionHash: _setGameSessionHash,<br>  transactionHash: _transactionHash,<br>}: TransactionHistoryProps) {<br>  const theme = useTheme();<br><br>  const [transactionHash, setTransactionHash] =<br>    useState&lt;Hash&gt;(_transactionHash);<br><br>  const { setIsLoading, setErrorMessage } = useContext(AppContext);<br><br>  const {<br>    error,<br>    data: transactionData,<br>    isLoading: isTransactionDataLoading,<br>  } = useWaitForTransaction({<br>    hash: transactionHash,<br>    enabled: !!transactionHash,<br>    onReplaced: (replacement) =&gt; {<br>      if (replacement.reason === &#39;cancelled&#39;) {<br>        setErrorMessage?.(`Transaction ${transactionHash} was cancelled`);<br>        return;<br>      } else {<br>        setTransactionHash(replacement.transactionReceipt.transactionHash);<br>      }<br>    },<br>    onError: (err) =&gt; setErrorMessage?.(err.message),<br>    confirmations: 1,<br>  });<br><br>  // eslint-disable-next-line @typescript-eslint/naming-convention<br>  const [gameSessionHash, setGameSessionHash] = useState&lt;Hash&gt;();<br><br>  useEffect(() =&gt; {<br>    if (!transactionData?.logs[0]?.data) return;<br><br>    // eslint-disable-next-line @typescript-eslint/naming-convention<br>    const _gameSessionHash = String(<br>      decodeAbiParameters(<br>        [<br>          {<br>            type: &#39;address&#39;,<br>            name: &#39;gameSession&#39;,<br>          },<br>        ],<br>        transactionData.logs[0].topics[1] as Address,<br>      ),<br>    ) as Hash;<br><br>    setGameSessionHash(_gameSessionHash);<br><br>    _setGameSessionHash(_gameSessionHash);<br>  }, [transactionData]);<br><br>  const navigate = useNavigate();<br><br>  useEffect(() =&gt; {<br>    setIsLoading?.(isTransactionDataLoading);<br>  }, [isTransactionDataLoading]);<br><br>  return isTransactionDataLoading ? (<br>    &lt;&gt;<br>      &lt;S.Container&gt;<br>        &lt;S.Details&gt;<br>          &lt;S.Heading&gt;Transaction pending&lt;/S.Heading&gt;<br>          &lt;S.DetailsItem&gt;<br>            &lt;strong&gt;Transaction address: &lt;/strong&gt;<br>            {transactionHash}<br>          &lt;/S.DetailsItem&gt;<br>          &lt;S.DetailsItem&gt;<br>            &lt;strong&gt;Status: &lt;/strong&gt;<br>            Pending<br>          &lt;/S.DetailsItem&gt;<br>          &lt;S.LoadingIconComponent variant=&quot;indeterminate&quot; /&gt;<br>        &lt;/S.Details&gt;<br>        &lt;S.CutOffBorder /&gt;<br>      &lt;/S.Container&gt;<br>    &lt;/&gt;<br>  ) : transactionData?.status === &#39;success&#39; &amp;&amp; !error ? (<br>    &lt;&gt;<br>      &lt;S.Container&gt;<br>        &lt;S.Details&gt;<br>          &lt;S.SuccessIndicator<br>            height={theme.spacing(4)}<br>            src={successTickIcon}<br>            alt=&quot;Success&quot;<br>          /&gt;<br>          &lt;S.Heading&gt;Transaction details&lt;/S.Heading&gt;<br>          &lt;S.DetailsItem&gt;<br>            &lt;strong&gt;Transaction address: &lt;/strong&gt;<br>            {transactionData?.transactionHash}<br>          &lt;/S.DetailsItem&gt;<br>          &lt;S.DetailsItem&gt;<br>            &lt;strong&gt;Gas used: &lt;/strong&gt;<br>            {String(transactionData.gasUsed)}<br>          &lt;/S.DetailsItem&gt;<br>          &lt;S.DetailsItem&gt;<br>            &lt;strong&gt;Gas price: &lt;/strong&gt;<br>            {String(transactionData.effectiveGasPrice)} WEI<br>          &lt;/S.DetailsItem&gt;<br>          {gameSessionHash ? (<br>            &lt;S.DetailsItem&gt;<br>              &lt;strong&gt;Game session hash: &lt;/strong&gt;<br>              {gameSessionHash}<br>            &lt;/S.DetailsItem&gt;<br>          ) : (<br>            &lt;&gt;&lt;/&gt;<br>          )}<br>          &lt;S.DetailsItem&gt;<br>            &lt;strong&gt;Status: &lt;/strong&gt;<br>            {transactionData.status.charAt(0).toUpperCase()}<br>            {transactionData.status.slice(1)}<br>          &lt;/S.DetailsItem&gt;<br>        &lt;/S.Details&gt;<br>        &lt;S.CutOffBorder /&gt;<br>      &lt;/S.Container&gt;<br>      {gameSessionHash ? (<br>        &lt;S.GameButtonsContainer&gt;<br>          &lt;S.InviteOpponentButton<br>            onClick={() =&gt; {<br>              navigator.clipboard.writeText(<br>                `${window.location.hostname}/game-session/${gameSessionHash}`,<br>              );<br>            }}<br>          &gt;<br>            Copy opponent&#39;s invitation link<br>          &lt;/S.InviteOpponentButton&gt;<br>          &lt;S.GoToSolveGameButton<br>            onClick={() =&gt; navigate(`/game-session/${gameSessionHash}`)}<br>          &gt;<br>            Go to game session<br>          &lt;/S.GoToSolveGameButton&gt;<br>        &lt;/S.GameButtonsContainer&gt;<br>      ) : (<br>        &lt;&gt;&lt;/&gt;<br>      )}<br>    &lt;/&gt;<br>  ) : (<br>    &lt;&gt;&lt;/&gt;<br>  );<br>}<br><br>export default TransactionHistory;</pre><pre>onReplaced: (replacement) =&gt; {<br>  if (replacement.reason === &#39;cancelled&#39;) {<br>    setErrorMessage?.(`Transaction ${transactionHash} was cancelled`);<br>    return;<br>  } else {<br>    setTransactionHash(replacement.transactionReceipt.transactionHash);<br>  }<br>},</pre><p><strong>👆 These particular lines allow us to seamlessly replace the transaction hash &amp; continue fetching the data if the transaction gets replaced with a higher fee to speed up.</strong></p><p><strong><em>Bonus</em></strong>! Some utils🧹 worth mentioning:</p><pre>// hooks/useLocalStorage.ts<br><br>import React, { useEffect, useSyncExternalStore } from &quot;react&quot;;<br><br>export const useLocalStorage = (<br>  key: string,<br>): [string | null, (value: string, key?: string) =&gt; void] =&gt; {<br>  const subscribe = (listener: () =&gt; void) =&gt; {<br>    window.addEventListener(&quot;storage&quot;, listener);<br>    return () =&gt; {<br>      window.removeEventListener(&quot;storage&quot;, listener);<br>    };<br>  };<br><br>  const getSnapShot = (): string | null =&gt; {<br>    return localStorage.getItem(key);<br>  };<br><br>  const value = useSyncExternalStore(subscribe, getSnapShot);<br><br>  const setValue = (newValue: string, _key?: string) =&gt; {<br>    localStorage.setItem(_key || key, newValue);<br>  };<br><br>  useEffect(() =&gt; {<br>    if (value) {<br>      setValue(value, key);<br>    }<br>  }, [key]);<br><br>  return [value, setValue];<br>};</pre><pre>// utils/validators.ts<br><br>import { isAddress } from &quot;viem&quot;;<br><br>export const validateAddress = (address : string | undefined) =&gt; address &amp;&amp; isAddress(address);</pre><p><strong>There’re a lot of libraries that provide the </strong><strong>useLocalStorage hook, but they don’t have support for updating the key of the storage item. As our salt &amp; move storage secrets are attached to a gameSession address for further decryption, we need the local storage item key to be a dynamically updating variable.</strong></p><p>3. The second page will be the index <strong>Welcome</strong> page where all of the games available to the user will be displayed, either a game where the user is the 1st player or has an invite to join the game as the 2nd player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*aTmdHebcQzV94cxp.gif" /></figure><p>It’s a pretty simple page except for one nuance.</p><p>We have to make sure that if the game is gets further solved, it won’t be displayed in the available game sessions list, as it’s not active anymore.</p><p>I used the useContractRead hook to fetch the user’s available game sessions from the <strong>factory 👩‍🏭</strong>contract.</p><p>Then I mapped through the returned array to fetch the values of stakes of each game session. I used the useContractReads hook to read from a list of contracts.</p><pre>// pages/welcome/index.tsx<br><br>import React, { FC, useContext, useEffect } from &#39;react&#39;;<br>import { useNavigate } from &#39;react-router-dom&#39;;<br><br>import { Hash } from &#39;viem&#39;;<br>import { useContractRead, useContractReads, useWalletClient } from &#39;wagmi&#39;;<br><br>import { AppContext } from &#39;../../context/AppContext&#39;;<br>import { contracts } from &#39;../../contracts&#39;;<br>import * as S from &#39;./styles&#39;;<br><br>const WelcomePage: FC = () =&gt; {<br>  const { data: walletClient } = useWalletClient();<br>  const { isLoading, data: availableGameSessions } = useContractRead({<br>    ...contracts.factory,<br>    functionName: &#39;getGameSessions&#39;,<br>    account: walletClient?.account,<br>    watch: true,<br>  });<br>  const { data: activeGameSessions, isLoading: isGameStakesLoading } =<br>    useContractReads({<br>      contracts: availableGameSessions?.map((gameSession: Hash) =&gt; {<br>        return {<br>          address: gameSession,<br>          functionName: &#39;stake&#39;,<br>          abi: contracts.rpslsGame.abi,<br>        };<br>      }),<br>      select: (data) =&gt; {<br>        if (!availableGameSessions) return [];<br><br>        return data<br>          .filter((session) =&gt; Number(session.result) &gt; 0)<br>          .map((_, index) =&gt; availableGameSessions[index]);<br>      },<br>      watch: true,<br>    });<br><br>  const navigate = useNavigate();<br><br>  const { setIsLoading } = useContext(AppContext);<br><br>  useEffect(() =&gt; {<br>    setIsLoading?.(isLoading || isGameStakesLoading);<br>  }, [isLoading, isGameStakesLoading]);<br><br>  return activeGameSessions &amp;&amp; activeGameSessions?.length &gt;= 1 ? (<br>    &lt;S.Container&gt;<br>      {activeGameSessions.map((hash: Hash) =&gt; (<br>        &lt;S.LinkToSession onClick={() =&gt; navigate(`/game-session/${hash}`)}&gt;<br>          &lt;span&gt;{hash}&lt;/span&gt;<br>          &lt;S.ArrowRightButton /&gt;<br>        &lt;/S.LinkToSession&gt;<br>      ))}<br>      &lt;S.NewGameSessionLink onClick={() =&gt; navigate(&#39;/new-game&#39;)}&gt;<br>        Propose new game session<br>      &lt;/S.NewGameSessionLink&gt;<br>    &lt;/S.Container&gt;<br>  ) : (<br>    &lt;S.NoAvailableGameSessions&gt;<br>      &lt;S.NoAvailableGameSessionsLabel&gt;<br>        There&#39;re no available active game sessions for you yet. Propose a new<br>        game session or get invited to join one!<br>      &lt;/S.NoAvailableGameSessionsLabel&gt;<br>      &lt;S.NewGameSessionLink onClick={() =&gt; navigate(&#39;/new-game&#39;)}&gt;<br>        Propose new game session<br>      &lt;/S.NewGameSessionLink&gt;<br>    &lt;/S.NoAvailableGameSessions&gt;<br>  );<br>};<br><br>export default WelcomePage;</pre><p>4. The last page is the <strong>Game session</strong> page. It’ll be accessible to the players of the same game session, for the 2nd user to join the game &amp; make his move, the first player can then reveal his commitment, as well there’s timeout functionality incorporated. It’s a <strong>shareable</strong> link thanks to the React Router’s /game-session/:gameSession parameter.</p><pre>// pages/game-session/index.tsx<br><br>import { useContext, useEffect, useMemo, useState } from &#39;react&#39;;<br>import { useParams } from &#39;react-router-dom&#39;;<br>import { useTimer } from &#39;react-timer-hook&#39;;<br><br>import { Typography } from &#39;@mui/material&#39;;<br>import { formatEther } from &#39;viem&#39;;<br>import {<br>  Address,<br>  useAccount,<br>  useContractRead,<br>  useContractWrite,<br>  useWaitForTransaction,<br>} from &#39;wagmi&#39;;<br><br>import hiddenMoveIcon from &#39;../../assets/icons/moves/hidden-move.gif&#39;;<br>import { AppContext } from &#39;../../context/AppContext&#39;;<br>import { contracts } from &#39;../../contracts&#39;;<br>import { useLocalStorage } from &#39;../../hooks/useLocalStorage&#39;;<br>import { Move, moveIcons, moves } from &#39;../../moves&#39;;<br>import * as S from &#39;./styles&#39;;<br><br>const formatTime = (time: number): string =&gt;<br>  time &lt; 10 ? `0${time}` : `${time}`;<br><br>function GameSessionPage() {<br>  const { hash } = useParams&lt;{ hash: Address }&gt;();<br><br>  const rpslsGameContract = useMemo(<br>    () =&gt; ({<br>      abi: contracts.rpslsGame.abi,<br>      address: hash,<br>    }),<br>    [hash],<br>  );<br><br>  const { data: move2 } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;move2&#39;,<br>    watch: true,<br>  });<br><br>  const { data: stake } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;stake&#39;,<br>    watch: true,<br>  });<br><br>  const { data: player1 } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;player1&#39;,<br>    watch: true,<br>  });<br><br>  const { data: lastTimePlayed } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;lastTimePlayed&#39;,<br>    watch: true,<br>  });<br><br>  const { data: TIMEOUT_IN_MS } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;TIMEOUT_IN_MS&#39;,<br>  });<br><br>  const { data: player2 } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;player2&#39;,<br>    watch: true,<br>  });<br><br>  const { setIsLoading } = useContext(AppContext);<br><br>  const [isEligibleForTimeout, setIsEligibleForTimeout] =<br>    useState&lt;boolean&gt;(false);<br><br>  const {<br>    isLoading: claimTimeoutLoading,<br>    write: claimTimeout,<br>    data: claimTimeoutTransactionData,<br>  } = useContractWrite({<br>    ...rpslsGameContract,<br>    functionName: &#39;claimTimeout&#39;,<br>  });<br><br>  const { address } = useAccount();<br><br>  const [successMessage, setSuccessMessage] = useState&lt;string | undefined&gt;();<br><br>  const { isLoading: claimTimeoutTransactionLoading } = useWaitForTransaction({<br>    hash: claimTimeoutTransactionData?.hash,<br>    onSuccess: () =&gt; setSuccessMessage(&#39;Timeout claimed successfully&#39;),<br>  });<br><br>  useEffect(() =&gt; {<br>    setIsLoading?.(claimTimeoutLoading || claimTimeoutTransactionLoading);<br>  }, [claimTimeoutLoading, claimTimeoutTransactionLoading]);<br><br>  const { seconds, minutes, restart } = useTimer({<br>    expiryTimestamp: new Date(<br>      (Number(lastTimePlayed || 0) + Number(TIMEOUT_IN_MS || 0)) * 1000, // Convert Epoch timestamp to ms (https://dev.to/iamephraim/how-to-convert-epoch-timestamp-to-date-using-javascript-352f)<br>    ),<br>    autoStart: true,<br>    onExpire: () =&gt; setIsEligibleForTimeout(true),<br>  });<br><br>  const [selectedMove, setSelectedMove] = useState&lt;Move&gt;(Move.Null);<br><br>  const {<br>    write: submitMove,<br>    isLoading: isSubmitMoveLoading,<br>    data: submitMoveData,<br>  } = useContractWrite({<br>    ...rpslsGameContract,<br>    functionName: &#39;play&#39;,<br>    args: [selectedMove],<br>    value: stake || BigInt(0),<br>  });<br><br>  const { isLoading: isSubmitMoveTransactionLoading } = useWaitForTransaction({<br>    hash: submitMoveData?.hash,<br>    onSuccess: () =&gt; setSuccessMessage(&#39;Move submitted successfully!&#39;),<br>  });<br><br>  const [salt] = useLocalStorage(`salt-${hash}`);<br>  const [move1] = useLocalStorage(`move-${hash}`);<br><br>  const {<br>    write: solveGame,<br>    isLoading: isSolveGameLoading,<br>    data: solveGameData,<br>  } = useContractWrite({<br>    ...rpslsGameContract,<br>    functionName: &#39;solve&#39;,<br>    args: [Number(move1), String(salt)],<br>  });<br><br>  const { isLoading: isSolveGameTransactionLoading } = useWaitForTransaction({<br>    hash: solveGameData?.hash,<br>    onSuccess: () =&gt;<br>      setSuccessMessage(&#39;Game solved successfully. See the winner! 🎊🎉&#39;),<br>  });<br><br>  const { data: isPlayer1Winner } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;win&#39;,<br>    args: [Number(move1), Number(move2)],<br>    enabled: Number(move1) !== Move.Null &amp;&amp; Number(move2) !== Move.Null,<br>  });<br><br>  const { data: isPlayer2Winner } = useContractRead({<br>    ...rpslsGameContract,<br>    functionName: &#39;win&#39;,<br>    args: [Number(move2), Number(move1)],<br>    enabled: Number(move1) !== Move.Null &amp;&amp; Number(move2) !== Move.Null,<br>  });<br><br>  useEffect(() =&gt; {<br>    if (!TIMEOUT_IN_MS || !lastTimePlayed) return;<br><br>    restart(<br>      new Date(<br>        (Number(lastTimePlayed || 0) + Number(TIMEOUT_IN_MS || 0)) * 1000,<br>      ),<br>    );<br>  }, [TIMEOUT_IN_MS, lastTimePlayed]);<br><br>  return player1 &amp;&amp; (stake || !move2) ? (<br>    &lt;S.Container&gt;<br>      {player2 === address ? (<br>        &lt;S.MovesContainer&gt;<br>          {moves.map((move: Move) =&gt; (<br>            &lt;S.MoveItem<br>              className={move === selectedMove ? &#39;selected&#39; : &#39;&#39;}<br>              onClick={() =&gt; setSelectedMove(move)}<br>            &gt;<br>              &lt;img src={moveIcons[move - 1]} alt={`Move №${move}`} /&gt;<br>            &lt;/S.MoveItem&gt;<br>          ))}<br>        &lt;/S.MovesContainer&gt;<br>      ) : (<br>        &lt;&gt;&lt;/&gt;<br>      )}<br>      &lt;S.PlayerContainer&gt;<br>        &lt;S.DetailsItem&gt;<br>          &lt;strong&gt;Player 1: &lt;/strong&gt;<br>          &lt;span&gt;{player1}&lt;/span&gt;<br>        &lt;/S.DetailsItem&gt;<br>        &lt;S.DetailsItem&gt;<br>          &lt;strong&gt;Player 2: &lt;/strong&gt;<br>          &lt;span&gt;{player2}&lt;/span&gt;<br>        &lt;/S.DetailsItem&gt;<br>        &lt;S.DetailsItem&gt;<br>          &lt;strong&gt;Stake details: &lt;/strong&gt;<br>          &lt;span&gt;{stake ? formatEther(stake) : 0} ETH&lt;/span&gt;<br>        &lt;/S.DetailsItem&gt;<br>        &lt;S.DetailsItem&gt;<br>          &lt;strong&gt;Time until timeout: &lt;/strong&gt;<br>          &lt;span&gt;<br>            {formatTime(minutes)}::{formatTime(seconds)}<br>          &lt;/span&gt;<br>        &lt;/S.DetailsItem&gt;<br>        &lt;S.DetailsItem&gt;<br>          &lt;strong&gt;Player 1&#39;s move: &lt;/strong&gt;<br>          &lt;S.HiddenMoveImage src={hiddenMoveIcon} alt=&quot;?&quot; /&gt;<br>        &lt;/S.DetailsItem&gt;<br>        &lt;S.DetailsItem&gt;<br>          &lt;strong&gt;Player 2&#39;s move: &lt;/strong&gt;<br>          {player2 === address &amp;&amp; !move2 ? (<br>            &lt;S.SubmitMoveButton<br>              disabled={selectedMove === Move.Null}<br>              onClick={() =&gt; stake &amp;&amp; submitMove?.()}<br>              loading={isSubmitMoveLoading || isSubmitMoveTransactionLoading}<br>            &gt;<br>              Submit move<br>            &lt;/S.SubmitMoveButton&gt;<br>          ) : move2 ? (<br>            &lt;S.MoveImage alt=&quot;Player 2&#39;s move&quot; src={moveIcons[move2 - 1]} /&gt;<br>          ) : (<br>            &lt;span&gt;Move not submitted&lt;/span&gt;<br>          )}<br>        &lt;/S.DetailsItem&gt;<br>      &lt;/S.PlayerContainer&gt;<br>      {(player2 === address &amp;&amp; move2 &amp;&amp; isEligibleForTimeout) ||<br>      (isEligibleForTimeout &amp;&amp; player1 === address &amp;&amp; !move2) ? (<br>        &lt;S.TimeoutButton<br>          loading={claimTimeoutLoading || claimTimeoutTransactionLoading}<br>          onClick={() =&gt; claimTimeout?.()}<br>        &gt;<br>          Claim timeout<br>        &lt;/S.TimeoutButton&gt;<br>      ) : (<br>        &lt;&gt;&lt;/&gt;<br>      )}<br>      {player1 === address &amp;&amp; move2 ? (<br>        &lt;S.SolveButton<br>          loading={isSolveGameTransactionLoading || isSolveGameLoading}<br>          onClick={() =&gt; solveGame?.()}<br>        &gt;<br>          Solve game<br>        &lt;/S.SolveButton&gt;<br>      ) : (<br>        &lt;&gt;&lt;/&gt;<br>      )}<br>      {successMessage ? &lt;S.SuccessBox&gt;{successMessage}&lt;/S.SuccessBox&gt; : &lt;&gt;&lt;/&gt;}<br>    &lt;/S.Container&gt;<br>  ) : player1 &amp;&amp; move2 ? (<br>    &lt;S.GameSolvedContainer&gt;<br>      &lt;Typography variant=&quot;h3&quot;&gt;Game solved successfully!&lt;/Typography&gt;<br>      &lt;S.GameSolvedTitle variant=&quot;h4&quot;&gt;<br>        &lt;S.HighlightContainer&gt;The winner is:&lt;/S.HighlightContainer&gt;<br>      &lt;/S.GameSolvedTitle&gt;<br>      &lt;Typography variant=&quot;h6&quot;&gt;<br>        {isPlayer1Winner === false ? (<br>          &lt;strong&gt;Player2: {player2}&lt;/strong&gt;<br>        ) : isPlayer2Winner === false ? (<br>          &lt;strong&gt;Player 1: {player1}&lt;/strong&gt;<br>        ) : (<br>          &lt;strong&gt;Everyone winned. Game tied! 🪢&lt;/strong&gt;<br>        )}<br>      &lt;/Typography&gt;<br>    &lt;/S.GameSolvedContainer&gt;<br>  ) : (<br>    &lt;&gt;&lt;/&gt;<br>  );<br>}<br><br>export default GameSessionPage;</pre><ol><li>When the 1st player (the creator of the game) visits the game session page, he’ll see whether the second player submitted his move already or not yet, as well as how much time is left until the game is eligible for timeout.</li><li>When the second player visits the game session page, he’ll be able to submit his move &amp; wait for the first player to reveal his commitment &amp; solve the game.</li><li>Similarly, he can claim a timeout (refund for both players), if the 1st player goes unresponsive.</li></ol><blockquote>(I’m not using useContractEvent <strong>wagmi</strong> hook for this page because it only watches the events in real-time, but I want to display the correct state even after the game is finished, if the user wants to re-visit the page later.)</blockquote><p><strong>The final dApp from the first player’s view came out to this:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FU3CrcnErQfw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DU3CrcnErQfw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FU3CrcnErQfw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfe5adf2aa62efefd956a0642524186/href">https://medium.com/media/2cfe5adf2aa62efefd956a0642524186/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4-pfWLmlgqtoMsSAs7nlA.png" /><figcaption>/ — Welcome page with all active game sessions displayed with useContractRead &amp; useContractReads</figcaption></figure><p>The active game sessions page 👆</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*mpqjZKlmuc1RpTRcydWJpw.png" /><figcaption>Metamask useSignMessage request result | Wagmi, React, Viem, Browser Subtle Crypto API</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cC6Ay5envWzeU3jNCnLU_Q.png" /><figcaption>Metamask useContractWrite | Solidity Factory pattern</figcaption></figure><p>The prompts from my Metamask were not recorded on the video due to my video recorder’s security limitations. These looks like 👆👆👆</p><p>⌚ When the time runs out, the 1st player can claim the timeout and get his stake back before the 2nd player can join the game. The game session will get disactivated automatically. 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3clhUhgaV7aQpvFJfhskxg.png" /></figure><p>For the second player, the game session page allows him to select his move &amp; submit it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*DTQOkAqWv9Mu0dH3cKajSw.png" /><figcaption>Rock paper scissors lizard spock Solidity &amp; React game: Player2, submit your move!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*urTJuB2VkVgZyMJMf-DiFg.png" /><figcaption>useContractWrite: “play”() function</figcaption></figure><p>The last thing for the player 1 is to solve the game by revealing his commitment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmL-1oH49I2wuBguVoXIMw.png" /><figcaption>Both players submitted their moves of choice</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOSAIg1N925hE1mU2CZXzg.png" /><figcaption>Solve game — rock paper scissors lizard spock!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*famImDqNjD_Sku_VSS4qIg.png" /><figcaption>Wagmi, React &amp; Typescript: Game solved successfully! Contract write (useContractWrite) completed.</figcaption></figure><p>The game is finished &amp; the stake was distributed fairly.</p><p>If the user claims a timeout considering there really is no time left for the opponent to make his move, the result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcHUQvN2CSw06uMzqHLcGw.png" /><figcaption>Timeout claimed Solidity claimTimeout() game smart contract | React Context API</figcaption></figure><h3>Let me know if this tutorial was helpful! © Built with love and a pinch of posture health. 🙂🙆‍♀️</h3><p>If you have any questions or ideas, make sure to ask those in the comments below. 🗨️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*6ho4_O2F825lIyCz.gif" /><figcaption>Gm all Web3 devs, it’s time for a posture check!</figcaption></figure><h4>Bonus: EsLint &amp; Prettier React, Typescript, Viem, Web3, MaterialUI (MUI) &amp; styled-components config.</h4><p>See these beautifully sorted &amp; formatted imports and code with no unused variables nor hooks mistakes?</p><p>Here’s my favorite (August/September 2023 EDITION) Prettier &amp; Eslint linting config.</p><pre>// &lt;root&gt;/prettier.config.js<br><br>module.exports = {<br>  plugins: [&#39;@trivago/prettier-plugin-sort-imports&#39;],<br>  importOrder: [&#39;react&#39;, &#39;&lt;THIRD_PARTY_MODULES&gt;&#39;, &#39;^[./]&#39;],<br>  importOrderSeparation: true,<br>  importOrderSortSpecifiers: true,<br>  importOrderCaseInsensitive: false,<br>  singleQuote: true,<br>};</pre><pre>// &lt;root&gt;/.eslintrc.js<br><br>module.exports = {<br>  root: true,<br>  plugins: [&#39;@typescript-eslint&#39;, &#39;import&#39;, &#39;prettier&#39;],<br>  extends: [<br>    &#39;airbnb-typescript/base&#39;,<br>    &#39;plugin:react-hooks/recommended&#39;,<br>    &#39;prettier&#39;,<br>    &#39;plugin:@typescript-eslint/recommended&#39;,<br>    &#39;plugin:import/typescript&#39;,<br>  ],<br>  parser: &#39;@typescript-eslint/parser&#39;,<br>  parserOptions: {<br>    project: &#39;./tsconfig.eslint.json&#39;,<br>  },<br>};</pre><pre>// tsconfig.eslint.json<br><br>{<br>  &quot;extends&quot;: &quot;./tsconfig.json&quot;,<br>  &quot;include&quot;: [&quot;./*/**/**.tsx&quot;, &quot;./*/**/**.ts&quot;, &quot;./**.js&quot;, &quot;./**.d.ts&quot;]<br>}</pre><h4>Don’t forget to also install these incredible community-supported NPM packages to run the linter (eslint . — fix &amp;&amp; prettier . — write) and fix all your dummy code style issues:</h4><p><strong>yarn add -D </strong><a href="http://twitter.com/trivago/prettier-plugin-sort-impo"><strong>@trivago/prettier-plugin-sort-impo</strong></a><strong>rts </strong><a href="http://twitter.com/typescript"><strong>@typescript</strong></a><strong>-eslint/eslint-plugin </strong><a href="http://twitter.com/typescript"><strong>@typescript</strong></a><strong>-eslint/parser eslint prettier eslint-config-airbnb-base eslint-config-airbnb-typescript eslint-config-prettier eslint-plugin-prettier eslint-plugin-react-hooks</strong></p><h3><strong>Voilà! 💐</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d5a1f8c3230" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/rock-paper-scissors-lizard-spock-game-with-solidity-react-typescript-wagmi-viem-commit-reveal-8d5a1f8c3230">✔ Best practices for front-end dApp development: On-Chain dApp Game with Solidity, React…</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>
    </channel>
</rss>