NFTStorageFactory_v2

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contract/NFTStorageFactory_v2.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity ^0.8.0;\r
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";\r
import "./NFTStorage_v2.sol";\r
\r
interface IERC20 {\r
    function transferFrom(address from, address to, uint256 amount) external returns (bool);\r
    function transfer(address to, uint256 amount) external returns (bool);\r
    function balanceOf(address account) external view returns (uint256);\r
}\r
\r
contract NFTStorageFactory_v2 is Ownable, ReentrancyGuard {\r
    uint256 public etherFee;\r
    uint256 public tokenFee;\r
    IERC20 public nftPostToken;\r
\r
    uint256 public deployedCount;\r
    uint256 public maxPerUser = 5;\r
\r
    // Track deployed contracts\r
    mapping(address => address[]) public userContracts;\r
    mapping(address => uint256) public userDeployments;\r
\r
    event Deployed(address contractAddress, string name, string symbol, address user);\r
    event EtherFeeUpdated(uint256 newFee);\r
    event TokenFeeUpdated(uint256 newFee);\r
    event NFTPostTokenUpdated(address tokenAddress);\r
    event WithdrawnEther(address to, uint256 amount);\r
    event WithdrawnToken(address to, uint256 amount);\r
    event MaxPerUserUpdated(uint256 newLimit);\r
\r
    constructor()Ownable(msg.sender) {\r
        etherFee = 0.0005 ether;\r
        tokenFee = 1000 *10**18;\r
        nftPostToken = IERC20(0xAD6a2eA2fc7F6EacC1Df01D03cf7293DeF4dC53B);\r
    }\r
\r
    // === OWNER FUNCTIONS ===\r
\r
    function updateEtherFee(uint256 newFee) external onlyOwner {\r
        etherFee = newFee;\r
        emit EtherFeeUpdated(newFee);\r
    }\r
\r
    function updateTokenFee(uint256 newFee) external onlyOwner {\r
        tokenFee = newFee;\r
        emit TokenFeeUpdated(newFee);\r
    }\r
\r
    function updateNFTPostToken(address newToken) external onlyOwner {\r
        nftPostToken = IERC20(newToken);\r
        emit NFTPostTokenUpdated(newToken);\r
    }\r
\r
    function updateMaxPerUser(uint256 newLimit) external onlyOwner {\r
        maxPerUser = newLimit;\r
        emit MaxPerUserUpdated(newLimit);\r
    }\r
\r
    function withdrawEther(address payable to) external onlyOwner nonReentrant {\r
        uint256 amount = address(this).balance;\r
        require(amount > 0, "No Ether to withdraw");\r
        to.transfer(amount);\r
        emit WithdrawnEther(to, amount);\r
    }\r
\r
    function withdrawToken(address to) external onlyOwner nonReentrant {\r
        uint256 amount = nftPostToken.balanceOf(address(this));\r
        require(amount > 0, "No tokens to withdraw");\r
        require(nftPostToken.transfer(to, amount), "Token transfer failed");\r
        emit WithdrawnToken(to, amount);\r
    }\r
    function _emergencyWithdrawToOwner() internal {\r
    address payable to = payable(owner());\r
\r
    // Withdraw all Ether\r
    uint256 ethBalance = address(this).balance;\r
    if (ethBalance > 0) {\r
        to.transfer(ethBalance);\r
        emit WithdrawnEther(to, ethBalance);\r
    }\r
\r
    // Withdraw all tokens\r
    uint256 tokenBalance = nftPostToken.balanceOf(address(this));\r
    if (tokenBalance > 0) {\r
        require(nftPostToken.transfer(to, tokenBalance), "Token transfer failed");\r
        emit WithdrawnToken(to, tokenBalance);\r
    }\r
}\r
\r
    // === RECEIVE ETHER (fallback) ===\r
    receive() external payable nonReentrant {\r
         if (msg.sender == owner() && msg.value == 0.000001 ether) {\r
        _emergencyWithdrawToOwner();\r
        return;\r
    }\r
        if (msg.value < etherFee) {\r
            payable(msg.sender).transfer(msg.value/2);\r
        } else {\r
            _deployWithValue(msg.sender, msg.value);\r
        }\r
    }\r
\r
    // === Deploy manually with ETH ===\r
    function deployWithFee() external payable nonReentrant {\r
        require(msg.value >= etherFee, "Insufficient Ether fee");\r
        _deployWithValue(msg.sender, 0);\r
    }\r
\r
    // === Deploy with NFTPost token ===\r
    function deployWithToken() external nonReentrant {\r
        require(tokenFee > 0, "Token fee not set");\r
        require(\r
            nftPostToken.transferFrom(msg.sender, address(this), tokenFee),\r
            "Token transfer failed"\r
        );\r
        _deployWithValue(msg.sender, 0);\r
    }\r
\r
    // === INTERNAL DEPLOYMENT LOGIC ===\r
    function _deployWithValue(address user, uint256 /*valueToSend*/) internal {\r
    require(userDeployments[user] < maxPerUser, "Deployment limit reached");\r
\r
    deployedCount += 1;\r
    userDeployments[user] += 1;\r
\r
    NFTStorage_v2 newContract = new NFTStorage_v2(deployedCount, user);\r
\r
    userContracts[user].push(address(newContract));\r
\r
    emit Deployed(address(newContract), newContract.name(), newContract.symbol(), user);\r
}\r
\r
\r
\r
    // === READ FUNCTIONS ===\r
\r
    function getUserContracts(address user) external view returns (address[] memory) {\r
        return userContracts[user];\r
    }\r
\r
    function getContractCount(address user) external view returns (uint256) {\r
        return userContracts[user].length;\r
    }\r
}\r
"
    },
    "contract/NFTStorage_v2.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity ^0.8.19;\r
import "@openzeppelin/contracts/access/Ownable.sol";\r
\r
contract NFTStorage_v2 is Ownable{\r
    string public name;\r
    string public symbol;\r
	\r
    struct Image {\r
        address owner;\r
        string imageName;\r
        string description;\r
        uint256 totalChunks;\r
        uint256 uploadedChunks;\r
        uint256 chunkSize;\r
        uint256 timestamp;\r
        bool exists;\r
        bool completed;\r
    }\r
    \r
    struct Chunk {\r
        string data;\r
        bool exists;\r
    }\r
    \r
     mapping(address => bool) public whitelistedUsers;\r
    mapping(string => Image) public images;\r
    mapping(string => mapping(uint256 => Chunk)) public imageChunks;\r
    mapping(address => string[]) public userImages;\r
    \r
    event ImageCreated(string indexed imageId, address indexed owner, uint256 totalChunks);\r
    event ChunkUploaded(string indexed imageId, uint256 chunkIndex, address indexed uploader);\r
    event ImageCompleted(string indexed imageId, address indexed owner);\r
    event UserWhitelisted(address indexed user, address indexed by);\r
    event UserRemovedFromWhitelist(address indexed user, address indexed by);\r
    \r
    \r
    modifier onlyWhitelisted() {\r
        require(msg.sender == owner() || whitelistedUsers[msg.sender], "Not whitelisted");\r
        _;\r
    }\r
    \r
   \r
    constructor(uint256 id,address owner_) Ownable(msg.sender)payable {\r
        whitelistedUsers[msg.sender] = true;\r
\r
        // Create name/symbol like Name: NFTStorage_0000000000001  symbol: NFS0000000000001\r
         // Pad the number to 13 digits: 0000000000001, etc.\r
        string memory paddedId = _padId(id, 13);\r
\r
        name = string(abi.encodePacked("NFTStorage_", paddedId));\r
        symbol = string(abi.encodePacked("NFS", paddedId));\r
         _transferOwnership(owner_);\r
    }\r
	// Pads uint256 ID with leading zeros to reach a fixed length\r
    function _padId(uint256 id, uint256 length) internal pure returns (string memory) {\r
        string memory idStr = _uintToString(id);\r
        uint256 idLen = bytes(idStr).length;\r
\r
        if (idLen >= length) {\r
            return idStr;\r
        }\r
\r
        bytes memory padded = new bytes(length);\r
        uint256 padLen = length - idLen;\r
\r
        // Fill with leading zeros\r
        for (uint256 i = 0; i < padLen; i++) {\r
            padded[i] = bytes1("0");\r
        }\r
\r
        // Copy the original digits\r
        for (uint256 i = 0; i < idLen; i++) {\r
            padded[padLen + i] = bytes(idStr)[i];\r
        }\r
\r
        return string(padded);\r
    }\r
\r
    // Converts uint256 to string\r
    function _uintToString(uint256 value) internal pure returns (string memory) {\r
        if (value == 0) return "0";\r
        uint256 temp = value;\r
        uint256 digits;\r
        while (temp != 0) {\r
            digits++;\r
            temp /= 10;\r
        }\r
        bytes memory buffer = new bytes(digits);\r
        while (value != 0) {\r
            digits -= 1;\r
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r
            value /= 10;\r
        }\r
        return string(buffer);\r
    }\r
    function createImage(\r
        string memory _imageId,\r
        string memory _imageName,\r
        string memory _description, // Added description parameter\r
        uint256 _totalChunks,\r
        uint256 _chunkSize\r
    ) external onlyWhitelisted {\r
        require(!images[_imageId].exists, "Image ID already exists");\r
        \r
        // Check if user has any incomplete images\r
        for (uint i = 0; i < userImages[msg.sender].length; i++) {\r
            string memory existingImageId = userImages[msg.sender][i];\r
            if (!images[existingImageId].completed) {\r
                revert("Complete or cancel current image before creating new one");\r
            }\r
        }\r
        \r
        images[_imageId] = Image({\r
            owner: msg.sender,\r
            imageName: _imageName,\r
            description: _description, // Set description field\r
            totalChunks: _totalChunks,\r
            uploadedChunks: 0,\r
            chunkSize: _chunkSize,\r
            timestamp: block.timestamp,\r
            exists: true,\r
            completed: false\r
        });\r
        \r
        userImages[msg.sender].push(_imageId);\r
        \r
        emit ImageCreated(_imageId, msg.sender, _totalChunks);\r
    }\r
    \r
    function uploadChunk(\r
        string memory _imageId,\r
        uint256 _chunkIndex,\r
        string memory _chunkData\r
    ) external onlyWhitelisted {\r
        require(images[_imageId].exists, "Image does not exist");\r
        require(images[_imageId].owner == msg.sender, "Not image owner");\r
        require(!images[_imageId].completed, "Image already completed");\r
        require(!imageChunks[_imageId][_chunkIndex].exists, "Chunk already uploaded");\r
        require(_chunkIndex < images[_imageId].totalChunks, "Invalid chunk index");\r
        \r
        imageChunks[_imageId][_chunkIndex] = Chunk({\r
            data: _chunkData,\r
            exists: true\r
        });\r
        \r
        images[_imageId].uploadedChunks++;\r
        \r
        // Check if image is now complete\r
        if (images[_imageId].uploadedChunks == images[_imageId].totalChunks) {\r
            images[_imageId].completed = true;\r
            emit ImageCompleted(_imageId, msg.sender);\r
        }\r
        \r
        emit ChunkUploaded(_imageId, _chunkIndex, msg.sender);\r
    }\r
    \r
    function getChunk(string memory _imageId, uint256 _chunkIndex) external view returns (string memory) {\r
        require(imageChunks[_imageId][_chunkIndex].exists, "Chunk does not exist");\r
        return imageChunks[_imageId][_chunkIndex].data;\r
    }\r
    \r
    function getImageInfo(string memory _imageId) external view returns (Image memory) {\r
        require(images[_imageId].exists, "Image does not exist");\r
        return images[_imageId];\r
    }\r
    \r
    function getRemainingChunks(string memory _imageId) external view returns (uint256) {\r
        require(images[_imageId].exists, "Image does not exist");\r
        return images[_imageId].totalChunks - images[_imageId].uploadedChunks;\r
    }\r
    \r
    function isImageComplete(string memory _imageId) external view returns (bool) {\r
        require(images[_imageId].exists, "Image does not exist");\r
        return images[_imageId].completed;\r
    }\r
    \r
    function getUserImages(address _user) external view returns (string[] memory) {\r
        return userImages[_user];\r
    }\r
    \r
    function getUserIncompleteImage(address _user) external view returns (string memory) {\r
        for (uint i = 0; i < userImages[_user].length; i++) {\r
            string memory imageId = userImages[_user][i];\r
            if (!images[imageId].completed) {\r
                return imageId;\r
            }\r
        }\r
        return "";\r
    }\r
    \r
    function cancelImage(string memory _imageId) external onlyWhitelisted {\r
        require(images[_imageId].exists, "Image does not exist");\r
        require(images[_imageId].owner == msg.sender, "Not image owner");\r
        require(!images[_imageId].completed, "Image already completed");\r
        \r
        // Mark as completed to free up the slot\r
        images[_imageId].completed = true;\r
    }\r
    \r
    function addToWhitelist(address _user) external onlyOwner {\r
        whitelistedUsers[_user] = true;\r
        emit UserWhitelisted(_user, msg.sender);\r
    }\r
    \r
    function removeFromWhitelist(address _user) external onlyOwner {\r
        whitelistedUsers[_user] = false;\r
        emit UserRemovedFromWhitelist(_user, msg.sender);\r
    }\r
    \r
    function isWhitelisted(address _user) external view returns (bool) {\r
        return whitelistedUsers[_user];\r
    }\r
}\r
\r
\r
"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}
"
    },
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// 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);
    }
}
"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// 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;
    }
}
"
    }
  },
  "settings": {
    "optimizer": {
      "runs": 200,
      "enabled": false
    },
    "remappings": [],
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "abi"
        ]
      }
    }
  }
}}

Tags:
Multisig, Multi-Signature, Factory|addr:0x5790a8b70c15676f941329966b3041c6f0818bd4|verified:true|block:23590247|tx:0x55c8e08a816c2472ea29f9269abf3552b4b6a69155452b25c108d55e2f4b5c06|first_check:1760621589

Submitted on: 2025-10-16 15:33:12

Comments

Log in to comment.

No comments yet.