Skip to content
Verified contractPartialUNLICENSED

Utils

Address0x85dde7be6cf978b7e515de73c2b301c1f1df5ba3
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.13

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.13+commit.abaa5c0e
Language
solidity
Optimization
Yes, 200 runs
EVM version
london
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
17,034,530
Creation transaction
0xe3cac0f60a…af9b892b13

/contracts/Utils.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.8.0;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./Base64.sol";

struct ContractData {
  address beneficiary;
	uint96 royalty;
  string desc;
  string osImage;
	string osBanner;
  string osDescription;
  string osExternalLink;
}

struct SignData {
	bytes32 payloadHash;
	string tokenUri;
	bytes nonce;
	bytes signature;
}

struct TransferData {
  uint fee;
  uint expires;
  bytes data;
	bytes signature;
}

struct ReturnData {
  uint fee;
  uint expires;
  string ordinal;
  bytes data;
	bytes signature;
}

contract Utils {

	using ECDSA for bytes32;

	constructor() {
  }

  event xTransferEvent (
    address indexed sender,
    uint indexed tokenId,
    address indexed addr,
    bytes transferData
  );

  event xReturnEvent (
    address indexed receiver,
    uint indexed tokenId,
    address indexed addr,
    string ordinal,
    bytes returnData
  );

	function verifySignature(SignData memory _signData, address addr, uint tokenId, address signedBy) public pure returns(address signer, bytes32 signedHash, string memory tokenUri) {
		bytes memory messageBytes = abi.encodePacked(
			_signData.tokenUri,
			_signData.nonce, 
			_signData.payloadHash, 
			uint160(address(addr)),
			Strings.toString(tokenId)
		);
		bytes memory message = abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(messageBytes.length), messageBytes);
		signedHash = keccak256(message);
   	signer = signedHash.recover(_signData.signature);
    tokenUri = _signData.tokenUri;
    require(signedBy == signer, 'invsign');
	}

	function verifySignatureData(bytes memory _data, address addr, uint tokenId, address signedBy) public pure returns(address signer, bytes32 signedHash, string memory tokenUri) {
    SignData memory _signData = abi.decode(_data, (SignData));
    return verifySignature(_signData, addr, tokenId, signedBy);
	}

	function verifyXTransfer(TransferData memory _xferData, address addr, uint tokenId, address signedBy) public returns(bytes32 signedHash) {
		bytes memory messageBytes = abi.encodePacked(
			uint160(address(addr)),
			_xferData.data,
			Strings.toString(tokenId) 
		);
		bytes memory message = abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(messageBytes.length), messageBytes);
		signedHash = keccak256(message);
   	address signer = signedHash.recover(_xferData.signature);
    require(signedBy == signer, 'invsign');
    emit xTransferEvent(
      msg.sender,
      tokenId,
      addr,
      _xferData.data
    );
	}

	function verifyXTransferData(bytes memory _data, address addr, uint tokenId, address signedBy) public returns(uint) {
    TransferData memory _transferData = abi.decode(_data, (TransferData));
    require(!_expired(_transferData.expires), 'expired');
    verifyXTransfer(_transferData, addr, tokenId, signedBy);
    return _transferData.fee;
	}

	function verifyXReturn(ReturnData memory _xretData, address addr, uint tokenId, address signedBy) public returns(bytes32 signedHash) {
		bytes memory messageBytes = abi.encodePacked(
			uint160(address(addr)),
      _xretData.ordinal,
			_xretData.data,
			Strings.toString(tokenId) 
		);
		bytes memory message = abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(messageBytes.length), messageBytes);
		signedHash = keccak256(message);
   	address signer = signedHash.recover(_xretData.signature);
    require(signedBy == signer, 'invsign');
    emit xReturnEvent(
      msg.sender,
      tokenId,
      addr,
      _xretData.ordinal,
      _xretData.data
    );
	}

  function _expired(uint when) internal view returns(bool) {
    return block.timestamp > when;
  }

	function verifyXReturnData(bytes memory _data, address addr, uint tokenId, address signedBy) public returns(uint) {
    ReturnData memory _xretData = abi.decode(_data, (ReturnData));
    require(!_expired(_xretData.expires), 'expired');
    verifyXReturn(_xretData, addr, tokenId, signedBy);
    return _xretData.fee;
	}

	function toHexString(uint a) internal pure returns (string memory) {
   	uint count = 0;
   	uint b = a;
   	while (b != 0) {
      count++;
      b /= 16;
    }
    bytes memory res = new bytes(count);
    for (uint i=0; i<count; ++i) {
       b = a % 16;
       res[count - i - 1] = bytes1(toHexDigit(uint8(b)));
       a /= 16;
    }
    return string(res);
	}

	function toHexDigit(uint8 d) pure internal returns (uint8) {
   	if (0 <= d && d <= 9) {
     	return uint8(bytes1('0')) + d;
   	} else if (10 <= uint8(d) && uint8(d) <= 15) {
       return uint8(bytes1('a')) + d - 10;
   	}
   	revert();
	}

	function generateContractJson(ContractData memory cd) public pure returns (string memory) {
		bytes memory name = abi.encodePacked('"name":"', cd.desc, '", ');
		bytes memory image = abi.encodePacked('"image":"', cd.osImage, '", ');
		bytes memory banner = abi.encodePacked('"banner":"', cd.osBanner, '", ');
		bytes memory description = abi.encodePacked('"description":"', cd.osDescription, '", ');
		bytes memory external_link = abi.encodePacked('"external_link":"', cd.osExternalLink, '", ');
		bytes memory addr = abi.encodePacked('0x', toHexString(uint(uint160(address(cd.beneficiary)))));
		bytes memory fee_recipient = abi.encodePacked('"fee_recipient":"', addr , '", ');
		bytes memory seller_fee_basis_points = abi.encodePacked('"seller_fee_basis_points":', Strings.toString(cd.royalty));
		string memory b64 = Base64.encode(abi.encodePacked('{', name, image, banner, description, external_link, fee_recipient, seller_fee_basis_points, '}'));
		return string(abi.encodePacked('data:application/json;base64,', b64));
	}

}

/contracts/Base64.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

library Base64 {
    bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /// @notice Encodes some bytes to the base64 representation
    function encode(bytes memory data) internal pure returns (string memory) {
        uint256 len = data.length;
        if (len == 0) return "";

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

        // Add some extra buffer at the end
        bytes memory result = new bytes(encodedLen + 32);

        bytes memory table = TABLE;

        assembly {
            let tablePtr := add(table, 1)
            let resultPtr := add(result, 32)

            for {
                let i := 0
            } lt(i, len) {

            } {
                i := add(i, 3)
                let input := and(mload(add(data, i)), 0xffffff)

                let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
                out := shl(8, out)
                out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
                out := shl(8, out)
                out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
                out := shl(8, out)
                out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
                out := shl(224, out)

                mstore(resultPtr, out)

                resultPtr := add(resultPtr, 4)
            }

            switch mod(len, 3)
            case 1 {
                mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
            }
            case 2 {
                mstore(sub(resultPtr, 1), shl(248, 0x3d))
            }

            mstore(result, encodedLen)
        }

        return string(result);
    }
}

@openzeppelin/contracts/utils/Strings.sol

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

pragma solidity ^0.8.0;

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

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        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_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        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);
    }
}

@openzeppelin/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.3) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.