slavingia / fweb3.xyz

Home Page:fweb3.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fix background color of diamond NFT

slavingia opened this issue · comments

Our BG color function is:

  function getBackgroundColor(uint256 tokenId) public pure returns (string memory) {
    uint256 rand = random(string(abi.encodePacked(toString(tokenId))));
    bytes32 val = bytes32(rand);
    bytes memory hx = "0123456789ABCDEF";
    bytes memory str = new bytes(51);

    for (uint i = 17; i < 20; i++) {
      str[i*2] = hx[uint(uint8(val[i + 12] >> 4))];
      str[1+i*2] = hx[uint(uint8(val[i + 12] & 0x0f))];
    }

    return string(str);
  }

Currently spitting out:

<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 512 512"><rect width="100%" height="100%" fill="#����������������������������������000001�����������"><polygon style="fill:hsl(6,26%,79%);" points="256,499.47 512,146.167 414.217,12.53 97.784,12.53 0.001,146.167 "/><g><polygon style="fill:hsl(6,26%,82%);" points="97.786,12.53 170.663,146.172 0,146.172"/><polygon style="fill:hsl(6,26%,82%);" points="414.217,12.53 341.327,146.172 255.995,12.53"/><polygon style="fill:hsl(6,26%,82%);" points="341.327,146.172 255.995,499.467 170.663,146.172"/></g><g><polygon style="fill:hsl(6,26%,94%);" points="414.217,12.53 511.99,146.172 341.327,146.172"/><polygon style="fill:hsl(6,26%,94%);" points="255.995,12.53 341.327,146.172 170.663,146.172"/><polygon style="fill:hsl(6,26%,94%);" points="170.663,146.172 255.995,499.467 0,146.172"/></g></svg>
  • Deploy new smart contract and update code

This loop here was not returning a 6 digit hexadecimal, simplified:
`function getBackgroundColor(uint256 tokenId) public view returns (string memory) {
uint256 rand = random(string(abi.encodePacked(toString(tokenId))));
bytes32 val = bytes32(rand);
bytes memory hx = "0123456789ABCDEF";
bytes memory str = new bytes(6);

for (uint i = 0; i < 6; i++) {
  str[i] = hx[uint8(val[i]) & 0xf];
  // str[i*2] = hx[uint(uint8(val[i + 12] >> 4))];
  // str[1+i*2] = hx[uint(uint8(val[i + 12] & 0x0f))];
}
console.log("getbgcolor:");
console.log(string(str));
return string(str);

}`

The function can be changed back to pure from view if you remove the console.log statements that I added.

It looks like my thinking about this was incorrect, the smart contract is fine as is: no further optimizations necessary since tokenURI is pure there is no benefit to using bytes vs strings. Did some tests with hardhat deploying locally and benefits are negligible in contract size as well.

With the fixes to getBackgroundColor() in #52 the NFT contract should be good to go unless a different design for the NFT is decided.