Skip to content

Instantly share code, notes, and snippets.

@fiveoutofnine
Last active February 17, 2023 02:24
Show Gist options
  • Save fiveoutofnine/21bff9b9b8a3ceb8f70d5f2ac8682f31 to your computer and use it in GitHub Desktop.
Save fiveoutofnine/21bff9b9b8a3ceb8f70d5f2ac8682f31 to your computer and use it in GitHub Desktop.
A script to generate and print identicons.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Script } from "forge-std/Script.sol";
import { console } from "forge-std/Test.sol";
import { LibString } from "solmate/utils/LibString.sol";
/// @title Script to generate and print an identicon.
/// @author fiveoutofnine
/// @dev To run the script, run the following commands:
/// ```sh
/// forge install transmissions11/solmate
/// echo "solmate/=lib/solmate/src/" > remappings.txt
/// forge script PrintIdenticon.s.sol:PrintIdenticonScript -vvv
/// ```
contract PrintIdenticonScript is Script {
using LibString for uint256;
/// @notice The seed to generate the identicon based off of.
uint256 constant SEED = 2;
function run() public {
uint256 seed = uint256(keccak256(abi.encodePacked(SEED)));
// Read color from the last 24 bits of the seed.
(uint256 r, uint256 g, uint256 b) = (seed & 0xFF, (seed >> 8) & 0xFF, (seed >> 16) & 0xFF);
// Generate `rgb` color with `r`, `g`, and `b` values.
string memory color =
string.concat("rgb(", r.toString(), ",", g.toString(), ",", b.toString(), ")");
// Generate the fill color to be white/black depending on how bright
// `color` is.
string memory emptyColor = ((r + g + b) >> 1) < 383 ? "white" : "black";
seed >>= 24;
// SVG header.
string memory svg =
'<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.o'
'rg/2000/svg">';
// Generate the identicon.
// `0xEFAE78CF2C70AEAA688E28606DA6584D24502CA2480C2040` is a bitpacked
// representation of the following array:
// ```
// [
// 59, 58, 57, 56,
// 51, 50, 49, 48,
// 43, 42, 41, 40,
// 35, 34, 33, 32,
// 27, 26, 25, 24,
// 19, 18, 17, 16,
// 11, 10, 9, 8,
// 3, 2, 1, 0
// ]
// ```
for (uint256 i = 0xEFAE78CF2C70AEAA688E28606DA6584D24502CA2480C2040; i != 0; i >>= 6) {
(uint256 x, uint256 y) = (i & 7, (i >> 3) & 7);
svg = string.concat(
svg,
'<rect width="32" height="32" x="',
(x << 5).toString(),
'" y="',
(y << 5).toString(),
'" fill="',
(seed & 1) == 0 ? color : emptyColor,
'"/>' '<rect width="32" height="32" x="',
((7 - x) << 5).toString(),
'" y="',
(y << 5).toString(),
'" fill="',
(seed & 1) == 0 ? color : emptyColor,
'"/>'
);
seed >>= 1;
}
// SVG footer.
svg = string.concat(svg, "</svg>");
console.log(svg);
}
}
@fiveoutofnine
Copy link
Author

I recommend copy pasting the output into https://www.svgviewer.dev/svg-to-png to view it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment