<?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 Hua Jiang on Medium]]></title>
        <description><![CDATA[Stories by Hua Jiang on Medium]]></description>
        <link>https://medium.com/@hua.jiang_92778?source=rss-78ad8d9c59f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ggle_V-f7y-pAyd1</url>
            <title>Stories by Hua Jiang on Medium</title>
            <link>https://medium.com/@hua.jiang_92778?source=rss-78ad8d9c59f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:41:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hua.jiang_92778/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[Web3.0 dApp Development—How to make dapp using deeperchain]]></title>
            <link>https://medium.com/@hua.jiang_92778/web3-0-dapp-development-how-to-make-dapp-using-deeperchain-78970456f03a?source=rss-78ad8d9c59f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/78970456f03a</guid>
            <dc:creator><![CDATA[Hua Jiang]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 08:26:11 GMT</pubDate>
            <atom:updated>2022-03-20T08:27:47.408Z</atom:updated>
            <content:encoded><![CDATA[<p>This dapp including smart contract, front-end code full-stack practice,is a simple NFT mint and presentation project. In this tutorial we will walk you through a step-by-step using deeperchain evm deploy smart contract.</p><p><strong>Running and testing locally</strong></p><p>First we will run the project to see what we are going to analyse and implement.</p><h4>Running locally</h4><p>First we run the project locally.<br>1,clone the project and switch to the loogies-svg-nft branch.</p><pre>git clone https://github.com/qiwihui/scaffold-eth.git loogies-svg-nft<br>cd loogies-svg-nft<br>git checkout loogies-svg-nft</pre><p>2,Installing dependency packages</p><pre>yarn install</pre><p>3,Running the front-end</p><pre>yarn start</pre><p>4,In the second terminal window, run the local test chain</p><pre>yarn chain</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmC4MchlhFd2I_2PUGXW4w.png" /></figure><p>5,In the third terminal window, run the deployment contract</p><pre>yarn deploy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EK9viNCsiIOhEl-rUNEGFA.png" /></figure><p>At this point visit <a href="http://localhost:3000/">http://localhost:3000</a> in your browser and you will see the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Apq_gJL4ogLUlKqaTr0pwQ.png" /></figure><h4>Local test</h4><p>1,first add the local network to the MetaMask wallet and switch to the local network.<br>Network name: Localhost 8545<br>Add RPC URL: <a href="http://localhost:8545/">http://localhost:8545</a><br>Chain ID: 31337<br>Currency Symbol: ETH<br>2,Create a new local wallet account.<br>3,Copy the wallet address and send some test ETH to this address in the bottom left corner of the page.<br>4,click on connect in the top right corner of the page to connect to the wallet.<br>5,Click on Mint to cast.<br>6,When the transaction is successful, the newly minted NFT can be seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhXhMgWFrFwJ6V1xuqZK6A.png" /></figure><p>We began our analysis of the project contract.</p><h3>Smart Contract Analysis</h3><p>NFT and ERC721</p><p>NFT, or Non-Fungible Token, refers to a non-homogeneous token and corresponds to the ERC-721 standard on ethereum. Generally in smart contracts, the definition of NFT contains tokenId and tokenURI, the tokenId of each NFT is unique, tokenURI for the metadata that holds the NFT, can be image URL, description, properties, etc.. If an NFT wants to be displayed and sold on the NFT marketplace, the tokenURI content needs to correspond to the standards of the NFT marketplace, for example, in the OpenSea metadata standard for the NFT marketplace, which indicates the attributes that need to be set for the NFT to be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCeXzoI8tO5_GcYN8A9eNQ.png" /></figure><p>Correspondence between NFT metadata and presentation in OpenSea</p><h4>Contracts overview</h4><p>The contract files for the loogies-svg-nft project are located under the packages/hardhat/contracts/ path and contain the following three files.</p><p>packages/hardhat/contracts/<br>├── HexStrings.sol<br>├── ToColor.sol<br>└── YourCollectible.sol</p><p>HexString.sol : generates the address string.<br>ToColor.sol : generates colour-coded strings.<br>YourCollectible.sol : Loogies NFT’s contract file, the main functions involve contract casting and metadata generation.</p><p>The main structure and methods of the contract are:</p><pre>contract YourCollectible is ERC721, Ownable {</pre><pre>// Constructors function<br> constructor() public ERC721(“Loogies”, “LOOG”) {<br> }<br> // mint NFT<br> function mintItem()<br> public<br> returns (uint256)<br> {<br> …<br> }<br> // Get the tokenId corresponding to the tokenURI<br> function tokenURI(uint256 id) public view override returns (string memory) {<br> …<br> }<br> // Generate the tokenId corresponding to the svg code<br> function generateSVGofTokenById(uint256 id) internal view returns (string memory) {<br> …<br> }</pre><pre>// Generate tokenId corresponding to svg code, mainly for drawing images<br> function renderTokenById(uint256 id) public view returns (string memory) {<br> …<br> }</pre><pre>}</pre><h3>Constructor function</h3><pre>constructor() public ERC721(&quot;Deeperchain&quot;, &quot;DPR&quot;) {<br>    // RELEASE THE LOOGIES!<br>  }</pre><p>Token symbol: Loogies<br>Token name: LOOG<br>The contract is inherited from OpenZeppelin’s ERC721.sol, which is the basic contract code provided by OpenZeppelin and can be easily used by developers.</p><h4>Application library functions</h4><p>Different library functions are applied in the contract for uint256, uint160 and bytes3 to extend the corresponding functions.</p><p>// Enables uint256 to have toHexString functionality<br>using Strings for uint256;<br>// Make uint160 with custom toHexString functionality<br>using HexStrings for uint160;<br>// Make bytes3 easy to generate front-end colour representations<br>using ToColor for bytes3;<br>// Counting function<br>using Counters for Counters.Counter;</p><h4>Mint Duration</h4><p>The following codes are Mint time limits.</p><pre>uint256 mintDeadline = block.timestamp + 24 hours;</pre><pre>function mintItem()<br> public<br> returns (uint256)<br> {<br> require( block.timestamp &lt; mintDeadline, “DONE MINTING”);<br>…</pre><p>Contracts can be cast within 24 hours of deployment, beyond that time an exception is raised. This mechanism is similar to pre-selling. As this contract is relatively simple, no whitelisting mechanism is used, and in general, in practical situations, pre-selling and whitelisting are used to control the issuance of NFTs.</p><h4>Mint Minting</h4><p>Minting an NFT is actually setting two pieces of information in the contract: <br>tokenId and its owner<br>tokenId and its tokenURI</p><p>We start by looking at the mint function mintItem:</p><pre>// Used to store the characteristics of each cast Loogies, where colour indicates colour and chubbiness indicates fatness<br>mapping (uint256 =&gt; bytes3) public color;<br>mapping (uint256 =&gt; uint256) public chubbiness;<br><br>...<br><br>function mintItem()<br>      public<br>      returns (uint256)<br>  {<br>      require( block.timestamp &lt; mintDeadline, &quot;DONE MINTING&quot;);<br>   // Self-incrementing _tokenIds before each casting to ensure that _tokenIds are unique<br>      _tokenIds.increment();<br><br>      uint256 id = _tokenIds.current();<br>   // minter are bound to tokenId<br>      _mint(msg.sender, id);<br>   // Generate random properties corresponding to tokenId<br>      bytes32 predictableRandom = keccak256(abi.encodePacked( blockhash(block.number-1), msg.sender, address(this), id ));<br>      color[id] = bytes2(predictableRandom[0]) | ( bytes2(predictableRandom[1]) &gt;&gt; 8 ) | ( bytes3(predictableRandom[2]) &gt;&gt; 16 );<br>      chubbiness[id] = 35+((55*uint256(uint8(predictableRandom[3])))/255);<br><br>      return id;<br>  }</pre><p>tokenId is self-incremented each time it is mint, ensuring that the tokenId is unique.<br>The _mint function binds the tokenId and its owner.<br>The attribute corresponding to each tokenId is generated in a random way, as follows</p><p>generating a hash predictableRandom from the hash of the previous block (blockhash(block.number-1)), the current minting account (msg.sender), the contract address (address(this)) and the tokenId.</p><p>Calculate the NFT colour: get the colour by bit or by the first three bits of predictableRandom, the colour is represented by bytes3, where:</p><p>bytes2(predictableRandom[0]) corresponds to the lowest blue value, ( bytes2(predictableRandom[1]) &gt;&gt; 8 ) corresponds to the middle green value, and ( bytes3(predictableRandom[1]) &gt;&gt; 8 ) corresponds to the middle green value. values, ( bytes3(predictableRandom[2]) &gt;&gt; 16 ) corresponding to the highest red values.</p><p>Calculate NFT fat and thin:</p><p>35+((55*uint256(uint8(predictableRandom[3])))/255); , uint8(predictableRandom[3]) is between 0 and 255, so the minimum value is 35 and the maximum value is 35+55 = 90.</p><p>For example, the NFT image with a colour of 0x4cc4c1 and chubbiness of 88 would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgTVN843QLfaGjNW2waBLg.png" /></figure><h4>tokenURI Function</h4><p>The tokenURI function accepts the tokenId parameter and returns the encoded metadata string.</p><pre>function tokenURI(uint256 id) public view override returns (string memory) {<br>   // Check if the id exists<br>      require(_exists(id), &quot;not exist&quot;);<br>      string memory name = string(abi.encodePacked(&#39;Loogie #&#39;,id.toString()));<br>      string memory description = string(abi.encodePacked(&#39;This Loogie is the color #&#39;,color[id].toColor(),&#39; with a chubbiness of &#39;,uint2str(chubbiness[id]),&#39;!!!&#39;));<br>      // Generate svg base64 encoding of the image<br>   string memory image = Base64.encode(bytes(generateSVGofTokenById(id)));<br><br>      return<br>          string(<br>              abi.encodePacked(<br>                &#39;data:application/json;base64,&#39;,<br>        // Encoding metadata via base64<br>                Base64.encode(<br>                    bytes(<br>                          abi.encodePacked(<br>                              &#39;{&quot;name&quot;:&quot;&#39;,<br>                              name,<br>                              &#39;&quot;, &quot;description&quot;:&quot;&#39;,<br>                              description,<br>                              &#39;&quot;, &quot;external_url&quot;:&quot;https://burnyboys.com/token/&#39;,<br>                              id.toString(),<br>                              &#39;&quot;, &quot;attributes&quot;: [{&quot;trait_type&quot;: &quot;color&quot;, &quot;value&quot;: &quot;#&#39;,<br>                              color[id].toColor(),<br>                              &#39;&quot;},{&quot;trait_type&quot;: &quot;chubbiness&quot;, &quot;value&quot;: &#39;,<br>                              uint2str(chubbiness[id]),<br>                              &#39;}], &quot;owner&quot;:&quot;&#39;,<br>                              (uint160(ownerOf(id))).toHexString(20),<br>                              &#39;&quot;, &quot;image&quot;: &quot;&#39;,<br>                              &#39;data:image/svg+xml;base64,&#39;,<br>                              image,<br>                              &#39;&quot;}&#39;<br>                          )<br>                        )<br>                    )<br>              )<br>          );<br>  }<br>// Generated SVG string<br>function generateSVGofTokenById(uint256 id) internal view returns (string memory) {<br>...<br>}<br><br>//Drawing images<br>// Visibility is `public` to enable it being called by other contracts for composition.<br>function renderTokenById(uint256 id) public view returns (string memory) {<br>...<br>}</pre><p>The generateSVGofTokenById function returns the SVG string generated by the colour and fatness attributes corresponding to the tokenId, and the renderTokenById user draws the image.<br>We can see that the NFT metadata contains the following attributes.<br>name: name<br>description: description<br>external_url: external link<br>attributes: attributes<br>colour: colour<br>chubbiness: fatness<br>owner: the owner, in hexadecimal form of an ethereal address<br>image: the base64 encoding of the image corresponding to the SVG<br>Here, we have a look at what an SVG is, using actual data. tokenId is 1 and the corresponding tokenURI results in</p><pre>data:application/json;base64,eyJuYW1lIjoiTG9vZ2llICMxIiwiZGVzY3JpcHRpb24iOiJUaGlzIExvb2dpZSBpcyB0aGUgY29sb3IgIzRjYzRjMSB3aXRoIGEgY2h1YmJpbmVzcyBvZiA4OCEhISIsImV4dGVybmFsX3VybCI6Imh0dHBzOi8vYnVybnlib3lzLmNvbS90b2tlbi8xIiwiYXR0cmlidXRlcyI6W3sidHJhaXRfdHlwZSI6ImNvbG9yIiwidmFsdWUiOiIjNGNjNGMxIn0seyJ0cmFpdF90eXBlIjoiY2h1YmJpbmVzcyIsInZhbHVlIjo4OH1dLCJvd25lciI6IjB4MTY5ODQxYWEzMDI0Y2ZhNTcwMDI0ZWI3ZGQ2YmY1Zjc3NDA5MjA4OCIsImltYWdlIjoiZGF0YTppbWFnZS9zdmcreG1sO2Jhc2U2NCxQSE4yWnlCM2FXUjBhRDBpTkRBd0lpQm9aV2xuYUhROUlqUXdNQ0lnZUcxc2JuTTlJbWgwZEhBNkx5OTNkM2N1ZHpNdWIzSm5Mekl3TURBdmMzWm5JajQ4WnlCcFpEMGlaWGxsTVNJK1BHVnNiR2x3YzJVZ2MzUnliMnRsTFhkcFpIUm9QU0l6SWlCeWVUMGlNamt1TlNJZ2NuZzlJakk1TGpVaUlHbGtQU0p6ZG1kZk1TSWdZM2s5SWpFMU5DNDFJaUJqZUQwaU1UZ3hMalVpSUhOMGNtOXJaVDBpSXpBd01DSWdabWxzYkQwaUkyWm1aaUl2UGp4bGJHeHBjSE5sSUhKNVBTSXpMalVpSUhKNFBTSXlMalVpSUdsa1BTSnpkbWRmTXlJZ1kzazlJakUxTkM0MUlpQmplRDBpTVRjekxqVWlJSE4wY205clpTMTNhV1IwYUQwaU15SWdjM1J5YjJ0bFBTSWpNREF3SWlCbWFXeHNQU0lqTURBd01EQXdJaTgrUEM5blBqeG5JR2xrUFNKb1pXRmtJajQ4Wld4c2FYQnpaU0JtYVd4c1BTSWpOR05qTkdNeElpQnpkSEp2YTJVdGQybGtkR2c5SWpNaUlHTjRQU0l5TURRdU5TSWdZM2s5SWpJeE1TNDRNREEyTlNJZ2FXUTlJbk4yWjE4MUlpQnllRDBpT0RnaUlISjVQU0kxTVM0NE1EQTJOU0lnYzNSeWIydGxQU0lqTURBd0lpOCtQQzluUGp4bklHbGtQU0psZVdVeUlqNDhaV3hzYVhCelpTQnpkSEp2YTJVdGQybGtkR2c5SWpNaUlISjVQU0l5T1M0MUlpQnllRDBpTWprdU5TSWdhV1E5SW5OMloxOHlJaUJqZVQwaU1UWTRMalVpSUdONFBTSXlNRGt1TlNJZ2MzUnliMnRsUFNJak1EQXdJaUJtYVd4c1BTSWpabVptSWk4K1BHVnNiR2x3YzJVZ2NuazlJak11TlNJZ2NuZzlJak1pSUdsa1BTSnpkbWRmTkNJZ1kzazlJakUyT1M0MUlpQmplRDBpTWpBNElpQnpkSEp2YTJVdGQybGtkR2c5SWpNaUlHWnBiR3c5SWlNd01EQXdNREFpSUhOMGNtOXJaVDBpSXpBd01DSXZQand2Wno0OEwzTjJaejQ9In0=</pre><p>Decoding data:application/json;base64 with base64 yields the following json (the following json is formatted for readability).</p><pre>{<br> “name”: “Loogie #1”,<br> “description”: “This Loogie is the color #4cc4c1 with a chubbiness of 88!!!”,<br> “external_url”: “https://burnyboys.com/token/1&quot;,<br> “attributes”: [<br> {<br> “trait_type”: “color”,<br> “value”: “#4cc4c1”<br> },<br> {<br> “trait_type”: “chubbiness”,<br> “value”: 88<br> }<br> ],<br> “owner”: “0x169841aa3024cfa570024eb7dd6bf5f774092088”,<br> “image”: “data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjQwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBpZD0iZXllMSI+PGVsbGlwc2Ugc3Ryb2tlLXdpZHRoPSIzIiByeT0iMjkuNSIgcng9IjI5LjUiIGlkPSJzdmdfMSIgY3k9IjE1NC41IiBjeD0iMTgxLjUiIHN0cm9rZT0iIzAwMCIgZmlsbD0iI2ZmZiIvPjxlbGxpcHNlIHJ5PSIzLjUiIHJ4PSIyLjUiIGlkPSJzdmdfMyIgY3k9IjE1NC41IiBjeD0iMTczLjUiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlPSIjMDAwIiBmaWxsPSIjMDAwMDAwIi8+PC9nPjxnIGlkPSJoZWFkIj48ZWxsaXBzZSBmaWxsPSIjNGNjNGMxIiBzdHJva2Utd2lkdGg9IjMiIGN4PSIyMDQuNSIgY3k9IjIxMS44MDA2NSIgaWQ9InN2Z181IiByeD0iODgiIHJ5PSI1MS44MDA2NSIgc3Ryb2tlPSIjMDAwIi8+PC9nPjxnIGlkPSJleWUyIj48ZWxsaXBzZSBzdHJva2Utd2lkdGg9IjMiIHJ5PSIyOS41IiByeD0iMjkuNSIgaWQ9InN2Z18yIiBjeT0iMTY4LjUiIGN4PSIyMDkuNSIgc3Ryb2tlPSIjMDAwIiBmaWxsPSIjZmZmIi8+PGVsbGlwc2Ugcnk9IjMuNSIgcng9IjMiIGlkPSJzdmdfNCIgY3k9IjE2OS41IiBjeD0iMjA4IiBzdHJva2Utd2lkdGg9IjMiIGZpbGw9IiMwMDAwMDAiIHN0cm9rZT0iIzAwMCIvPjwvZz48L3N2Zz4=”<br>}</pre><p>We decode and format the image field to obtain an SVG of the image.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;400&quot; height=&quot;400&quot;&gt;<br>   &lt;g id=&quot;eye1&quot;&gt;<br>      &lt;ellipse stroke-width=&quot;3&quot; ry=&quot;29.5&quot; rx=&quot;29.5&quot; id=&quot;svg_1&quot; cy=&quot;154.5&quot; cx=&quot;181.5&quot; stroke=&quot;#000&quot; fill=&quot;#fff&quot; /&gt;<br>      &lt;ellipse ry=&quot;3.5&quot; rx=&quot;2.5&quot; id=&quot;svg_3&quot; cy=&quot;154.5&quot; cx=&quot;173.5&quot; stroke-width=&quot;3&quot; stroke=&quot;#000&quot; fill=&quot;#000000&quot; /&gt;<br>   &lt;/g&gt;<br>   &lt;g id=&quot;head&quot;&gt;<br>      &lt;ellipse fill=&quot;#4cc4c1&quot; stroke-width=&quot;3&quot; cx=&quot;204.5&quot; cy=&quot;211.80065&quot; id=&quot;svg_5&quot; rx=&quot;88&quot; ry=&quot;51.80065&quot; stroke=&quot;#000&quot; /&gt;<br>   &lt;/g&gt;<br>   &lt;g id=&quot;eye2&quot;&gt;<br>      &lt;ellipse stroke-width=&quot;3&quot; ry=&quot;29.5&quot; rx=&quot;29.5&quot; id=&quot;svg_2&quot; cy=&quot;168.5&quot; cx=&quot;209.5&quot; stroke=&quot;#000&quot; fill=&quot;#fff&quot; /&gt;<br>      &lt;ellipse ry=&quot;3.5&quot; rx=&quot;3&quot; id=&quot;svg_4&quot; cy=&quot;169.5&quot; cx=&quot;208&quot; stroke-width=&quot;3&quot; fill=&quot;#000000&quot; stroke=&quot;#000&quot; /&gt;<br>   &lt;/g&gt;<br>&lt;/svg&gt;</pre><p>SVG is a language defined in XML to describe two-dimensional vector and vector/raster graphics. It is widely used as it can be displayed in any size and without sacrificing image quality, it can be described using code and is easily editable.<br>As can be seen from the code above combined with the image below, this SVG contains the following.<br>an XML declaration in the first line, indicating the version and encoding type, followed by the width and height of the SVG.<br>eye1: an eye circle and black eye drawn by two ellipses (ellipse).<br>head: ellipse filled with the colour #4cc4c1 for the body.<br>eye2: identical to eye1, positioned differently.<br>eye1, head and eye2 are superimposed in sequence to obtain the final shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7fgIKW8icw7_rerCqNCwQ.png" /></figure><h4>Explanation of helper functions</h4><p>uint2str converts a uint to a string, e.g. 123 to ‘123’</p><pre>function uint2str(uint _i) internal pure returns (string memory _uintAsString) {<br>      if (_i == 0) {<br>          return &quot;0&quot;;<br>      }<br>      uint j = _i;<br>   // uint 位数<br>      uint len;<br>      while (j != 0) {<br>          len++;<br>          j /= 10;<br>      }<br>      bytes memory bstr = new bytes(len);<br>      uint k = len;<br>      while (_i != 0) {<br>          k = k-1;<br>       // _i 个位数字<br>          uint8 temp = (48 + uint8(_i - _i / 10 * 10));<br>          bytes1 b1 = bytes1(temp);<br>          bstr[k] = b1;<br>          _i /= 10;<br>      }<br>      return string(bstr);<br>  }</pre><p>ToColor.sol library: converts byte3 types to front-end colour strings, e.g. input 0x4cc4c1 output ‘4cc4c1’</p><pre>library ToColor {<br> bytes16 internal constant ALPHABET = ‘0123456789abcdef’;</pre><pre>function toColor(bytes3 value) internal pure returns (string memory) {<br> bytes memory buffer = new bytes(6);<br> for (uint256 i = 0; i &lt; 3; i++) {<br> buffer[i*2+1] = ALPHABET[uint8(value[i]) &amp; 0xf];<br> buffer[i*2] = ALPHABET[uint8(value[i]&gt;&gt;4) &amp; 0xf];<br> }<br> return string(buffer);<br> }<br>}</pre><p>HexStrings.sol library: the main function is to extract the uint by length bits, corresponding to the function that intercepts the first 20 bits when generating a public key: (*uint160*(ownerOf(id))).toHexString(20), this expression generates the address of the owner of the corresponding tokenId.</p><pre>library HexStrings {<br> bytes16 internal constant ALPHABET = ‘0123456789abcdef’;</pre><pre>function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {<br> bytes memory buffer = new bytes(2 * length + 2);<br> buffer[0] = ‘0’;<br> buffer[1] = ‘x’;<br> for (uint256 i = 2 * length + 1; i &gt; 1; — i) {<br> buffer[i] = ALPHABET[value &amp; 0xf];<br> value &gt;&gt;= 4;<br> }<br> return string(buffer);<br> }<br>}</pre><p>At this point, the analysis of the contract source code is complete.<br>Below we will briefly analyse the front-end logic and then we will implement the NFT casting and presentation functionality step by step. Before switching the code over to the front-end code commit, follow the steps below to add functionality step by step.</p><h4>Front-end logic analysis</h4><p>The front-end files for the project are located in packages/react-app and the locations of the files covered in the following articles will be found in this file.</p><blockquote><em>查看App.jsx：</em></blockquote><blockquote><a href="https://github.com/qiwihui/scaffold-eth/blob/loogies-svg-nft/packages/react-app/src/App.jsx"><em>https://github.com/qiwihui/scaffold-eth/blob/loogies-svg-nft/packages/react-app/src/App.jsx</em></a></blockquote><p>Let’s start by looking at src/App.jsx, the main page of the project, and we can view the main parts of this file using the code editor at</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaYAlhl-FfYAajpglakK7w.png" /></figure><p>The functions and components included are<br>Header: the title bar, which displays the title<br>NetworkDisplay: the status of the network you are on<br>Menu, Switch: menu switch<br>ThemeSwitch: lower right corner light and dark theme switch<br>Account: the top-right account information component<br>The next two Rows correspond to the Gas display, Support and Local taps in the bottom left corner<br>We will now look at the logical implementation of NetworkDisplay and Account, as well as the functionality in Menu, Switch.</p><h4>NetworkDisplay</h4><p>Component location: src/components/NetworkDisplay.jsx<br>Contains two main functions.<br>Displaying the name of the currently selected network.<br>A warning if the network the wallet is currently on does not match the network settings in the project, where the network ID needs to be set to 31337 when the local network is selected.</p><pre>function NetworkDisplay({<br>  NETWORKCHECK,<br>  localChainId,<br>  selectedChainId,<br>  targetNetwork,<br>  USE_NETWORK_SELECTOR,<br>  logoutOfWeb3Modal,<br>}) {<br>  let networkDisplay = &quot;&quot;;<br>  if (NETWORKCHECK &amp;&amp; localChainId &amp;&amp; selectedChainId &amp;&amp; localChainId !== selectedChainId) {<br>    const networkSelected = NETWORK(selectedChainId);<br>    const networkLocal = NETWORK(localChainId);<br>    if (selectedChainId === 1337 &amp;&amp; localChainId === 31337) {<br>   <em>// </em>Prompt for incorrect network ID<br>   ...<br>    } else {<br>   <em>// </em>Prompt for network error<br>   ...<br>    }<br>  } else {<br>    networkDisplay = USE_NETWORK_SELECTOR ? null : (<br>      <em>// </em>Show network name<br>      &lt;div style={{ zIndex: -1, position: &quot;absolute&quot;, right: 154, top: 28, padding: 16, color: targetNetwork.color }}&gt;<br>        {targetNetwork.name}<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  console.log({ networkDisplay });<br><br>  return networkDisplay;<br>}</pre><h4>Account</h4><p>Component location: src/components/Account.jsx<br>Contains two main functions.<br>Displaying the current wallet<br>Show wallet balance<br>Show Connect or Logout<br>This function is required to connect to a wallet such as MetaMask and listen to the wallet’s chainChanged, accountsChanged and disconnect events, i.e. when we switch networks in the wallet, select when we switch networks, select an account to connect to and disconnect from the wallet.</p><pre>const loadWeb3Modal = useCallback(async () =&gt; {<br>  <em>// </em>Connect Wallet<br>    const provider = await web3Modal.connect();<br>    setInjectedProvider(new ethers.providers.Web3Provider(provider));<br>  <em>// </em>Listening to the switching network<br>    provider.on(&quot;chainChanged&quot;, chainId =&gt; {<br>      console.log(`chain changed to ${chainId}! updating providers`);<br>      setInjectedProvider(new ethers.providers.Web3Provider(provider));<br>    });<br>    <em>// </em>Listening to switching accounts<br>    provider.on(&quot;accountsChanged&quot;, () =&gt; {<br>      console.log(`account changed!`);<br>      setInjectedProvider(new ethers.providers.Web3Provider(provider));<br>    });<br>  <em>// </em>Listening for disconnections<br>    <em>// Subscribe to session disconnection</em><br>    provider.on(&quot;disconnect&quot;, (code, reason) =&gt; {<br>      console.log(code, reason);<br>      logoutOfWeb3Modal();<br>    });<br>    <em>// eslint-disable-next-line</em><br>  }, [setInjectedProvider]);</pre><p>Similarly, in the case of a connected wallet, the user clicks Logout to invoke the logoutOfWeb3Modal function.</p><pre>const logoutOfWeb3Modal = async () =&gt; {<br>  <em>// </em>Clear the network provider of the cache and disconnect<br>    await web3Modal.clearCachedProvider();<br>    if (injectedProvider &amp;&amp; injectedProvider.provider &amp;&amp; typeof injectedProvider.provider.disconnect == &quot;function&quot;) {<br>      await injectedProvider.provider.disconnect();<br>    }<br>    setTimeout(() =&gt; {<br>      window.location.reload();<br>    }, 1);<br>  };</pre><h4>Menu, Switch</h4><p>These two menus correspond to the display menu and to the switch menu function, respectively.<br>App Home: the project wants us to put the functions we need to implement in this menu, such as the casting and display functions of the NFT we will implement.<br>Debug Contracts: debug your own contracts, which will show you the state variables and functions that can be called based on the contract’s ABI file.<br>Hints: programming hints<br>ExampleUI: an example UI that can be used for programming purposes<br>Mainnet DAI: the contract status and available functions of the Ethernet mainnet DAI, which is consistent with the Debug Contracts function<br>Subgraph: Listening and querying for events in the contract using The Graph protocol.</p><h4>Debugging information</h4><p>App.jsx also contains debug information that prints the current page state, allowing you to view the current state variables in real time as you develop.</p><pre><em>//</em><br>  <em>// 🧫 DEBUG 👨🏻‍🔬</em><br>  <em>//</em><br>  useEffect(() =&gt; {<br>    if (<br>      DEBUG &amp;&amp;<br>      mainnetProvider &amp;&amp;<br>      address &amp;&amp;<br>      selectedChainId &amp;&amp;<br>      yourLocalBalance &amp;&amp;<br>      yourMainnetBalance &amp;&amp;<br>      readContracts &amp;&amp;<br>      writeContracts &amp;&amp;<br>      mainnetContracts<br>    ) {<br>      console.log(&quot;_____________________________________ 🏗 scaffold-eth _____________________________________&quot;);<br>      console.log(&quot;🌎 mainnetProvider&quot;, mainnetProvider);<br>      console.log(&quot;🏠 localChainId&quot;, localChainId);<br>      console.log(&quot;👩‍💼 selected address:&quot;, address);<br>      console.log(&quot;🕵🏻‍♂️ selectedChainId:&quot;, selectedChainId);<br>      console.log(&quot;💵 yourLocalBalance&quot;, yourLocalBalance ? ethers.utils.formatEther(yourLocalBalance) : &quot;...&quot;);<br>      console.log(&quot;💵 yourMainnetBalance&quot;, yourMainnetBalance ? ethers.utils.formatEther(yourMainnetBalance) : &quot;...&quot;);<br>      console.log(&quot;📝 readContracts&quot;, readContracts);<br>      console.log(&quot;🌍 DAI contract on mainnet:&quot;, mainnetContracts);<br>      console.log(&quot;💵 yourMainnetDAIBalance&quot;, myMainnetDAIBalance);<br>      console.log(&quot;🔐 writeContracts&quot;, writeContracts);<br>    }<br>  }, [<br>    mainnetProvider,<br>    address,<br>    selectedChainId,<br>    yourLocalBalance,<br>    yourMainnetBalance,<br>    readContracts,<br>    writeContracts,<br>    mainnetContracts,<br>    localChainId,<br>    myMainnetDAIBalance,<br>  ]);</pre><p>After viewing the basic functions of the home page, we start implementing the two functions of NFT casting and displaying the NFT list.</p><h4>NFT function implementation</h4><p>We will implement the following three main parts of functionality.<br>Minting NFTs.<br>Displaying the NFT list.<br>Displaying the list of NFT contract interfaces.<br>mintint NFT</p><p>First we find the component that corresponds to the App Home, as you can see from the code below, which corresponds to the Home component, located in src/views/Home.jsx.</p><pre>…<br> &lt;Switch&gt;<br> &lt;Route exact path=”/”&gt;<br> {/* pass in any web3 props to this Home component. For example, yourLocalBalance */}<br> &lt;Home yourLocalBalance={yourLocalBalance} readContracts={readContracts} /&gt;<br> &lt;/Route&gt;<br> ….</pre><p>Delete the contents of Home.jsx and add the following Mint button.</p><pre>import React, { useState } from &quot;react&quot;;<br>import { Button, Card, List } from &quot;antd&quot;;<br><br>function Home({ <br>  isSigner,<br>  loadWeb3Modal,<br>  tx,<br>  writeContracts,<br>}) {<br><br>  return (<br>    &lt;div&gt;<br>      {/* Mint button */}<br>      &lt;div style={{ maxWidth: 820, margin: &quot;auto&quot;, marginTop: 32, paddingBottom: 32 }}&gt;<br>        {isSigner?(<br>          &lt;Button type={&quot;primary&quot;} onClick={()=&gt;{<br>            tx( writeContracts.YourCollectible.mintItem() )<br>          }}&gt;MINT&lt;/Button&gt;<br>        ):(<br>          &lt;Button type={&quot;primary&quot;} onClick={loadWeb3Modal}&gt;CONNECT WALLET&lt;/Button&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Home;</pre><p>Also change the use of the corresponding component in Switch to</p><pre>...<br>      &lt;Switch&gt;<br>        &lt;Route exact path=&quot;/&quot;&gt;<br>          {/* pass in any web3 props to this Home component. For example, yourLocalBalance */}<br>          &lt;Home<br>            isSigner={userSigner}<br>            loadWeb3Modal={loadWeb3Modal}<br>            tx={tx}<br>            writeContracts={writeContracts}<br>          /&gt;<br>       ...</pre><p>The renderings are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRqF2A6QP1Ytf6SjvgWELw.png" /></figure><p>After clicking Mint, we can see that the transaction was successfully issued. At this point, although we have successfully minted the NFT, we still need to add a list to show our NFT.</p><h4>Display of NFT lists</h4><p>Add a list to show that the transfer function containing NFTs can send the corresponding NFTs to other addresses.</p><pre>import React, { useState } from &quot;react&quot;;<br>import { Button, Card, List } from &quot;antd&quot;;<br>import { useContractReader } from &quot;eth-hooks&quot;;<br>import { Address, AddressInput} from &quot;../components&quot;;<br><br>function Home({ <br>  isSigner,<br>  loadWeb3Modal,<br>  yourCollectibles,<br>  address,<br>  blockExplorer,<br>  mainnetProvider,<br>  tx,<br>  readContracts,<br>  writeContracts,<br>}) {<br>  const [transferToAddresses, setTransferToAddresses] = useState({});<br><br>  return (<br>    &lt;div&gt;<br>      {/* Mint botton*/}<br>   ...<br>   {/* list*/}<br>      &lt;div style={{ width: 820, margin: &quot;auto&quot;, paddingBottom: 256 }}&gt;<br>        &lt;List<br>          bordered<br>          dataSource={yourCollectibles}<br>          renderItem={item =&gt; {<br>            const id = item.id.toNumber();<br>            console.log(&quot;IMAGE&quot;,item.image)<br>            return (<br>              &lt;List.Item key={id + &quot;_&quot; + item.uri + &quot;_&quot; + item.owner}&gt;<br>                &lt;Card<br>                  title={<br>                    &lt;div&gt;<br>                      &lt;span style={{ fontSize: 18, marginRight: 8 }}&gt;{item.name}&lt;/span&gt;<br>                    &lt;/div&gt;<br>                  }<br>                &gt;<br>                  &lt;a href={&quot;https://opensea.io/assets/&quot;+(readContracts &amp;&amp; readContracts.YourCollectible &amp;&amp; readContracts.YourCollectible.address)+&quot;/&quot;+item.id} target=&quot;_blank&quot;&gt;<br>                  &lt;img src={item.image} /&gt;<br>                  &lt;/a&gt;<br>                  &lt;div&gt;{item.description}&lt;/div&gt;<br>                &lt;/Card&gt;<br>        {/* NFT transfer*/}<br>                &lt;div&gt;<br>                  owner:{&quot; &quot;}<br>                  &lt;Address<br>                    address={item.owner}<br>                    ensProvider={mainnetProvider}<br>                    blockExplorer={blockExplorer}<br>                    fontSize={16}<br>                  /&gt;<br>                  &lt;AddressInput<br>                    ensProvider={mainnetProvider}<br>                    placeholder=&quot;transfer to address&quot;<br>                    value={transferToAddresses[id]}<br>                    onChange={newValue =&gt; {<br>                      const update = {};<br>                      update[id] = newValue;<br>                      setTransferToAddresses({ ...transferToAddresses, ...update });<br>                    }}<br>                  /&gt;<br>                  &lt;Button<br>                    onClick={() =&gt; {<br>                      console.log(&quot;writeContracts&quot;, writeContracts);<br>                      tx(writeContracts.YourCollectible.transferFrom(address, transferToAddresses[id], id));<br>                    }}<br>                  &gt;<br>                    Transfer<br>                  &lt;/Button&gt;<br>                &lt;/div&gt;<br>              &lt;/List.Item&gt;<br>            );<br>          }}<br>        /&gt;<br>      &lt;/div&gt;<br>      {/* info */}<br>      &lt;div style={{ maxWidth: 820, margin: &quot;auto&quot;, marginTop: 32, paddingBottom: 256 }}&gt;<br>        🛠 built with &lt;a href=&quot;https://github.com/austintgriffith/scaffold-eth&quot; target=&quot;_blank&quot;&gt;🏗 scaffold-eth&lt;/a&gt;<br>        🍴 &lt;a href=&quot;https://github.com/austintgriffith/scaffold-eth&quot; target=&quot;_blank&quot;&gt;Fork this repo&lt;/a&gt; and build a cool SVG NFT!<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Home;</pre><p>The corresponding component use is modified to read</p><pre>...<br>      &lt;Switch&gt;<br>        &lt;Route exact path=&quot;/&quot;&gt;<br>          {/* pass in any web3 props to this Home component. For example, yourLocalBalance */}<br>          &lt;Home<br>            isSigner={userSigner}<br>            loadWeb3Modal={loadWeb3Modal}<br>            yourCollectibles={yourCollectibles}<br>            address={address}<br>            blockExplorer={blockExplorer}<br>            mainnetProvider={mainnetProvider}<br>            tx={tx}<br>            writeContracts={writeContracts}<br>            readContracts={readContracts}<br>          /&gt;<br>       ...</pre><p>The renderings are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEAAdzHcix4_Y4GPo5_RMg.png" /></figure><p>However, we found that when we mint again, the list does not update and remains as it was, so we need to add event listeners to App.jsx that will refresh the list once we cast NFT:</p><pre><em>// </em>Track the current number of NFTs<br>  const balance = useContractReader(readContracts, &quot;YourCollectible&quot;, &quot;balanceOf&quot;, [address]);<br>  console.log(&quot;🤗 balance:&quot;, balance);<br><br>  const yourBalance = balance &amp;&amp; balance.toNumber &amp;&amp; balance.toNumber();<br>  const [yourCollectibles, setYourCollectibles] = useState();<br>  <em>//</em><br>  <em>// 🧠 </em>This effect will update yourCollectibles when the balance changes.<br>  <em>//</em><br>  useEffect(() =&gt; {<br>    const updateYourCollectibles = async () =&gt; {<br>      const collectibleUpdate = [];<br>      for (let tokenIndex = 0; tokenIndex &lt; balance; tokenIndex++) {<br>        try {<br>          console.log(&quot;GEtting token index&quot;, tokenIndex);<br>          const tokenId = await readContracts.YourCollectible.tokenOfOwnerByIndex(address, tokenIndex);<br>          console.log(&quot;tokenId&quot;, tokenId);<br>          const tokenURI = await readContracts.YourCollectible.tokenURI(tokenId);<br>          const jsonManifestString = atob(tokenURI.substring(29))<br>          console.log(&quot;jsonManifestString&quot;, jsonManifestString);<br><br>          try {<br>            const jsonManifest = JSON.parse(jsonManifestString);<br>            console.log(&quot;jsonManifest&quot;, jsonManifest);<br>            collectibleUpdate.push({ id: tokenId, uri: tokenURI, owner: address, ...jsonManifest });<br>          } catch (e) {<br>            console.log(e);<br>          }<br><br>        } catch (e) {<br>          console.log(e);<br>        }<br>      }<br>      setYourCollectibles(collectibleUpdate.reverse());<br>    };<br>    updateYourCollectibles();<br>  }, [address, yourBalance]);</pre><p>At this point, when we Mint again, the list is automatically updated to show the latest cast NFTs.</p><h4>Showing the list of NFT contract interfaces</h4><p>This function is relatively simple and only requires the following changes to the corresponding debug section.</p><pre>&lt;Route exact path=&quot;/debug&quot;&gt;<br>          {<em>/*<br>                🎛 this scaffolding is full of commonly used components<br>                this &lt;Contract/&gt; component will automatically parse your ABI<br>                and give you a form to interact with it locally<br>            */</em>}<br><br>          &lt;Contract<br>            name=&quot;YourCollectible&quot;<br>            price={price}<br>            signer={userSigner}<br>            provider={localProvider}<br>            address={address}<br>            blockExplorer={blockExplorer}<br>            contractConfig={contractConfig}<br>          /&gt;</pre><p>After the update, you can see the functions that can be called from the contract under the Debug Contracts menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cxxa4UXgTR64uNSvx4_OiA.png" /></figure><p>At this point, we have completed a simple NFT casting and presentation DApp.</p><h3>Summing up</h3><p>Through this project, we were able to learn and understand the<br>The basics of NFT contracts and how to display NFT in marketplaces such as Opensea.<br>How the front-end connects to wallets such as MetaMask.<br>How to call contract functions on the front end.</p><h3>Bounty Task</h3><p>1,change rpc using deeprchain rpc,compile &amp; deploy smart contract on deeperchain:</p><p>evm rpc:</p><p><a href="https://mainnet-dev.deeper.network/rpc">https://mainnet-dev.deeper.network/rpc</a></p><p>chainID:</p><p>518</p><p>blockchain Expoler:</p><p>blockscount-dev.deeper.network</p><p>tutorial:</p><p>https://medium.com/@hua.jiang_92778/how-to-use-remix-deploy-deeperchain-evm-smartcontract-a2b0b849abe1</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78970456f03a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeeperChain Credit Module Code Tutorials]]></title>
            <link>https://medium.com/@hua.jiang_92778/deeperchain-credit-module-code-tutorials-56213f3d9dc8?source=rss-78ad8d9c59f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/56213f3d9dc8</guid>
            <dc:creator><![CDATA[Hua Jiang]]></dc:creator>
            <pubDate>Sun, 27 Feb 2022 14:09:59 GMT</pubDate>
            <atom:updated>2022-02-27T14:09:59.326Z</atom:updated>
            <content:encoded><![CDATA[<p>Code link:</p><p><a href="https://github.com/deeper-chain/deeper-chain/blob/master/pallets/credit/src/lib.rs">https://github.com/deeper-chain/deeper-chain/blob/master/pallets/credit</a></p><p>The whole project is formed by adding new features to the module step by step through the substrate template code, for us, we use which module we use, we introduce which module, and then become more and more rich. The overall project is substrate4.0-dev, the specific version is polkadot-0.9.12, we are about to upgrade the version 0.9.16. The overall project of this deep, he will also depend on the project of this deeper frontier. To do the upgrade, in addition to the subtrate project, the deper frontier project must also be upgraded to the corresponding version of polkadot-0.9.16.</p><p>If you are a developer. You will mainly focus on two pieces, one is the runtime, one is the pallet, all of our business code is written in this one. This runtime layer, in fact, is mainly composed of four .rs files, constants.rs, all the configuration information about the chain, mainly two categories, one is the time information, the second category is the currency information, including, for example, DPR, how the initial allocation of a parameter, to 2158 addresses assigned to the two DPR, which is this is the initial one at the time The total of this mining auto mining reward piece is divided 250 million. For this seven verification nodes, how many DPRs they are allocated, this has an initial configuration. For example, the time information, an epoch is four hours, and then one by oneera is a day.</p><p>precompiles.rs, the other is this precompiled, we added a lot of precompiled contracts, this contract is also introduced through this module. This is also mainly used by the frontier side. The pre-compiled contract is what it means, that is, these operations are very cpu-consuming, so we do not put these operations in the smart contract inside the execution, otherwise it will consume high gas fees.</p><p>lib.rs, which is actually if you add a module, then for example, you like tips such a module. Then we will need to go behind this to register him, such as this pallet_tips, and then if you use some of these variables, you will be in this again to define, construct_runtime, most of this configuration is some of the module registration.</p><p><a href="https://github.com/deeper-chain/deeper-chain/tree/master/runtime/src">https://github.com/deeper-chain/deeper-chain/tree/master/runtime/src</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sz8z6TDOwLA-rhFR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9QUc-oaiqueudWy_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zsMHnRdd0KlsGVCw" /></figure><p>However, once you add, that is, any module, you need to go to this, Transaction version this value increases, any change spec-version value becomes larger, but if you say that the constructor_runtime inside the addition of a new module, you have to the transaction_version also have to increase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*IyXgnkJ132IDGoPA" /></figure><p>For developers we generally focus on the development of a pallet. Then I’ll say in this order, this balance module we have now is a basic balance module, it mainly actually implements, for example, this DPR transfer, lock, unlock, these functions are processed in the balance module inside lib.rs, each pallet module, it is composed of this lib.rs, benchmarking.rs, tests.rs, weights.rs. benchmarking.rs, tests.rs, weights.rs, these are actually tests, that basically, will be called by this we call benchmark, we call script, and then our benchmark standard macro will run, this script will run after the results will be written to this weights.rs inside. Cargo.toml is a dependency added to the project data description file specific to cargo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*mmO3tjG_9NpF3GK1" /></figure><p><a href="https://github.com/deeper-chain/deeper-chain/tree/master/pallets/credit">https://github.com/deeper-chain/deeper-chain/tree/master/pallets/credit</a></p><p>Then there is this credit module. At the moment it means that for, overall we go through the code of a module, what we recommend is first, you need to look at the pallet storage.</p><p><a href="https://github.com/deeper-chain/deeper-chain/blob/master/pallets/credit/src/lib.rs">https://github.com/deeper-chain/deeper-chain/blob/master/pallets/credit/src/lib.rs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_tHQ1MkPNP1T3ZuO" /></figure><p>Because this represents some of the data that you can read out on the chain through the chainstate, so we read we go to look at a module, we will look at this first, how many pallet storage there are in this.</p><p>users’ credit score books</p><pre>#[pallet::storage]<br>    #[pallet::getter(fn user_credit)]<br>    pub type UserCredit&lt;T: Config&gt; =<br>        StorageMap&lt;_, Blake2_128Concat, T::AccountId, CreditData, OptionQuery&gt;;</pre><p>the user’s credit score history</p><pre>#[pallet::storage]<br>    #[pallet::getter(fn user_credit_history)]<br>    pub type UserCreditHistory&lt;T: Config&gt; =<br>        StorageMap&lt;_, Blake2_128Concat, T::AccountId, Vec&lt;(EraIndex, CreditData)&gt;, ValueQuery&gt;;</pre><p>There are also some of the settings for this activity</p><pre>#[pallet::storage]<br>    #[pallet::getter(fn credit_settings)]<br>    pub type CreditSettings&lt;T: Config&gt; = StorageDoubleMap&lt;<br>        _,<br>        Identity,<br>        CampaignId,<br>        Identity,<br>        CreditLevel,<br>        CreditSetting&lt;BalanceOf&lt;T&gt;&gt;,<br>        ValueQuery,<br>    &gt;;</pre><p>This daily poc of a reward, he is actually a double key, corresponding to our activity ID, plus our this credit rating, and then will give this, give this gain. What is written here is a look-up table method, that is, these values will be fixed in the chain first, and then we no longer need to do the operation every time when calculating the earnings.</p><pre>/// (daily_base_poc_reward, daily_poc_reward_with_bonus)<br>    #[pallet::storage]<br>    #[pallet::getter(fn daily_poc_reward)]<br>    pub type DailyPocReward&lt;T: Config&gt; = StorageDoubleMap&lt;<br>        _,<br>        Identity,<br>        CampaignId,<br>        Identity,<br>        CreditLevel,<br>        (BalanceOf&lt;T&gt;, BalanceOf&lt;T&gt;),<br>        ValueQuery,<br>    &gt;;</pre><p>The time of the last credit update is displayed in era as a number of days, it does not show a particular block.</p><pre>#[pallet::storage]<br>    #[pallet::getter(fn last_credit_update)]<br>    pub type LastCreditUpdate&lt;T: Config&gt; =<br>        StorageMap&lt;_, Blake2_128Concat, T::AccountId, EraIndex, OptionQuery&gt;;</pre><p>Timestamp of the latest credit update, a structure of this storage map, which is an account corresponding to what is the last updated credit score.</p><pre>#[pallet::storage]<br>    #[pallet::getter(fn last_credit_update_timestamp)]<br>    pub type LastCreditUpdateTimestamp&lt;T: Config&gt; =<br>        StorageMap&lt;_, Blake2_128Concat, T::AccountId, u64, OptionQuery&gt;;</pre><p>Then we can look at things like these structs, like the enumeration we will also look at this credit rating and which elements are contained inside each of these structs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FSZ5D6_LBwbeQPGT" /></figure><pre>/// settings for a specific campaign_id and credit level<br>#[derive(Decode, Encode, Default, Clone, Debug, PartialEq, Eq, TypeInfo)]<br>#[cfg_attr(feature = &quot;std&quot;, derive(Serialize, Deserialize))]<br>pub struct CreditSetting&lt;Balance&gt; {<br>    pub campaign_id: CampaignId,<br>    pub credit_level: CreditLevel,<br>    pub staking_balance: Balance,<br>    pub base_apy: Percent,<br>    pub bonus_apy: Percent,<br>    pub max_rank_with_bonus: u32, // max rank which can get bonus in the credit_level<br>    pub tax_rate: Percent,<br>    pub max_referees_with_rewards: u8,<br>    pub reward_per_referee: Balance,<br>}</pre><p>The activity credit rating, Staking balance is that is the pledge of this balance. then there is the prime rate of this interest rate bonus rate, and then this we call ranking, that is, the top of this ranking will have additional rewards, and there is the tax.</p><pre>#[derive(Decode, Encode, Default, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, TypeInfo)]<br>#[cfg_attr(feature = &quot;std&quot;, derive(Serialize, Deserialize))]<br>pub struct CreditData {<br>    pub campaign_id: CampaignId,<br>    pub credit: u64,<br>    pub initial_credit_level: CreditLevel,<br>    pub rank_in_initial_credit_level: u32,<br>    pub number_of_referees: u8,<br>    pub current_credit_level: CreditLevel,<br>    pub reward_eras: EraIndex, // reward eras since device gets online<br>}</pre><p>This credit data, credit data is actually mainly, the first is the ID of the activity, the credit score, the initialized credit rating, and then the initialized ranking of the credit rating. The current credit rating, the reward ofera, this value we currently write is 270, that is, nine months.</p><p>After focusing on this this data structure and that storage, I usually look at the external interfaces, such as which external call functions are available. These functions can be called by other modules.</p><pre>pub trait CreditInterface&lt;AccountId, Balance&gt; {<br>    fn get_credit_score(account_id: &amp;AccountId) -&gt; Option&lt;u64&gt;;<br>    fn pass_threshold(account_id: &amp;AccountId) -&gt; bool;<br>    fn slash_credit(account_id: &amp;AccountId) -&gt; Weight;<br>    fn get_credit_level(credit_score: u64) -&gt; CreditLevel;<br>    fn get_reward(<br>        account_id: &amp;AccountId,<br>        from: EraIndex,<br>        to: EraIndex,<br>    ) -&gt; (Option&lt;(Balance, Balance)&gt;, Weight);<br>    fn get_top_referee_reward(account_id: &amp;AccountId) -&gt; (Balance, Weight);<br>    fn update_credit(micropayment: (AccountId, Balance));<br>    fn update_credit_by_traffic(server: AccountId);<br>    fn get_current_era() -&gt; EraIndex;<br>    fn update_credit_by_tip(who: AccountId, add_credit: u64);<br>    fn init_delegator_history(account_id: &amp;AccountId, era: u32) -&gt; bool;<br>}</pre><p>Then we will look at some things inside this Config, pallet this module inside which some type, will use event. then like we have a this here, Blocked for error, actually it is a block number type, and then this this this is his a type definition currency, that is You involve money, CreditCapTwoEras is u8 type, there is a get, which means that in the runtime, it will have the default value. These syntaxes are substrate syntaxes, he is not the standard syntax.</p><pre>#[pallet::config]<br>    pub trait Config: frame_system::Config {<br>        /// Because this pallet emits events, it depends on the runtime&#39;s definition of an event.<br>        type Event: From&lt;Event&lt;Self&gt;&gt; + IsType&lt;&lt;Self as frame_system::Config&gt;::Event&gt;;<br>        /// Number of blocks per era.<br>        type BlocksPerEra: Get&lt;&lt;Self as frame_system::Config&gt;::BlockNumber&gt;;<br>        /// Currency<br>        type Currency: Currency&lt;Self::AccountId&gt;;<br>        /// Credit cap every two eras<br>        type CreditCapTwoEras: Get&lt;u8&gt;;<br>        /// credit attenuation step<br>        type CreditAttenuationStep: Get&lt;u64&gt;;<br>        /// Minimum credit to delegate<br>        type MinCreditToDelegate: Get&lt;u64&gt;;<br>        /// mircropayment to credit factor:<br>        type MicropaymentToCreditFactor: Get&lt;u128&gt;;<br>        /// NodeInterface of deeper-node pallet<br>        type NodeInterface: NodeInterface&lt;Self::AccountId, Self::BlockNumber&gt;;<br>        /// Weight information for extrinsics in this pallet.<br>        type WeightInfo: WeightInfo;<br>        type UnixTime: UnixTime;<br>        type SecsPerBlock: Get&lt;u32&gt;;<br>        type DPRPerCreditBurned: Get&lt;BalanceOf&lt;Self&gt;&gt;;<br>        type BurnedTo: OnUnbalanced&lt;NegativeImbalanceOf&lt;Self&gt;&gt;;<br>    }</pre><p>For example, you need to introduce other modules, is the external interface, for example, like we now see this above the trait, this is a credit module external interface, that like us here, referenced this of the deepernode this of an external interface, we need to go to do so an introduction, if you this interface inside the introduction of other this. If you have introduced other interfaces inside this interface. Type, for example, like this account, block number, then you need to write this out inside.</p><pre>type NodeInterface: NodeInterface&lt;Self::AccountId, Self::BlockNumber&gt;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vrCjADqFj7JYsmS8" /></figure><p>Then all these things are nothing this balance, that is to say it is the type used before the calculation, all modules will basically use, is a fixed writing method.</p><pre>pub type BalanceOf&lt;T&gt; =<br>        &lt;&lt;T as Config&gt;::Currency as Currency&lt;&lt;T as frame_system::Config&gt;::AccountId&gt;&gt;::Balance;</pre><p>Then we can look at his events again, that is, what events it will send to the outside, that is, what events it will send to the outside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*27GPziQAU6Ndvc3Q" /></figure><p>The most critical, we will need to go into a pallet_call, which defines all the callable functions, that is, in this, he is not all functions. You can go through extrinsive on our block browser page, and then go, and be able to access is in this can be able to be able to access, is all of the measurable functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hWTpzJ_zcxUN4jF2" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fbs3l1rmREdR5C6N" /></figure><p>We have these two functions what does this mean? It’s the first one is our update credit, credit activity is the equivalent of a new activity that we can go and insert, which may have a different power law. Different this gain, and then the bottom of this, is actually a function that we use to go to the user to initialize the credit book used, it is called with root, this follow-up, it will be taken over by the parliamentary module to parliament, but this piece of this design, is that we can go to discuss, why, because after the gradual removal of our sudo stage, we want to do more decentralized and community Governance, so that how to go to the user to create a credit ledger, it is possible to remove this root, this credit ledger will be created by the user himself.</p><pre>// Dispatchable functions must be annotated with a weight and must return a DispatchResult.<br>    #[pallet::call]<br>    impl&lt;T: Config&gt; Pallet&lt;T&gt; {<br>        /// This operation requires sudo now and it will be decentralized in future<br>        #[pallet::weight(&lt;T as pallet::Config&gt;::WeightInfo::update_credit_setting())]<br>        pub fn update_credit_setting(<br>            origin: OriginFor&lt;T&gt;,<br>            credit_setting: CreditSetting&lt;BalanceOf&lt;T&gt;&gt;,<br>        ) -&gt; DispatchResultWithPostInfo {<br>            ensure_root(origin)?; // requires sudo<br>            Self::_update_credit_setting(credit_setting.clone());<br>            Self::deposit_event(Event::CreditSettingUpdated(credit_setting));<br>            Ok(().into())<br>        }<br>        #[pallet::weight(&lt;T as pallet::Config&gt;::WeightInfo::force_modify_credit_history())]<br>        pub fn force_modify_credit_history(<br>            origin: OriginFor&lt;T&gt;,<br>            account_id: T::AccountId,<br>            expected_era: EraIndex,<br>        ) -&gt; DispatchResultWithPostInfo {<br>            ensure_root(origin)?; // requires sudo<br>            if UserCreditHistory::&lt;T&gt;::contains_key(&amp;account_id) {<br>                let is_success = UserCreditHistory::&lt;T&gt;::mutate(&amp;account_id, |history| {<br>                    if history.len() &gt; 0 {<br>                        for i in 0..history.len() {<br>                            if (i + 1 &lt; history.len()<br>                                &amp;&amp; expected_era &gt;= history[i].0<br>                                &amp;&amp; expected_era &lt; history[i + 1].0)<br>                                || (i + 1 == history.len() &amp;&amp; expected_era &gt;= history[i].0)<br>                            {<br>                                // the first i records were creted before delegate, should be removed<br>                                for _j in 0..i {<br>                                    history.remove(0);<br>                                }<br>                                history[0].0 = expected_era;<br>                                return true;<br>                            }<br>                        }<br>                    }<br>                    false<br>                });<br>                if is_success {<br>                    Self::deposit_event(Event::CreditHistoryUpdateSuccess(<br>                        account_id,<br>                        expected_era,<br>                    ));<br>                    return Ok(().into());<br>                }<br>                Self::deposit_event(Event::CreditHistoryUpdateFailed(account_id, expected_era));<br>                return Err(Error::&lt;T&gt;::BadEraOrHistory)?;<br>            }<br>            Self::deposit_event(Event::CreditHistoryUpdateFailed(account_id, expected_era));<br>            Err(Error::&lt;T&gt;::AccountNotFound)?<br>        }</pre><p>We actually have a part of the function belongs to the internal function, these functions it is not accessed externally, his main purpose is to serve this external call function, why? Because we do not want to write too much complex logic inside the external call function, but in the form of this function call, if you need to do any further calculations or storage, these things will be given to the modular, that is, we separate the live, the main external call function, or a call to other functions of a function and a basic logic.</p><p>If your device is offline, then we will make a judgment, if your more than three days you are offline, you will be deducted a credit score, this logic is in this function.</p><pre>impl&lt;T: Config&gt; Pallet&lt;T&gt; {<br>        pub fn slash_offline_device_credit(account_id: &amp;T::AccountId) -&gt; Weight {<br>            let mut weight = T::DbWeight::get().reads_writes(1, 0);<br>            let eras = T::NodeInterface::get_eras_offline(&amp;account_id);<br>            if eras &gt; 0 &amp;&amp; eras % 3 == 0 {<br>                // slash one credit for being offline every 3 eras<br>                weight = weight.saturating_add(Self::slash_credit(&amp;account_id));<br>            }<br>            weight<br>        }</pre><p>All the logic to update the credit score is inside this function.</p><pre>/// inner: update credit score<br>        fn _update_credit(account_id: &amp;T::AccountId, score: u64) -&gt; bool {<br>            if UserCredit::&lt;T&gt;::contains_key(account_id) {<br>                UserCredit::&lt;T&gt;::mutate(account_id, |v| match v {<br>                    Some(credit_data) =&gt; {<br>                        credit_data.credit = score;<br>                        credit_data.current_credit_level = Self::get_credit_level(score);<br>                    }<br>                    _ =&gt; (),<br>                });<br>                Self::deposit_event(Event::CreditUpdateSuccess((*account_id).clone(), score));<br>                true<br>            } else {<br>                Self::deposit_event(Event::CreditUpdateFailed((*account_id).clone(), score));<br>                false<br>            }<br>        }</pre><p>Updating the credit score history is inside this function.</p><pre>pub fn update_credit_history(account_id: &amp;T::AccountId, current_era: EraIndex) -&gt; Weight {<br>            let user_credit_data = Self::user_credit(&amp;account_id).unwrap();<br>            let mut weight = T::DbWeight::get().reads_writes(1, 0);<br>            let mut user_credit_history = Self::user_credit_history(&amp;account_id);<br>            weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));<br>            if !user_credit_history.is_empty() {<br>                // update credit history only if it&#39;s not empty<br>                let last_index = user_credit_history.len() - 1;<br>                if user_credit_history[last_index].0 == current_era {<br>                    user_credit_history[last_index] = (current_era, user_credit_data.clone());<br>                } else {<br>                    user_credit_history.push((current_era, user_credit_data));<br>                }<br>                UserCreditHistory::&lt;T&gt;::insert(&amp;account_id, user_credit_history);<br>                weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));<br>            }<br>            weight<br>        }</pre><p>The initialization of the credit score history is in this function</p><pre>fn init_credit_history(<br>            account_id: &amp;T::AccountId,<br>            credit_data: CreditData,<br>            era: u32,<br>        ) -&gt; Weight {<br>            UserCreditHistory::&lt;T&gt;::insert(account_id, vec![(era, credit_data)]);<br>            T::DbWeight::get().reads_writes(0, 1)<br>        }</pre><p>This is to get the error corresponding to the user’s power on, for example, the user’s power on the tenth day can be obtained.</p><pre>fn get_onboard_era(account_id: &amp;T::AccountId) -&gt; Option&lt;EraIndex&gt; {<br>            match T::NodeInterface::get_onboard_time(account_id) {<br>                Some(block_number) =&gt; Some(Self::block_to_era(block_number)),<br>                None =&gt; None,<br>            }<br>        }</pre><p>It is used to calculate the user from from from anera. is from to this one, this one phase inside, it’s this, we call each point, it corresponds to the credit score into a time slice, is a piece of a slice to do a slice, he is to assist to calculate our revenue with this.</p><pre>fn get_credit_map(<br>            credit_history: Vec&lt;(EraIndex, CreditData)&gt;,<br>            from: EraIndex,<br>            to: EraIndex,<br>        ) -&gt; BTreeMap&lt;CreditData, u16&gt; {<br>            let mut credit_map = BTreeMap::&lt;CreditData, u16&gt;::new();<br>            let mut i = 0;<br>            for era in from..to + 1 {<br>                while i &lt; credit_history.len() {<br>                    if credit_history[i].0 &lt; era {<br>                        i += 1;<br>                    } else {<br>                        break;<br>                    }<br>                }<br>                // either credit_history[i].0 &gt;= era or i == credit_history.len()<br>                if credit_history[0].0 &gt; era {<br>                    // if the first historical credit data is after the era paid for,<br>                    // then the device came onboard after the era paid for.<br>                    // we simply ignore the era paid for and continue to the next era<br>                    continue;<br>                } else {<br>                    // we get the credit data at the era or the closed one before the era<br>                    let credit_data = if i &lt; credit_history.len() &amp;&amp; credit_history[i].0 == era {<br>                        credit_history[i].1.clone()<br>                    } else {<br>                        credit_history[i - 1].1.clone()<br>                    };<br>                    if Self::_pass_threshold(&amp;credit_data) {<br>                        if credit_map.contains_key(&amp;credit_data) {<br>                            credit_map.insert(<br>                                credit_data.clone(),<br>                                credit_map.get(&amp;credit_data).unwrap() + 1,<br>                            );<br>                        } else {<br>                            credit_map.insert(credit_data, 1);<br>                        }<br>                    }<br>                }<br>            }<br>            credit_map<br>        }</pre><p>It is what we use to judge the threshold, which means that only if your credit score reaches 100 or more, then we will give you is, go to this step of the reward.</p><pre>fn _pass_threshold(credit_data: &amp;CreditData) -&gt; bool {<br>            credit_data.credit &gt;= T::MinCreditToDelegate::get()<br>        }</pre><p>This block to Era actually means that the current block is converted into the corresponding era, which is actually our current era, which is approximately equal to one day.</p><pre>fn block_to_era(block_number: T::BlockNumber) -&gt; EraIndex {<br>            TryInto::&lt;EraIndex&gt;::try_into(block_number / T::BlocksPerEra::get())<br>                .ok()<br>                .unwrap()<br>        }</pre><p>What do we check for this credit data? On the main is to check, your input into this credit data, is not compliant that is, the first check your credit rating right, the second check this number of reference, whether it is to this is less than or equal to, if not that will be reported invalid.</p><pre>/// credit data check<br>        fn check_credit_data(data: &amp;CreditData) -&gt; Result&lt;(), DispatchErrorWithPostInfo&gt; {<br>            ensure!(<br>                Self::get_credit_level(data.credit) == data.current_credit_level,<br>                Error::&lt;T&gt;::InvalidCreditData<br>            );<br>            let credit_setting = Self::credit_settings(data.campaign_id, data.initial_credit_level);<br>            ensure!(<br>                data.number_of_referees &lt;= credit_setting.max_referees_with_rewards,<br>                Error::&lt;T&gt;::InvalidCreditData<br>            );<br>            Ok(())<br>        }</pre><p>This credit activity of our credit activity</p><pre>fn _update_credit_setting(credit_setting: CreditSetting&lt;BalanceOf&lt;T&gt;&gt;) {<br>            let daily_referee_reward = credit_setting<br>                .reward_per_referee<br>                .saturating_mul(credit_setting.max_referees_with_rewards.into());<br>            // poc reward<br>            let base_total_reward = Perbill::from_rational(270u32, 365u32)<br>                * (credit_setting.base_apy * credit_setting.staking_balance);<br>            let base_daily_poc_reward = (Perbill::from_rational(1u32, 270u32) * base_total_reward)<br>                .saturating_sub(daily_referee_reward);<br>            let base_total_reward_with_bonus = Perbill::from_rational(270u32, 365u32)<br>                * (credit_setting<br>                    .base_apy<br>                    .saturating_add(credit_setting.bonus_apy)<br>                    * credit_setting.staking_balance);<br>            let base_daily_poc_reward_with_bonus = (Perbill::from_rational(1u32, 270u32)<br>                * base_total_reward_with_bonus)<br>                .saturating_sub(daily_referee_reward);<br>            DailyPocReward::&lt;T&gt;::insert(<br>                credit_setting.campaign_id,<br>                credit_setting.credit_level.clone(),<br>                (base_daily_poc_reward, base_daily_poc_reward_with_bonus),<br>            );<br>            CreditSettings::&lt;T&gt;::insert(<br>                credit_setting.campaign_id,<br>                credit_setting.credit_level.clone(),<br>                credit_setting,<br>            );<br>        }</pre><p>We have a logic called share traffic two consecutive days before giving a credit score, so the function of this function is to check if you that device submits this, that is, a request to increase the credit score when you meet this demand for two days.</p><pre>/// check the interval between two credit update as long enouth<br>        /// return (u64,bool):<br>        /// the first means the inteval of eras ;<br>        /// the second means if use era for check (tobe deprecated)<br>        fn check_update_credit_interval(<br>            server_id: &amp;T::AccountId,<br>            current_era: EraIndex,<br>            onboard_era: EraIndex,<br>            now_as_secs: u64,<br>        ) -&gt; (u64, bool) {<br>            let diffs;<br>            let mut era_used = false;<br>            if let Some(pre_update_timestamp) = Self::last_credit_update_timestamp(server_id) {<br>                let era_block_count = TryInto::&lt;u64&gt;::try_into(T::BlocksPerEra::get())<br>                    .ok()<br>                    .unwrap();<br>                let secs_per_block = T::SecsPerBlock::get() as u64;<br>                diffs = now_as_secs.saturating_sub(pre_update_timestamp)<br>                    / era_block_count.saturating_mul(secs_per_block);<br>            } else if let Some(last_credit_update_era) = Self::last_credit_update(&amp;server_id) {<br>                diffs = current_era.saturating_sub(last_credit_update_era) as u64;<br>                era_used = true;<br>            } else {<br>                // if this is the first update, we use onboard era as the last update era<br>                diffs = current_era.saturating_sub(onboard_era) as u64;<br>            }<br>            (diffs, era_used)<br>        }<br>    }</pre><p>This external call to the function has a header like this</p><pre>impl&lt;T: Config&gt; CreditInterface&lt;T::AccountId, BalanceOf&lt;T&gt;&gt; for Pallet&lt;T&gt; {</pre><p>The functions without headers are internal calls</p><pre>impl&lt;T: Config&gt; Pallet&lt;T&gt; {</pre><p>Credit score deduction</p><pre>fn slash_credit(account_id: &amp;T::AccountId) -&gt; Weight {<br>            let mut weight = T::DbWeight::get().reads_writes(1, 0);<br>            if UserCredit::&lt;T&gt;::contains_key(account_id) {<br>                let penalty = T::CreditAttenuationStep::get();<br>                UserCredit::&lt;T&gt;::mutate(account_id, |v| match v {<br>                    Some(credit_data) =&gt; {<br>                        credit_data.credit = credit_data.credit.saturating_sub(penalty);<br>                        credit_data.current_credit_level =<br>                            Self::get_credit_level(credit_data.credit);<br>                        Self::deposit_event(Event::CreditScoreSlashed(<br>                            (*account_id).clone(),<br>                            (*credit_data).clone().credit,<br>                        ));<br>                    }<br>                    _ =&gt; (),<br>                });<br>                weight = weight.saturating_add(T::DbWeight::get().reads_writes(0, 1));<br>                weight = weight.saturating_add(Self::update_credit_history(<br>                    account_id,<br>                    Self::get_current_era(),<br>                ));<br>            }<br>            weight<br>        }</pre><p>It is a function that is external and it is mainly called by our pledge module. The reason for this is that it may correspond to different rewards for different credit levels, because the higher the credit level, the higher the reward will be.</p><pre>fn get_reward(<br>            account_id: &amp;T::AccountId,<br>            from: EraIndex,<br>            to: EraIndex,<br>        ) -&gt; (Option&lt;(BalanceOf&lt;T&gt;, BalanceOf&lt;T&gt;)&gt;, Weight) {<br>            // silently ignore invalid inputs<br>            let cur_era = Self::get_current_era();<br>            if from &gt; to || to &gt;= cur_era {<br>                Self::deposit_event(Event::GetRewardResult(account_id.clone(), from, to, 1));<br>                return (None, Weight::zero());<br>            }<br>            let optional_credit_data = Self::user_credit(account_id); // 1 db read<br>            let mut weight = T::DbWeight::get().reads_writes(1, 0);<br>            if optional_credit_data.is_none() {<br>                Self::deposit_event(Event::GetRewardResult(account_id.clone(), from, to, 2));<br>                return (None, weight);<br>            }<br>            let credit_data = optional_credit_data.unwrap();<br>            if credit_data.reward_eras == 0 {<br>                Self::deposit_event(Event::GetRewardResult(account_id.clone(), from, to, 3));<br>                return (None, weight);<br>            }<br>            weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));<br>            if Self::user_credit_history(account_id).is_empty() {<br>                weight = weight.saturating_add(Self::init_credit_history(<br>                    account_id,<br>                    credit_data.clone(),<br>                    cur_era,<br>                ));<br>            }<br>            weight = weight.saturating_add(Self::slash_offline_device_credit(account_id));<br>            let credit_history = Self::user_credit_history(account_id);<br>            weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));<br>            if credit_history.is_empty() {<br>                Self::deposit_event(Event::GetRewardResult(account_id.clone(), from, to, 4));<br>                return (None, weight);<br>            }<br>            let delegate_era = credit_history[0].0;<br>            let expiry_era = delegate_era + credit_data.reward_eras - 1;<br>            if from &gt; expiry_era {<br>                Self::deposit_event(Event::GetRewardResult(account_id.clone(), from, to, 5));<br>                return (None, weight);<br>            }<br>            let credit_map = Self::get_credit_map(credit_history, from, cmp::min(to, expiry_era));<br>            if credit_map.is_empty() {<br>                Self::deposit_event(Event::GetRewardResult(account_id.clone(), from, to, 6));<br>                return (None, weight);<br>            }<br>            let mut referee_reward = BalanceOf::&lt;T&gt;::zero();<br>            let mut poc_reward = BalanceOf::&lt;T&gt;::zero();<br>            for (credit_data, num_of_eras) in credit_map {<br>                let initial_credit_level = credit_data.initial_credit_level;<br>                let credit_setting =<br>                    Self::credit_settings(credit_data.campaign_id, initial_credit_level.clone());<br>                weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));<br>                // referral reward<br>                let number_of_referees =<br>                    if credit_data.number_of_referees &lt;= credit_setting.max_referees_with_rewards {<br>                        credit_data.number_of_referees<br>                    } else {<br>                        credit_setting.max_referees_with_rewards<br>                    };<br>                let daily_referee_reward = credit_setting<br>                    .reward_per_referee<br>                    .saturating_mul(number_of_referees.into());<br>                // poc reward<br>                let current_credit_level = credit_data.current_credit_level;<br>                let (base_daily_poc_reward, daily_poc_reward_with_bonus) =<br>                    Self::daily_poc_reward(credit_data.campaign_id, current_credit_level.clone());<br>                weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));<br>                let daily_poc_reward = if current_credit_level == initial_credit_level {<br>                    // level unchanged<br>                    if credit_data.rank_in_initial_credit_level<br>                        &lt;= credit_setting.max_rank_with_bonus<br>                    {<br>                        daily_poc_reward_with_bonus<br>                    } else {<br>                        base_daily_poc_reward<br>                    }<br>                } else {<br>                    // level changed<br>                    let (initial_base_daily_poc_reward, initial_daily_poc_reward_with_bonus) =<br>                        Self::daily_poc_reward(credit_data.campaign_id, initial_credit_level);<br>                    weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0));<br>                    if credit_data.rank_in_initial_credit_level<br>                        &lt;= credit_setting.max_rank_with_bonus<br>                    {<br>                        base_daily_poc_reward<br>                            + (initial_daily_poc_reward_with_bonus - initial_base_daily_poc_reward)<br>                    } else {<br>                        base_daily_poc_reward<br>                    }<br>                };<br>                referee_reward = referee_reward<br>                    .saturating_add(daily_referee_reward.saturating_mul(num_of_eras.into()));<br>                poc_reward =<br>                    poc_reward.saturating_add(daily_poc_reward.saturating_mul(num_of_eras.into()));<br>            }<br>            (Some((referee_reward, poc_reward)), weight)<br>        }</pre><p>Update your credit score in the form of traffic, whether you share traffic or consume traffic, go through this this portal to update, it needs to be updated once every two days, so that there is a portal.</p><pre>/// update credit score by traffic<br>        fn update_credit_by_traffic(server_id: T::AccountId) {<br>            let onboard_era = Self::get_onboard_era(&amp;server_id);<br>            if onboard_era.is_none() {<br>                // credit is not updated if the device is never online<br>                log!(<br>                    info,<br>                    &quot;update_credit_by_traffic account : {:?}, never online&quot;,<br>                    server_id<br>                );<br>                return;<br>            }<br>            let current_era = Self::get_current_era();<br>            let now_as_secs = T::UnixTime::now().as_secs();<br>            let (time_eras, era_used) = Self::check_update_credit_interval(<br>                &amp;server_id,<br>                current_era,<br>                onboard_era.unwrap(),<br>                now_as_secs,<br>            );<br>            if time_eras &gt;= 2 {<br>                let cap: u64 = T::CreditCapTwoEras::get() as u64;<br>                let new_credit = Self::get_credit_score(&amp;server_id)<br>                    .unwrap_or(0)<br>                    .saturating_add(cap);<br>                if Self::_update_credit(&amp;server_id, new_credit) {<br>                    LastCreditUpdateTimestamp::&lt;T&gt;::insert(&amp;server_id, now_as_secs);<br>                    Self::update_credit_history(&amp;server_id, current_era);<br>                    Self::deposit_event(Event::CreditDataAddedByTraffic(<br>                        server_id.clone(),<br>                        new_credit,<br>                    ));<br>                } else {<br>                    log!(<br>                        error,<br>                        &quot;failed to update credit {} for server_id: {:?}&quot;,<br>                        new_credit,<br>                        server_id<br>                    );<br>                }<br>                // clear old<br>                if era_used {<br>                    LastCreditUpdate::&lt;T&gt;::remove(server_id);<br>                }<br>            }<br>        }</pre><p>Update your credit score by tipping.</p><pre>fn update_credit_by_tip(who: T::AccountId, add_credit: u64) {<br>            let onboard_era = Self::get_onboard_era(&amp;who);<br>            if onboard_era.is_none() {<br>                // credit is not updated if the device is never online<br>                log!(<br>                    info,<br>                    &quot;update_credit_by_tip account : {:?}, never online&quot;,<br>                    who<br>                );<br>                return;<br>            }<br>            let current_era = Self::get_current_era();<br>            let new_credit = Self::get_credit_score(&amp;who)<br>                .unwrap_or(0)<br>                .saturating_add(add_credit);<br>            if Self::_update_credit(&amp;who, new_credit) {<br>                Self::update_credit_history(&amp;who, current_era);<br>                Self::deposit_event(Event::CreditDataAddedByTip(who.clone(), new_credit));<br>            } else {<br>                log!(<br>                    error,<br>                    &quot;failed to update credit {} for who: {:?}&quot;,<br>                    new_credit,<br>                    who<br>                );<br>            }<br>        }</pre><p>An initialized delegate one, meaning that the credit score’s will be created for you when you initially pledge. Our credit score history is only initialized when you pledge. This function is used to initialize the credit score only when you pledge.</p><pre>fn init_delegator_history(account_id: &amp;T::AccountId, era: u32) -&gt; bool {<br>            let credit_data = Self::user_credit(account_id); // 1 db read<br>            if credit_data.is_none() {<br>                log!(<br>                    error,<br>                    &quot;failed to init_delegator_history for  {:?}&quot;,<br>                    account_id<br>                );<br>                return false;<br>            }<br>            Self::init_credit_history(account_id, credit_data.unwrap(), era);<br>            true<br>        }<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56213f3d9dc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Remix deploy DeeperChain Evm SmartContract]]></title>
            <link>https://medium.com/@hua.jiang_92778/how-to-use-remix-deploy-deeperchain-evm-smartcontract-a2b0b849abe1?source=rss-78ad8d9c59f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2b0b849abe1</guid>
            <dc:creator><![CDATA[Hua Jiang]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 13:39:51 GMT</pubDate>
            <atom:updated>2022-02-20T13:48:47.836Z</atom:updated>
            <content:encoded><![CDATA[<h3>Outline</h3><ul><li>1,Bind address in DeeperChain and using deeperscan search pair tx</li><li>2,Download the interactive contract framework MetaMask and <a href="https://polkadot.js.org/extension/">polkadot</a> <a href="https://polkadot.js.org/extension/">extension</a></li><li>3,Interaction with Deeper Chain EVM using MetaMask</li><li>4,Simple smart contract deployment using Remix</li><li>5,Use evm blockscan search transaction</li><li>6,Bounty Task</li></ul><h3><strong>Bind address in DeeperChain and using deeperscan search pair tx</strong></h3><p>Method A:</p><ol><li>Generate an Ethereum address using MetaMask, click Create Account to generate a new address</li><li>Generate a Substrate address using Polkadot{.js}</li><li>Export the private key of the corresponding account to prepare for the binding address</li><li>Download the <a href="https://github.com/deeper-chain/deeper-chain/blob/dev/frontier/scripts/account_utils.js">here</a> script for backup and the web3 library included in the script and the truffle-privatekey-provider library</li><li>Fill in the corresponding comment section of the script, and uncomment it, sub_address should use a non-ss58 encoded address instead of an ss58 encoded address. For example, the address I want to bind is 5GmrzfcmjhaEX1R4yGstPU5hFrZC3jHKB33wUwknQciNG4Z7, then the substrate address I need to fill in should be d054c19be6989d0b5e416bdc8bd67d78365d923b528ade23dc3213eb09f8a705. Other than this, there are no special requirements for other fields.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59ddcdd54e63f9c3fe2eebea7017b8f6/href">https://medium.com/media/59ddcdd54e63f9c3fe2eebea7017b8f6/href</a></iframe><ul><li>const eth_private_key = ‘Your eth account private key’; const eth_address = ‘Your eth account’; const sub_address = ‘Your substrate account’;</li></ul><ol><li>Run the script to generate the corresponding signature, save the signature, and prepare for the binding operation</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuHElNUkV7HtqJ9EwLM6iw.png" /></figure><h3>Bind address</h3><p>1.Open our background management page, take the local panel as an example, select the Developer -&gt; Transaction tab to enter the transaction call page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yppr00X9m7VGn6E8.png" /></figure><ol><li>After entering the transaction call page, you need to configure the following: (1) Change the calling account to your own account (2) Selects evm module (3) Selects the action called pairAccounts</li><li>Then click the submit transaction button below to submit, and see the prompt in the red box below, indicating that the binding is successful.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K_uUfLj6HSaTkW4K.png" /></figure><p>Method B:open the tool on chrome</p><p>http://143.244.163.117:3000/sign.html</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqQ5i5ASEv0YMoa4GOxKSg.png" /></figure><h3>Download the interactive contract framework MetaMask and polkadot extension</h3><p>https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn?hl=en</p><p>https://polkadot.js.org/extension/</p><h3>Deeperscan search pair tx</h3><p>open deeperscan search blockhash:</p><p>0x933da77591db9fed1f69f608a55f03dcc4b737ef0dcfa146f424e3b0213e42c7</p><p>https://dev.deeperscan.io/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqbiw0uJHaFV5yDrIFDpAg.png" /></figure><h3>Interaction with Deeper Chain EVM using MetaMaskv</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*n98c4JGWusal8b7wXNKoJQ.png" /></figure><p>evm rpc:</p><p>https://mainnet-dev.deeper.network/rpc</p><p>chainID:</p><p>518</p><p>blockchain Expoler:</p><p>blockscount-dev.deeper.network</p><h3>Simple contract deployment using Remix</h3><p>remix.ethereum.org</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43216d03060541b52b80c47cac1edfbc/href">https://medium.com/media/43216d03060541b52b80c47cac1edfbc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXxmUgx7iAu5mauxxKMmgQ.png" /></figure><p>Deploy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOfXp7YvxljdqtIULYm-nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42uM-FUzfQw6WIe0Gu4q1w.png" /></figure><p><a href="http://blockscount-dev.deeper.network/tx/0x265bfcf4e5526b0a02b0897ea3f0e433c51cc7f97358f030d25f9d599728ad3e/token-transfers">Transaction 0x265bfcf4e5526b0a02b0897ea3f0e433c51cc7f97358f030d25f9d599728ad3e - Sokol Explorer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b0b849abe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>