Skip to content
Verified contractExactMIT

GifedRendererV1

Address0x8aee98ae83118b35a5995366ff28b444cf1093a9
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,878,381
Creation transaction
0x009f43ec98…f8ecafc519

4 files

Gifed.renderer.v1.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

import "./Colour.sol";
import "./Buffer.sol";
import "./IGifedRenderer.sol";

interface IStorageTools{
  function read(address,uint,uint) external view returns (bytes memory);
}

interface IGifed{
  function checkToken(uint, address, uint8) external returns (bytes8);
}

interface INiftygify{
  function imageURI(uint) external view returns (string memory);
}

contract GifedRendererV1 is IGifedRenderer{

  struct Seed {
    uint cycles;
    uint blockSize;
    uint[2] limits; // the upper and lower block dimensions determined by blocksize
    uint[3] hsv;
    uint[3] colourChanges;
    uint[2] trace;
    uint[2] reverse; // 1 = true
    uint mirror; // quad, vertical, horizontal, inverse-quad
    uint bias; // none, horizontal, vertical, square
    uint highlight; // subdue, full range, mirror, bias
    uint bump; // bump trace data index
    bytes8 gceControlled; // gif speed mutation
    uint svgCycles; // svg cycles mutation. if > 0 => renders svg
    // calculated each cycle
    uint[3] rand;
    bytes10[4] quadIds;
    uint width;
    uint height;
    uint xpos;
    uint ypos;
    uint iter;
    bytes6 lct;
    bytes rectTemplate; // for svg
    bytes imageBlock; // for gif
  }

  address public constant GIFED_ADDRESS = 0x7212604875bf24309263bE240F03d63D3aEBCA38;

  address internal constant TOOLS_ADDRESS = 0x744F25b06DEbc03a909c8CED93Fa121C6c47B773;

  address internal constant IMAGE_DATA_ADDRESS = 0x08487C7228401841F0Ae54bAF63C9260d088B153;

  address internal constant NFTYGIFY_ADDRESS = 0x77a2ae79D314686B2A66a5CBc9F58Ad1f345BBE1;

  // cycle mutator controls the number of svg render cycles
  uint8 internal constant DEFAULT_SVG_CYCLE_MUTATOR = 36;

  mapping(bytes8 => uint8) internal gifSpeedMutators;
  mapping(bytes8 => uint8) internal svgCycleMutators;

  /// @inheritdoc IGifedRenderer
  function gifBytes(bytes8 salt) external view returns(bytes memory) {
    salt = stripSalt(salt);
    IStorageTools tools = IStorageTools(TOOLS_ADDRESS);
    Seed memory seed;
    parseSalt(seed, salt);
    seed.imageBlock = getImageBlock();
    bytes memory seal = genSeal("", salt);
    bytes memory buffer = Buffer.allocate(1789 + seed.cycles * 76 * 4 + seal.length);
    Buffer.appendBytes(buffer, tools.read(IMAGE_DATA_ADDRESS, 1, 1790));
    genBlocks(seed, buffer);
    Buffer.appendBytes(buffer, seal);
    return buffer;
  }

  /// @inheritdoc IGifedRenderer
  function gifURI(bytes8 salt) external view returns (string memory) {
    salt = stripSalt(salt);
    IStorageTools tools = IStorageTools(TOOLS_ADDRESS);
    Seed memory seed;
    parseSalt(seed, salt);
    seed.imageBlock = getImageBlock();
    bytes memory seal = genSeal("", salt);
    uint gifSize = (1789 + seed.cycles * 76 * 4 + seal.length);
    uint bufferSize = (gifSize + 2) / 3 * 4 + 22;
    bytes memory buffer = Buffer.allocate(bufferSize);
    Buffer.appendBytes(buffer, "data:image/gif;base64,");
    Buffer.setPointer(buffer, bufferSize - gifSize);
    Buffer.appendBytes(buffer, tools.read(IMAGE_DATA_ADDRESS, 1, 1790));
    genBlocks(seed, buffer);
    Buffer.appendBytes(buffer, seal);
    Buffer.incode64(buffer, bufferSize - gifSize, 22);
    return string(buffer);
  }

  /**
  * @notice generates an svg string
  * @param salt the salt
  */
  function svgString(bytes8 salt) external view returns (string memory) {
    salt = stripSalt(salt);
    Seed memory seed;
    parseSalt(seed, salt);
    seed.rectTemplate = getRectTemplate();
    /* seed.svgCycles = getSvgCycles(salt); */
    setSvgCycles(seed, salt);
    bytes memory svgStart = genSvgStart(hex'', salt);
    uint svgSize = svgStart.length + seed.svgCycles * 69 * 4 + 6;
    bytes memory buffer = Buffer.allocate(svgSize);
    Buffer.appendBytes(buffer, svgStart);
    genBlocks(seed, buffer);
    Buffer.appendBytes(buffer,'</svg>');
    return string(buffer);
  }

  /// @inheritdoc IGifedRenderer
  function packTokenURI(bytes calldata start, string calldata idString, bytes8 salt)
        external view returns(string memory) {
    IStorageTools tools = IStorageTools(TOOLS_ADDRESS);
    Seed memory seed;
    parseSalt(seed, salt);
    seed.rectTemplate = getRectTemplate();
    seed.imageBlock = getImageBlock();
    /* seed.svgCycles = getSvgCycles(salt); */
    setSvgCycles(seed, salt);
    bytes memory seal = genSeal(idString, salt);
    bytes memory jsonStart = bytes.concat(
            start,
            versionAttributes(seed, salt),
            ',%22image%22:%22data:image/svg+xml;base64,');
    bytes memory svgStart = genSvgStart(bytes(idString), salt);
    uint svgSize = svgStart.length + seed.svgCycles * 69 * 4 + 6;
    uint svg64Size = (svgSize + 2) / 3 * 4;
    uint gifSize = (1789 + seed.cycles * 76 * 4 + seal.length);
    uint gif64size = (gifSize + 2) / 3 * 4;
    // json animation_url(49) + close(6) = 55
    uint bufferSize = jsonStart.length + svg64Size + gif64size + 55;
    bytes memory buffer = Buffer.allocate(bufferSize);
    Buffer.appendBytes(buffer, jsonStart);
    Buffer.setPointer(buffer, bufferSize - svgSize); // reset the buffer pointer
    Buffer.appendBytes(buffer, svgStart);
    genBlocks(seed, buffer);
    Buffer.appendBytes(buffer,'</svg>');
    // base64 svg
    Buffer.incode64(buffer, bufferSize - svgSize, jsonStart.length);
    // animation_url => gif (seed.svgCycles == 0 is the trigger for gif block rendering)
    seed.svgCycles = 0;
    Buffer.appendBytes(buffer, bytes('%22,%22animation_url%22:%22data:image/gif;base64,'));
    // write gif bytes
    Buffer.setPointer(buffer, bufferSize - gifSize);
    Buffer.appendBytes(buffer, tools.read(IMAGE_DATA_ADDRESS, 1, 1790));
    genBlocks(seed, buffer);
    Buffer.appendBytes(buffer, seal);
    // base64 gif
    Buffer.incode64(buffer, bufferSize - gifSize, jsonStart.length + svg64Size + 49);
    Buffer.appendBytes(buffer, bytes('%22%7d')); // json close
    return string(buffer);
  }

  function setSvgCycles(Seed memory seed, bytes8 salt) internal view {
    uint8 mutator = svgCycleMutators[salt];
    mutator = mutator > 0 ? mutator : DEFAULT_SVG_CYCLE_MUTATOR;
    seed.svgCycles = mutator * (seed.cycles - seed.cycles / 8) / 255 + (seed.cycles / 8);
  }

  function genSvgStart(bytes memory idString, bytes8 salt) internal view returns(bytes memory) {
    bool useId = idString.length > 0;
    return bytes.concat(
      '<svg width="1024px" height="1024px" viewBox="0 0 1024 1024" '
      'xmlns="http://www.w3.org/2000/svg">\n'
      ' <title>Gifed ',
      bytes(useId ? '#' : 'v1 '),
      useId ? idString : getHexString(abi.encodePacked(salt)),
      bytes(useId ? ' v1' : ''),
      '</title>\n'
      ' <link xmlns="http://www.w3.org/1999/xhtml" rel="shortcut icon" href="',
      bytes(INiftygify(NFTYGIFY_ADDRESS).imageURI(1)),
      '"/>\n'
      ' <rect width="100%" height="100%" fill="#000000" />\n'
      );
  }

  /// @dev completes the tokenURI json attributes array
  function versionAttributes(Seed memory seed, bytes8 salt) internal view returns(bytes memory) {
    bytes memory gifSpeed = bytes(gifSpeedMutators[salt] == 0
                  ? ''
                  : ',%7b%22trait_type%22:%22mutation%22,%22value%22:%22GIF%20Speed%22%7d'
                  );
    bytes memory svgCycles = bytes(svgCycleMutators[salt] == 0
                  ? ''
                  : ',%7b%22trait_type%22:%22mutation%22,%22value%22:%22SVG%20Cycles%22%7d'
                  );
    return bytes.concat(
                      ',%7b%22trait_type%22:%22trace%22,%22value%22:%22',
                      getTraceName(seed.trace[0]),
                      '%22%7d',
                      gifSpeed,
                      svgCycles,
                      '%5d'
                    );
  }

  /// @dev generates the comment extension and closing gif bytes
  function genSeal(string memory idString, bytes8 salt) internal view returns(bytes memory) {
    bool extend = msg.sender == GIFED_ADDRESS  && msg.sig == hex'686b62fa'; // hex'dffc226e'; // old 6f344620
    bytes memory comment = bytes.concat(
                                  "-- Gifed",
                                  extend ? bytes.concat(" #", bytes(idString)) : bytes(""),
                                  " v1 - salt: ",
                                  getHexString(abi.encodePacked(salt)),
                                  " - contract: ",
                                  getHexString(abi.encodePacked(GIFED_ADDRESS)),
                                  " - germs was here -- "
                                );
    return bytes.concat(
                  hex'21fe',
                  bytes1(uint8(comment.length)),
                  comment,
                  hex'003b'
                );
  }

  function parseSalt(Seed memory seed, bytes8 salt) internal view {
    unchecked {
      // recycle pack
      // first 2 bits of salt[0]
      uint pack = uint(uint8(salt[0]) >> 6);
      seed.cycles = pack * 1200 / 3 + 800; // 800 - 2000
      // invert for block pre calcs
      pack = 3 - pack;
      // max block = 48x48 = 2304
      seed.blockSize = pack * 1280 / 3 + 1024; // 1024 - 2304 (inverse to cycles)
      seed.limits[0] = pack * 16 / 3 + 48; // 48 - 64 min major dimension
      seed.limits[1] = pack * 17 / 3 + 213 - seed.limits[0]; // 213 - 230 max major dimesion

      pack = uint(uint8(salt[0]));
      seed.bias = pack % 4;
      seed.mirror = (pack >> 2) % 4;
      seed.trace[1] = (pack >> 4) % 4;

      pack = uint(uint8(salt[1]));
      uint saturation = pack >> 2;
      if (saturation != 0) {
        saturation = saturation * 85 / 63 + 55; // 55 - 140
      }
      seed.reverse = [
              pack % 2, // reverse hue change
              (pack >> 1) % 2 // reverse value change
              ];

      pack = uint(uint8(salt[2]));
      seed.hsv = [
              uint(uint8(salt[3])),
              saturation,
              (pack >> 2) * 80 / 63 + 20 // 20 - 100
              ];
      seed.highlight = pack % 4;

      pack = uint8(salt[4]);
      seed.colourChanges = [
              (pack >> 4) * 140 / 15 + 30, // 30 - 170
              saturation == 0 ? uint(0) : uint(255) - saturation,
              uint(255) - seed.hsv[2]
            ];
      seed.trace[0] = (pack >> 1) % 8;
      seed.bump = pack % 2;
      // using only 5 bytes => 3 * 8 = 24 bits to strip
      // normal speed: hex'21f9040402000000'
      seed.gceControlled = bytes8(bytes.concat(
                        hex'21f90404',
                        bytes1(gifSpeedMutators[salt] < 2 ? 2 : gifSpeedMutators[salt]),
                        hex'000000'
                        ));
    }
  }

  function getRectTemplate() internal pure returns(bytes memory) {
    return ' <rect x="0000" y="0000" width="0000" height="0000" fill="#000000"/>\n';
  }

  function assembleSvgFrames(Seed memory seed, bytes memory buffer) internal pure {
    // append an updated template for each corner
    uint xpos2;
    uint ypos2;
    unchecked {
      xpos2 = (512 - seed.xpos) + 508 - seed.width;
      ypos2 = (512 - seed.ypos) + 509 - seed.height;
    }
    updateColour(seed.rectTemplate, 59, seed.lct);
    updateValue(seed.rectTemplate, 14, seed.xpos);
    updateValue(seed.rectTemplate, 23, seed.ypos);
    updateValue(seed.rectTemplate, 36, seed.width);
    updateValue(seed.rectTemplate, 50, seed.height);
    Buffer.appendBytes(buffer, seed.rectTemplate);
    updateValue(seed.rectTemplate, 23, ypos2);
    Buffer.appendBytes(buffer, seed.rectTemplate);
    updateValue(seed.rectTemplate, 14, xpos2);
    Buffer.appendBytes(buffer, seed.rectTemplate);
    updateValue(seed.rectTemplate, 23, seed.ypos);
    Buffer.appendBytes(buffer, seed.rectTemplate);
  }


  function genBlocks(Seed memory seed, bytes memory buffer) internal view {
    bytes memory trace = getTrace(seed);
    uint position;
    uint cycles = seed.svgCycles == 0 ? seed.cycles : seed.svgCycles;
    assembly {
      position := add(trace, 32)
    }
    bytes32 chunk;
    unchecked {
      for (seed.iter = 0; seed.iter < cycles;  seed.iter++) {
        assembly {
          chunk := mload(position)
        }
        seed.rand = [
          uint(uint8(chunk[0])),
          uint(uint8(chunk[1])),
          uint(uint8(chunk[2]))
          ];
        genFrames(seed, buffer);
        position += 3;
      }
    }
  }

  function genFrames(Seed memory seed, bytes memory buffer) internal pure {
    unchecked {
      uint major = seed.rand[0] * (seed.limits[1]) / 255 + seed.limits[0];
      uint minor = seed.blockSize/major;
      if (seed.bias == 0) { // none
        if (seed.rand[0] % 2 == 1) { // wide
          seed.width = major;
          seed.height = minor;
        } else { // tall
          seed.width = minor;
          seed.height = major;
        }
      } else if (seed.bias == 1) { // horizontal
        seed.width = major;
        seed.height =  minor;
      } else if (seed.bias == 2) { // vertical
        seed.width = minor;
        seed.height = major;
      } else { // square
        seed.width = minor;
        seed.height = minor;
      }
      // border 64px
      seed.xpos = seed.rand[1] * 2 * 446 / 510 + 64;
      seed.ypos = seed.rand[2] * 2 * 446 / 510 + 64;
      seed.lct = buildLCT(seed);
      if (seed.svgCycles > 0) {
        assembleSvgFrames(seed, buffer);
      } else {
        assembleGifFrames(seed, buffer);
      }
    }
  }

  function buildLCT(Seed memory seed)
      internal pure returns (bytes6) {
    unchecked {
      uint hStep;
      if (seed.mirror == 0) { // quad
        hStep = (seed.rand[2] * seed.rand[1] * seed.colourChanges[0]) / 65025;
      } else if (seed.mirror == 1){ // vertical
        hStep = (seed.rand[1] * seed.colourChanges[0]) / 255;
      } else if (seed.mirror == 2) { // horizontal
        hStep = (seed.rand[2] * seed.colourChanges[0]) / 255;
      } else {  // inverse of quad
        hStep = (255 - seed.rand[2]) * (255 - seed.rand[1]) * seed.colourChanges[0] / 65025;
      }
      uint vStep;
      if (seed.highlight == 0) { // subdue
        vStep = seed.iter * seed.colourChanges[2] / (seed.cycles - 1) / 2;
      } else if (seed.highlight == 1) { // full
        vStep = seed.iter * seed.colourChanges[2] / (seed.cycles - 1);
      } else if (seed.highlight == 2) { // follow mirror
        if (seed.mirror == 0) { // quad
          vStep = (seed.rand[2] * seed.rand[1] * seed.colourChanges[2]) / 65025;
        } else if (seed.mirror == 1) { // vertical
          vStep = seed.rand[1] * seed.colourChanges[2] / 255;
        } else if (seed.mirror == 2) { // horizontal
          vStep = seed.rand[2] * seed.colourChanges[2] / 255;
        } else { // inverse of quad
          vStep = (255 - seed.rand[2]) * (255 - seed.rand[1]) * seed.colourChanges[2] / 65025;
        }
      } else { // emphasize bias (seed.highlight == 3)
        vStep = seed.rand[0] * seed.colourChanges[2] / 255;
      }
      return bytes6(Colour.getRGB(
            seed.reverse[0] == 1 ? int(seed.hsv[0] + 256 - hStep) : int(seed.hsv[0] + hStep),
            int(seed.iter * seed.colourChanges[1] / (seed.cycles - 1) + seed.hsv[1]),
            int(seed.reverse[1] == 1? 255 - vStep : seed.hsv[2] + vStep)
          ));
    }
  }

  /// @dev The duration for the final frame is extended to play nicely with socials
  function assembleGifFrames(Seed memory seed, bytes memory gif) internal pure {
    // 1000 hundredths of a second => 03e8 => e803 (least significant first)
    uint xpos2;
    uint ypos2;
    /* bool lastCycle = seed.iter == seed.cycles - 1; */
    unchecked {
      xpos2 = (512 - seed.xpos) + 508 - seed.width;
      ypos2 = (512 - seed.ypos) + 509 - seed.height;
    }
    seed.quadIds[0] = buildID(seed.xpos, seed.ypos, seed.width, seed.height);
    seed.quadIds[1] = buildID(seed.xpos, ypos2, seed.width, seed.height);
    seed.quadIds[2] = buildID(xpos2, seed.ypos, seed.width, seed.height);
    seed.quadIds[3] = buildID(xpos2, ypos2, seed.width, seed.height);
    unchecked {
      // the first 3 frames of each quad always use shortest functional duration (0.02s)
      // don't know why, but renderers seem to ingnore a value of 0.01s
      for (uint8 i = 0; i < 3; i++) {
        Buffer.appendBytes8(gif, hex'21f9040402000000');
        Buffer.appendBytes10(gif, seed.quadIds[i]);
        Buffer.appendBytes6(gif, seed.lct);
        Buffer.appendBytes(gif, seed.imageBlock);
      }
      // the duration of the 4th frame of each quad is dependent on gif speed mutation
      // seed.gceControlled default is 0.02 seconds.
      // renderers should only play this gif once as looping is not set explicity.
      // last frame of gif is set to delay loop for non conforming renderers
      //   29.92 seconds (2992e-2) => 0x0bb0 => b00b (. .)
      Buffer.appendBytes8(gif, seed.iter == seed.cycles - 1 ?
            bytes8(hex'21f90404b00b0000') : seed.gceControlled);
      Buffer.appendBytes10(gif, seed.quadIds[3]);
      Buffer.appendBytes6(gif, seed.lct);
      Buffer.appendBytes(gif, seed.imageBlock);
    }
  }

  function buildID(uint xpos, uint ypos, uint width, uint height)
        internal pure returns (bytes10) {
    unchecked {
      return bytes10(uint80(
            0x80
            + ((height / 255) << 8)
            + ((height % 255) << 16)
            + ((width / 255) << 24)
            + ((width % 255) << 32)
            + ((ypos / 255) << 40)
            + ((ypos % 255) << 48)
            + ((xpos / 255) << 56)
            + ((xpos % 255) << 64)
            + (0x2c << 72)
        ));
    }
  }

  // mainnet
  function getTraceAddress(uint index) internal pure returns(address) {
    if (index == 0) return GIFED_ADDRESS;                                   // quinish
    else if (index == 1) return 0x606dafc3a4dE213B68b59e9f5842fE2d9f5Ce255; // diid
    else if (index == 2) return 0x9dd2BfBC211C07Dc6d0ddD31eB41708c9F3F0bf4; // DocT
    else if (index == 3) return 0x2C3D49E10956Dc91E68069a52a1Cdc7F58F285AA; // YUDHO
    else if (index == 4) return 0xbA7CB5E95B434d67d0F771167605a53E4ca11afD; // SATHAR
    else if (index == 5) return 0x9dD5d7EB0338A4B3fE271EbDdf7320D484dB4C04; // ripcache
    else if (index == 6) return 0x7d1a14C3dB9693f46E6d49b29B53c12850a866dc; // peng1
    else return 0x349DD5DC542eF98CEA06eD2E82D95c71de517430;                 // MRC
  }

  function getTraceName(uint index) internal pure returns (bytes memory) {
    if (index == 0) return bytes("quinish");
    else if (index == 1) return bytes("diid");
    else if (index == 2) return bytes("DocT");
    else if (index == 3) return bytes("YUDHO");
    else if (index == 4) return bytes("SATHAR");
    else if (index == 5) return bytes("ripcache");
    else if (index == 6) return bytes("peng1");
    else return bytes("MRC");
  }

  function getTrace(Seed memory seed) internal view returns (bytes memory) {
    IStorageTools tools = IStorageTools(TOOLS_ADDRESS);
    address traceAddress = getTraceAddress(seed.trace[0]);
    uint byteCount = seed.cycles * 3;
    uint length = traceAddress.code.length - 1; // -1 for the bump
    uint start = 0;
    if (seed.trace[1] == 0) {
      start = 1 + seed.bump;
    } else {
      uint step = byteCount + (3 - seed.trace[1]) * (length / 4) + (seed.cycles - 800) * 3 / 4;
      start = length - step + seed.bump;
    }
    return tools.read(traceAddress, start, start + byteCount);
  }

  function getImageBlock() internal view returns (bytes memory) {
    IStorageTools tools = IStorageTools(TOOLS_ADDRESS);
    return tools.read(IMAGE_DATA_ADDRESS, 1820, 1872);
  }

  function stripSalt(bytes8 salt) internal pure returns(bytes8) {
    return (salt >> 24) << 24;
  }

  function getHexString(bytes memory data) internal pure returns(bytes memory) {
    bytes memory hexBytes = '0x';
    bytes16 alphabet = "0123456789abcdef";
    for (uint i = 0; i < data.length; i++) {
      hexBytes = bytes.concat(
                        hexBytes,
                        alphabet[uint8(data[i] >> 4)],
                        alphabet[uint8(data[i] & 0x0f)]
                        );
    }
    return hexBytes;
  }

  // overwrites rect template "fill" with first colour in lcd
  function updateColour(bytes memory template, uint pointer, bytes6 lcd) internal pure {
    bytes16 alphabet = "0123456789abcdef";
    for (uint i = 0; i < 3; i++) {
        template[pointer + i * 2 ] = alphabet[uint8(lcd[i] >> 4)];
        template[pointer + 1 + i * 2] = alphabet[uint8(lcd[i] & 0x0f)];
    }
  }

  // this should write the asci value backwards from pointer
  // works like a fucking charm
  function updateValue(bytes memory template, uint pointer, uint value) internal pure {
    bytes16 alphabet = "0123456789abcdef";
    unchecked {
        assembly ("memory-safe") {
            pointer := add(add(template, 0x20), pointer)
        }
        // explicitly set each of the four digits.
        // need to zero previous value
        for (uint i = 0; i < 4; i ++) {
            pointer--;
            assembly ("memory-safe") {
                mstore8(pointer, byte(mod(value, 10), alphabet))
            }
            value /= 10;
        }
    }
  }

  /**
  * @notice allows token owner to change the animation speed of the gif.
  * @param tokenId the token's id.
  * @param mutator 0-255. delay in 0.01's of a second (higher => slower)
  * @dev a mutator < 3 will be set to the default speed of 2.
  *   most renderers seem to ingore a value of 0.01s for delay
  */
  function mutateGifSpeed(uint tokenId, uint8 mutator) external {
    // this will preserve trait even if set to default
    gifSpeedMutators[checkToken(tokenId)] = mutator < 3 ? 2 : mutator;
  }

  /**
  * @notice allows token owner to change the number of cycles for generating the svg image
  * @param tokenId the token's id.
  * @param mutator 1-255. higher => more cycles are rendered. (default: 36)
  * @dev mutator value of 0 will be set to default. 0 reserved for gif rendering.
  */
  function mutateSvgCycles(uint tokenId, uint8 mutator) external {
    bytes8 salt = checkToken(tokenId);
    svgCycleMutators[salt] = mutator > 0 ? mutator : DEFAULT_SVG_CYCLE_MUTATOR;
  }

  // TODO: make sure checkToken version arg is set correctly (have changed to 2 here)
  /**
  * @notice checks Gifed contract for tokenId within version range and ownership for mutation
  * @param tokenId the token's id.
  * @dev returns the salt for the given tokenId
  */
  function checkToken(uint tokenId) internal returns(bytes8) {
    IGifed gifed = IGifed(GIFED_ADDRESS);
    try gifed.checkToken(tokenId, msg.sender, 1) returns(bytes8 salt) {
      return salt;
    } catch Error(string memory err) {
      revert(err);
    } catch {
      revert('failed check');
    }
  }

}

Buffer.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

/**
* @title A Dangerous Buffer Manipulator
* @author Germs
* @author much of this has been copied and customized from original scripts:
*     Buffer.sol by David Huber and Simon Fremaux
*     Solady's Base64.sol (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)
* @notice purpose built functions for creating and manipulating memory buffers
* @dev i would not recommend using this library without understanding it thoroughly
*     i've marked some of the functions "memory-safe" but they really aren't
*     there are no checks or balances. use at your own peril.
*/

library Buffer {

    /**
    * @notice create a new memory buffer
    * @param capacity the size of the buffer
    * @dev data can be added to this buffer using appendBytes(buffer, data)
    */
    function allocate(uint256 capacity) internal pure returns (bytes memory buffer) {
        assembly ("memory-safe") {
            // get next free memory address
            buffer := mload(0x40)
            // allocate memory by setting a new next free address
            {
                // ignoring original container size
                // adding extra word for the illusion of safety
                let size := add(capacity, 0x40)
                mstore(0x40, add(buffer, size))
            }
            // init new buffer with length 0
            mstore(buffer, 0)
        }
    }

    /**
    * @notice appends data to an existing buffer and update it's length
    * @param buffer The memory buffer to add the data to
    * @param data The bytes to add to the buffer
    * @dev this does not check if it will extend beyond the buffer's allocated size
    */
    function appendBytes(bytes memory buffer, bytes memory data) internal pure {
        assembly ("memory-safe") {
            let length := mload(data)
            for {
                let chunk := add(data, 32)
                let dataEnd := add(chunk, length)
                let buf := add(buffer, add(mload(buffer), 32))
            } lt(chunk, dataEnd) {
                chunk := add(chunk, 32)
                buf := add(buf, 32)
            } {
                // Copy 32B chunks from data to buffer.
                // This may read over data array boundaries and copy invalid
                // bytes, which doesn't matter in the end since we will
                // later set the correct buffer length.
                mstore(buf, mload(chunk))
            }

            // Update buffer length
            mstore(buffer, add(mload(buffer), length))
        }
    }

    /**
    * @notice override the "size" of the buffer. appendBytes() will then write at this position.
    * @param buffer the memory buffer
    * @param position the new write position for the buffer.
    * @dev not sure what will happen if it is set beyond buffer's allocated size
    *   probably won't be good
    */
    function setPointer(bytes memory buffer, uint position) internal pure {
        assembly ("memory-safe") {
          mstore(buffer, position)
        }
    }

    /**
    * @notice appends a bytes6 to a memory buffer
    * @param buffer the memory buffer
    * @param data the bytes6 to write
    * @dev appendBytes8 and appendBytes10 follow the same pattern
    */
    function appendBytes6(bytes memory buffer, bytes6 data) internal pure {
      assembly ("memory-safe") {
        let length := mload(buffer)
        let position := add(buffer, add(length, 0x20))
        mstore(position, data)
        mstore(buffer, add(length, 6))
      }
    }

    function appendBytes8(bytes memory buffer, bytes8 data) internal pure {
      assembly ("memory-safe") {
        let length := mload(buffer)
        let position := add(buffer, add(length, 0x20))
        mstore(position, data)
        mstore(buffer, add(length, 8))
      }
    }

    function appendBytes10(bytes memory buffer, bytes10 data) internal pure {
      assembly ("memory-safe") {
        let length := mload(buffer)
        let position := add(buffer, add(length, 0x20))
        mstore(position, data)
        mstore(buffer, add(length, 10))
      }
    }

    /**
    * @notice encodes data within a buffer using the base64 encoding described in RFC 4648
    * @param buffer the buffer to encode within
    * @param readFrom the position within the buffer to begin reading data for encoding
    * @param writeTo the position within the buffer to write the encoded data
    * @dev data is read to the end of the buffer. encoding adds padding and not file safe
    *   this one will definitely break things if you aren't careful
    */
    function incode64(bytes memory buffer, uint readFrom, uint writeTo) internal pure {
        assembly ("memory-safe") {
            let dataLength := sub(mload(buffer), readFrom)
            let save := mload(0x40)
            if dataLength {
                // Multiply by 4/3 rounded up.
                // The `shl(2, ...)` is equivalent to multiplying by 4.
                let encodedLength := shl(2, div(add(dataLength, 2), 3))
                let readPtr := add(buffer, readFrom)
                let writePtr := add(buffer, add(writeTo, 32))
                // Store the table into the scratch space.
                // Offsetted by -1 byte so that the `mload` will load the character.
                // We will rewrite the free memory pointer at `0x40` later with
                // the allocated size.
                mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
                mstore(0x3f, "ghijklmnopqrstuvwxyz0123456789+/")
                let end := add(writePtr, encodedLength)

                // Run over the input, 3 bytes at a time.
                for {} 1 {} {
                    readPtr := add(readPtr, 3)
                    let input := mload(readPtr)

                    mstore8(writePtr, mload(and(shr(18, input), 0x3F)))
                    mstore8(add(writePtr, 1), mload(and(shr(12, input), 0x3F)))
                    mstore8(add(writePtr, 2), mload(and(shr(6, input), 0x3F)))
                    mstore8(add(writePtr, 3), mload(and(input, 0x3F)))

                    writePtr := add(writePtr, 4)
                    if iszero(lt(writePtr, end)) { break }
                }
                // Equivalent to `o = [0, 2, 1][dataLength % 3]`.
                let o := div(2, mod(dataLength, 3))
                // Offset `ptr` and pad with '='. We can simply write over the end.
                mstore(sub(writePtr, o), shl(240, 0x3d3d))
                mstore(writePtr, 0) // Zeroize the slot after the string.
                mstore(buffer, add(writeTo, encodedLength)) // set to the last write position
                // rewrite the free memory location
                mstore(0x40, save)
            }
        }
    }
}

Colour.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

/**
* @title Colour
* @author germs
* @author reduced and optomized 0xdiid's Color.sol used @ 0xDFC21c8b8346AA12096401BAF456f19C17127e5d
* @notice calculates rgb from hsv values
* @dev changed name from Color => Colour because i'm Canadian eh.
*/
library Colour {

    function _min(int o1, int o2, int o3) private pure returns(int) {
        int min = 0xFFFFFFFFFFFFFFFF;
        if (o1 < min) min = o1;
        if (o2 < min) min = o2;
        if (o3 < min) min = o3;
        return min;
    }

    function getRGBComponent(int n, int h, int s, int v) private pure returns(uint) {
        int k = (n * 256 + h * 6) % (6 * 256);
        int l = _min(k, 1024 - k, 256);
        int m = l > 0 ? l : int(0);
        return uint((v * (256 - (s * m) / 256)) / 256) & 0xff;
    }

    function getRGB(int h, int s, int v) internal pure returns(bytes3) {
        return bytes3(uint24(
                        getRGBComponent(1, h, s, v)
                        + (getRGBComponent(3, h, s, v) << 8)
                        + (getRGBComponent(5, h, s, v) << 16)
                      ));
    }
}

IGifedRenderer.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

interface IGifedRenderer {

    /**
    * @notice pack the token metadata with version attributes and image name/value
    *      close and return the completed json uri
    * @param start the beginning of the tokenURI meatdata json.
    *      the attribute array must still be open
    * @param idString the token Id number converted to a string
    * @param salt the salt for the given token Id
    * @dev to be called by the main ERC-721 contract's tokenURI function.
    */
    function packTokenURI(bytes calldata start, string calldata idString, bytes8 salt) external view returns(string memory);

    /**
    * @notice get a gif data uri for a given salt
    * @param salt the salt
    * @dev for frontend use
    */
    function gifURI(bytes8 salt) external view returns(string memory);

    /**
    * @notice get raw gif bytes for a given salt
    * @param salt the salt
    * @dev intended for use with web3:// protocol
    */
    function gifBytes(bytes8 salt) external view returns(bytes memory);
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.