// File: @chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol



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

interface AggregatorInterface {
  function latestAnswer()
    external
    view
    returns (
      int256
    );
  
  function latestTimestamp()
    external
    view
    returns (
      uint256
    );

  function latestRound()
    external
    view
    returns (
      uint256
    );

  function getAnswer(
    uint256 roundId
  )
    external
    view
    returns (
      int256
    );

  function getTimestamp(
    uint256 roundId
  )
    external
    view
    returns (
      uint256
    );

  event AnswerUpdated(
    int256 indexed current,
    uint256 indexed roundId,
    uint256 updatedAt
  );

  event NewRound(
    uint256 indexed roundId,
    address indexed startedBy,
    uint256 startedAt
  );
}

// File: @chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol



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

import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";

interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}

// File: @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol



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

interface AggregatorV3Interface {

  function decimals()
    external
    view
    returns (
      uint8
    );

  function description()
    external
    view
    returns (
      string memory
    );

  function version()
    external
    view
    returns (
      uint256
    );

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(
    uint80 _roundId
  )
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// File: @openzeppelin/contracts/utils/math/Math.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

// File: @openzeppelin/contracts/utils/math/SignedMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// File: @openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// File: base64-sol/base64.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;

/// @title Base64
/// @author Brecht Devos - <brecht@loopring.org>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
    string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    bytes  internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
                                            hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
                                            hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
                                            hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";

    function encode(bytes memory data) internal pure returns (string memory) {
        if (data.length == 0) return '';

        // load the table into memory
        string memory table = TABLE_ENCODE;

        // multiply by 4/3 rounded up
        uint256 encodedLen = 4 * ((data.length + 2) / 3);

        // add some extra buffer at the end required for the writing
        string memory result = new string(encodedLen + 32);

        assembly {
            // set the actual output length
            mstore(result, encodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 3 bytes at a time
            for {} lt(dataPtr, endPtr) {}
            {
                // read 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // write 4 characters
                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
                resultPtr := add(resultPtr, 1)
                mstore8(resultPtr, mload(add(tablePtr, and(        input,  0x3F))))
                resultPtr := add(resultPtr, 1)
            }

            // padding with '='
            switch mod(mload(data), 3)
            case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
            case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
        }

        return result;
    }

    function decode(string memory _data) internal pure returns (bytes memory) {
        bytes memory data = bytes(_data);

        if (data.length == 0) return new bytes(0);
        require(data.length % 4 == 0, "invalid base64 decoder input");

        // load the table into memory
        bytes memory table = TABLE_DECODE;

        // every 4 characters represent 3 bytes
        uint256 decodedLen = (data.length / 4) * 3;

        // add some extra buffer at the end required for the writing
        bytes memory result = new bytes(decodedLen + 32);

        assembly {
            // padding with '='
            let lastBytes := mload(add(data, mload(data)))
            if eq(and(lastBytes, 0xFF), 0x3d) {
                decodedLen := sub(decodedLen, 1)
                if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
                    decodedLen := sub(decodedLen, 1)
                }
            }

            // set the actual output length
            mstore(result, decodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 4 characters at a time
            for {} lt(dataPtr, endPtr) {}
            {
               // read 4 characters
               dataPtr := add(dataPtr, 4)
               let input := mload(dataPtr)

               // write 3 bytes
               let output := add(
                   add(
                       shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
                       shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
                   add(
                       shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
                               and(mload(add(tablePtr, and(        input , 0xFF))), 0xFF)
                    )
                )
                mstore(resultPtr, shl(232, output))
                resultPtr := add(resultPtr, 3)
            }
        }

        return result;
    }
}

// File: contracts/FiniSketch.sol



// SPDX-License-Identifier: GPL-3.0

/**

             #@@@@                                         @@@@@            
           @@@@@@@@@.                                    @@@@@@@@@          
           @@@@@@@@@.                                    @@@@@@@@@          
           @@@@@@@@@.      @@@@@              %@@@@      @@@@@@@@@          
             #@@@@           @@@@@         @@@@@           @@@@@            
                                 @@@@@@@@@@@@                               
      /////////////                                        ////////////     
     ///////////////.                                   //////////////////  
    /////////////////                                   //////////////////  
    /////////////////                                    ////////////////   
      /////////////                                        ////////////     

*/

pragma solidity ^0.8.19;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol";
import "./interfaces/IFiniOracle.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./interfaces/IHLFS.sol";
import { Base64 } from "base64-sol/base64.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract FiniSketch is Ownable {
    using Strings for uint256;
    using Strings for int256;

    address public finiOracleContract = 0xfA52EC029c47AfeD7Ff10DcF478149342441CEb4;
    address public fileStorage;

    string public description = "Fini Cards are an on-chain exploration of over 60 different Chainlink oracles-from foreign currencies and NFT floor prices, to commodities and ETFs-using animated sketches from the early days of Fini's conception. \\nHeads up: Fini Cards are experimental, and rely on the persistence of their underlying oracles to continue functioning properly. They may one day break.";

    address[] public oracleAddresses = [
        0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419, // eth -- 8, USD
        0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c, // btc -- 8, USD
        0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3, // jpy -- 8, USD
        0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5, // gbp -- 8, USD
        0xb49f677943BC038e9857d61E7d053CaA2C1734C1, // eur -- 8, USD
        0x449d117117838fFA61263B61dA6301AA2a88B13A, // chf -- 8, USD
        0x77F9710E7d0A19669A13c055F62cd80d313dF022, // aud -- 8, USD
        0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c, // link -- 8, USD
        0x6AF09DF7563C363B5763b9102712EbeD3b9e859B, // ltc -- 8, USD
        0xdbd020CAeF83eFd542f4De03e3cF0C28A4428bd5, // comp -- 8, USD
        0x14e613AC84a31f709eadbdF89C6CC390fDc9540A, // bnb -- 8, USD
        0x553303d460EE0afB37EdFf9bE42922D8FF63220e, // uni -- 8, USD
        0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55, // ada -- 8, USD
        0xCd627aA160A6fA45Eb793D19Ef54f5062F20f33f, // crv -- 8, USD
        0x547a514d5e3769680Ce22B2361c10Ea13619e8a9, // aave -- 8, USD
        0xA027702dbb89fbd58938e4324ac03B58d812b0E1, // yfi -- 8, USD
        0x1C07AFb8E2B827c5A4739C6d59Ae3A5035f28734, // dot -- 8, USD
        0x7bAC85A8a13A4BcD8abb3eB7d6b4d632c5a57676, // matic -- 8, USD
        0xa34317DB73e77d453b1B8d04550c44D10e981C8e, // cad -- 8, USD
        0xeF8A4aF35cd47424672E3C590aBD37FBB7A7759a, // cny -- 8, USD
        0xe25277fF4bbF9081C75Ab0EB13B4A13a721f3E13, // sgd -- 8, USD
        0x01435677FB11763550905594A16B645847C1d0F3, // krw -- 8, USD
        0xB09fC5fD3f11Cf9eb5E1C5Dba43114e3C9f477b5, // try -- 8, USD
        0xc929ad75B72593967DE83E7F7Cda0493458261D9, // 1inch -- 8, USD
        0x35E3f7E558C04cE7eEE1629258EcbbA03B36Ec56, // sand -- 8, USD
        0x3977CFc9e4f29C184D4675f4EB8e0013236e5f3e, // nzd -- 8, USD
        0x2465CefD3b488BE410b941b1d4b2767088e2A028, // doge -- 8, USD
        0xCc70F09A6CC17553b2E31954cD36E4A2d89501f7, // sushi -- 8, USD
        0xFF3EEb22B5E3dE6e705b44749C2559d704923FD7, // avax -- 8, USD
        0x4ffC43a60e009B551865A93d232E33Fce9f01507, // sol -- 8, USD
        0x8c110B94C5f1d347fAcF5E1E938AB2db60E3c9a8, // spell -- 8, USD
        0xD10aBbC76679a20055E167BB80A24ac851b37056, // ape -- 8, USD
        0xA8B9A447C73191744D5B79BcE864F343455E1150, // azuki -- 18, ETH
        0xFaA8F6073845DBe5627dAA3208F78A3043F99bcA, // cryptoadz -- 18, ETH
        0xF49f8F5b931B0e4B4246E4CcA7cD2083997Aa83d, // cool cats -- 18, ETH
        0x021264d59DAbD26E7506Ee7278407891Bb8CDCCc, // clonex -- 18, ETH
        0x352f2Bc3039429fC2fe62004a1575aE74001CfcE, // BAYC -- 18, ETH
        0xA97477aB5ab6ED2f6A2B5Cbe59D71e88ad334b90, // beanz -- 18, ETH
        0xEb0adf5C06861d6c07174288ce4D0a8128164003, // cake - 8, USD
        0x01B6710B01cF3dd8Ae64243097d91aFb03728Fdd, // cryptopunks -- 18, ETH
        0x027828052840a43Cc2D0187BcfA6e3D6AcE60336, // doodles -- 18, ETH
        0x9cd36E0E8D3C27d630D00406ACFC3463154951Af, // moonbirds -- 18, ETH
        0x1823C89715Fe3fB96A24d11c917aCA918894A090, // mayc -- 18, ETH
        0x6e3A4376B4C8D3ba49602f8542D9D3C4A87ba901, // otherdeed -- 18, ETH
        0x9f2ba149c2A0Ee76043d83558C4E79E9F3E5731B, // pudgy penguins -- 18, ETH
        0x9a51192e065ECC6BDEafE5e194ce54702DE4f1f5, // pce index -- 18, NO VALUE
        0x35bf6767577091E7f04707c0290b3f889e968307, // veefriends -- 18, ETH
        0xEC8761a0A73c34329CA5B1D3Dc7eD07F30e836e2, // total marketcap index - 8, USD
        0xF4E1B57FB228879D057ac5AE33973e8C53e4A0e0, // cspx -- 8, USD
        0x32d1463EB53b73C095625719Afa544D5426354cB, // ib01 -- 8, USD
        0xd27e6D02b72eB6FCe04Ad5690C419196B4EF2885, // ibta -- 8, USD
        0x214eD9Da11D2fbe465a6fc601a91E62EbEc1a0D6, // xau -- 8, USD
        0x379589227b15F1a12195D3f2d90bBc9F31f95235, // xag -- 8, USD
        0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C, // gas -- 0, GWEI
        0x5C8D8AaB4ffa4652753Df94f299330Bb4479bF85, // highstreet - 8, USD
        0x652Ac4468688f277fB84b26940e736a20A87Ac2d, // eurr reserves - 6, EUROS
        0xAF2Ce23Ef2dD9BB6F03668cA6eAd55aEa1e56FBa, // hope por - 8, USD
        0x60cbE8D88EF519cF3C62414D76f50818D211fea1, // swell eth por - 18, ETH
        0xad4A9bED9a5E2c1c9a6E43D35Db53c83873dd901, // stbt por - 18, USD
        0x5586bF404C7A22A4a4077401272cE5945f80189C, // cache gold reserves - 8, GRAMS
        0xBE456fd14720C3aCCc30A2013Bffd782c9Cb75D5, // TUSD por -- 18, USD
        0xa81FE04086865e63E12dD3776978E49DEEa2ea4e // WBTC por - 18, BTC
    ];

    string[] public colors = ["5dd5a5", "6ab4ff", "ff8445", "f1b3d1", "ffd88d", "efaf35", "ff564c", "24fff7"];

    constructor()
      Ownable(msg.sender)
    {}
    
    function tokenURI(uint256 tokenId) public view returns (string memory) {
       (string memory svg, string memory feedName) = drawSVG(tokenId);
       string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name":"Fini Card ', tokenId.toString(), '","description":"', description, '","image":"data:text/html;base64,', Base64.encode(bytes(svg)), '", "attributes":[{"trait_type":"Oracle","value":"', feedName,'"}]}'))));
       return json;
    }

    function drawSVG(uint256 tokenId) public view returns (string memory, string memory) {
        (
            int256 delta,
            int256 price,
            AggregatorV2V3Interface feed
        ) = getDataForTokenId(tokenId);

        (string memory textSnippets, string memory feedName) = getStringsForData(delta, price, feed);

        string memory image1;
        string memory image2;

        if (delta > 100) {
            image1 = IHLFS(fileStorage).fileContents("finiStarsOne.txt");
            image2 = IHLFS(fileStorage).fileContents("finiStarsTwo.txt");
        } else if (delta < -100) {
            image1 = IHLFS(fileStorage).fileContents("finiCopeOne.txt");
            image2 = IHLFS(fileStorage).fileContents("finiCopeTwo.txt");
        } else {
            image1 = IHLFS(fileStorage).fileContents("finiNeutralOne.txt");
            image2 = IHLFS(fileStorage).fileContents("finiNeutralTwo.txt");
        }

        return (
            string(abi.encodePacked(IHLFS(fileStorage).fileContents("svgPart1.txt"), IHLFS(fileStorage).fileContents("font.txt"), IHLFS(fileStorage).fileContents("svgPart2.txt"), getColorForTokenId(tokenId), textSnippets, image1, IHLFS(fileStorage).fileContents("svgPart6.txt"), image2, '"/></svg>')),
            feedName
        );
    }

    function getDataForTokenId(uint256 tokenId) public view returns (int256, int256, AggregatorV2V3Interface) {
        return getDataForFeedAddress(getOracleAddressForTokenId(tokenId));
    }


    /**
     * @notice Get a % delta for a given feed (oracle) address
     * @return delta This is a % delta * 100, i.e. it must be divided by 100 to
     * get the real %. We're doing this to preserve some precision with the calculation.
     */
    function getDataForFeedAddress(address feedAddress) public view returns (int256, int256, AggregatorV2V3Interface) {
        // first fetch the current price
        AggregatorV2V3Interface feed = AggregatorV2V3Interface(feedAddress);
        int256 latestPrice = feed.latestAnswer();

        // fetch the corresponding previous roundId from 24 hours prior
        uint80 roundId = getPreviousRoundId(feed);
        // now derive the previous price from the roundId
        (
          ,
          int256 previousPrice,
          ,
          ,
        ) = feed.getRoundData(roundId);

        // compare the two
        int256 delta = (latestPrice - previousPrice) * 10000 / previousPrice;

        return (delta, latestPrice, feed);
    }

    function getStringsForData(int256 delta, int256 latestPrice, AggregatorV2V3Interface feed)
        public
        view
        returns (string memory, string memory)
    {
        string memory textOne;
        string memory textTwo;

        string memory priceString = intToStringWithDecimals(latestPrice, feed.decimals());

        if (address(feed) == 0xa81FE04086865e63E12dD3776978E49DEEa2ea4e) {
            textTwo = string(abi.encodePacked("It's ", priceString, " Bitcoin"));
        } else if (address(feed) == 0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C) {
            textTwo = string(abi.encodePacked("It's ", priceString, " gwei"));
        } else if (address(feed) == 0x9a51192e065ECC6BDEafE5e194ce54702DE4f1f5) {
            textTwo = string(abi.encodePacked("It's ", priceString));
        } else if (address(feed) == 0x5586bF404C7A22A4a4077401272cE5945f80189C) {
            textTwo = string(abi.encodePacked("It's ", priceString, " grams"));
        } else if (feed.decimals() == 18 && address(feed) != 0xad4A9bED9a5E2c1c9a6E43D35Db53c83873dd901 && address(feed) != 0xBE456fd14720C3aCCc30A2013Bffd782c9Cb75D5) {
            textTwo = string(abi.encodePacked("It's ", priceString, " eth"));
        } else {
            textTwo = string(abi.encodePacked("It's $", priceString));
        }

        string memory feedName = feed.description();
        string memory deltaString = intToStringWithDecimals(delta, 2);

        if (delta > 100) {
            textOne = string(abi.encodePacked("Yay, ", feedName, " is up ", deltaString, "%!!"));
        } else if (delta < -100) {
            textOne = string(abi.encodePacked("Oh no, ", feedName, " is down ", deltaString, "%?!"));
        } else {
            textOne = string(abi.encodePacked("Hm, ", feedName, " has moved ", deltaString, "%"));
        }

        string memory svgSnippet = string(abi.encodePacked(IHLFS(fileStorage).fileContents("svgPart3.txt"), textOne, IHLFS(fileStorage).fileContents("svgPart4.txt"), textTwo, IHLFS(fileStorage).fileContents("svgPart5.txt")));

        return (svgSnippet, feedName);
    }

    /**
     * @notice Get the roundId for this feed from 24 hours prior. 
     * The roundId is used later to fetch an historical price.
     * @dev Keeping this separate so we can debug on mainnet if needed.
     * @param feed contract
     * @return roundId
     */
    function getPreviousRoundId(AggregatorV2V3Interface feed) public view returns (uint80) {
        IFiniOracle finiOracle = IFiniOracle(finiOracleContract);
        // grab the latest roundId
        uint80 latestRound = uint80(feed.latestRound());

        // recurse to find the previous roundId for our frequency
        uint80 roundId = finiOracle.findRoundId(
            block.timestamp - 86400, // target unix timestamp for 24 hrs ago
            feed,
            latestRound,
            0,
            12, // jump sizes for 24 hours
            false
        );

        return roundId;
    }

     /**
     * @notice Returns oracle address for a tokenId.
     * @dev This will be used to determine which token is assigned to which oracle.
     */
    function getOracleAddressForTokenId(uint256 tokenId) public view returns (address) {
        uint256 index = pseudoRandom(tokenId) % oracleAddresses.length;
        return oracleAddresses[index];
    }

    function getColorForTokenId(uint256 tokenId) public view returns (string memory) {
        uint256 index = pseudoRandom(tokenId) % colors.length;
        return colors[index];
    }

    /**
     * @notice Get a pseudorandom idempotent value for each tokenId.
     * @dev This will be used to determine which token is assigned to which oracle.
     */
    function pseudoRandom(uint256 tokenId) public pure returns (uint) {
        return uint(keccak256(abi.encodePacked(tokenId)));
    }

    function intToStringWithDecimals(int256 value, uint8 decimals) public pure returns (string memory) {
        // Check if the value is negative
        bool negative = value < 0;
        
        // Get what should come before the decimal
        uint256 intValue = negative ? uint256(-value) : uint256(value);
        // string memory intPart = toString(intValue);
        uint256 intPart = intValue / 10**decimals;

        // Get what should come after the decimals
        uint256 fractionalPart = (intValue - (intPart * 10**decimals));

        if (decimals > 10) {
            fractionalPart = fractionalPart / 10**(decimals - 6);
        }

        // Concatenate the integer and fractional parts
        string memory result;
        if (negative) {
            result = string(abi.encodePacked("-", intPart.toString(), ".", fractionalPart.toString()));
        } else {
            result = string(abi.encodePacked(intPart.toString(), ".", fractionalPart.toString()));
        }

        return result;
    }

    function updateFileStorage(address _address) public onlyOwner {
        fileStorage = _address;
    }

}

// File: contracts/interfaces/IFiniOracle.sol



// SPDX-License-Identifier: GPL-3.0

/// @title IDescriptor interface

pragma solidity ^0.8.6;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol";

interface IFiniOracle {
     function findRoundId(
        uint256 targetTimestamp,
        AggregatorV2V3Interface feed,
        uint80 roundId,
        uint16 counter,
        uint16 jumpSize,
        bool jumpDirection
    )
        external
        view
        returns (uint80);
}

// File: contracts/interfaces/IHLFS.sol



interface IHLFS {
    /**
     * @notice Get contents of a file on a HL FS
     */
    function fileContents(string calldata fileName) external view returns (string memory);
}