More Info
Private Name Tags
ContractCreator
Latest 25 from a total of 10,684 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Proxy Create Pro... | 59092167 | 155 days ago | IN | 0 POL | 0.01682275 | ||||
Proxy Create Pro... | 59063365 | 155 days ago | IN | 0 POL | 0.01119564 | ||||
Proxy Create Pro... | 59053658 | 156 days ago | IN | 0 POL | 0.01120521 | ||||
Proxy Create Pro... | 59052125 | 156 days ago | IN | 0 POL | 0.01173497 | ||||
Proxy Create Pro... | 59047300 | 156 days ago | IN | 0 POL | 0.01117404 | ||||
Proxy Create Pro... | 59037952 | 156 days ago | IN | 0 POL | 0.01120095 | ||||
Proxy Create Pro... | 58790887 | 162 days ago | IN | 0 POL | 0.01229688 | ||||
Proxy Create Pro... | 58753216 | 163 days ago | IN | 0 POL | 0.01117935 | ||||
Proxy Create Pro... | 58699690 | 165 days ago | IN | 0 POL | 0.01119404 | ||||
Proxy Create Pro... | 58683132 | 165 days ago | IN | 0 POL | 0.01115775 | ||||
Proxy Create Pro... | 58673575 | 165 days ago | IN | 0 POL | 0.01119882 | ||||
Proxy Create Pro... | 58664135 | 165 days ago | IN | 0 POL | 0.01118685 | ||||
Proxy Create Pro... | 58662834 | 165 days ago | IN | 0 POL | 0.01115315 | ||||
Proxy Create Pro... | 58634123 | 166 days ago | IN | 0 POL | 0.01122042 | ||||
Proxy Create Pro... | 58633551 | 166 days ago | IN | 0 POL | 0.01115775 | ||||
Proxy Create Pro... | 58631145 | 166 days ago | IN | 0 POL | 0.01116819 | ||||
Proxy Create Pro... | 58630690 | 166 days ago | IN | 0 POL | 0.01118661 | ||||
Proxy Create Pro... | 58585956 | 167 days ago | IN | 0 POL | 0.01323195 | ||||
Proxy Create Pro... | 58575843 | 168 days ago | IN | 0 POL | 0.02539441 | ||||
Proxy Create Pro... | 58516986 | 169 days ago | IN | 0 POL | 0.01117935 | ||||
Proxy Create Pro... | 58479323 | 170 days ago | IN | 0 POL | 0.01116759 | ||||
Proxy Create Pro... | 58478577 | 170 days ago | IN | 0 POL | 0.01115729 | ||||
Proxy Create Pro... | 58475085 | 170 days ago | IN | 0 POL | 0.01116855 | ||||
Proxy Create Pro... | 58474471 | 170 days ago | IN | 0 POL | 0.01115775 | ||||
Proxy Create Pro... | 58471230 | 170 days ago | IN | 0 POL | 0.01117935 |
Loading...
Loading
This contract contains unverified libraries: ActionLib, GovernanceLib
Contract Name:
ProfileCreationProxy
Compiler Version
v0.8.21+commit.d9974bed
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {ILensHub} from 'contracts/interfaces/ILensHub.sol'; import {LensV2Migration} from 'contracts/misc/LensV2Migration.sol'; import {Types} from 'contracts/libraries/constants/Types.sol'; import {ImmutableOwnable} from 'contracts/misc/ImmutableOwnable.sol'; import {ILensHandles} from 'contracts/interfaces/ILensHandles.sol'; import {ITokenHandleRegistry} from 'contracts/interfaces/ITokenHandleRegistry.sol'; /** * @title ProfileCreationProxy * @author Lens Protocol * * @notice This is an ownable proxy contract that enforces ".lens" handle suffixes at profile creation. * Only the owner can create profiles. */ contract ProfileCreationProxy is ImmutableOwnable { ILensHandles immutable LENS_HANDLES; ITokenHandleRegistry immutable TOKEN_HANDLE_REGISTRY; error ProfileAlreadyExists(); constructor( address owner, address hub, address lensHandles, address tokenHandleRegistry ) ImmutableOwnable(owner, hub) { LENS_HANDLES = ILensHandles(lensHandles); TOKEN_HANDLE_REGISTRY = ITokenHandleRegistry(tokenHandleRegistry); } function proxyCreateProfile( Types.CreateProfileParams calldata createProfileParams ) external onlyOwner returns (uint256) { return ILensHub(LENS_HUB).createProfile(createProfileParams); } function proxyCreateProfileWithHandle( Types.CreateProfileParams memory createProfileParams, string calldata handle ) external onlyOwner returns (uint256, uint256) { // Check if LensHubV1 already has a profile with this handle that was not migrated yet: bytes32 handleHash = keccak256(bytes(string.concat(handle, '.lens'))); if (LensV2Migration(LENS_HUB).getProfileIdByHandleHash(handleHash) != 0) { revert ProfileAlreadyExists(); } // We mint the handle & profile to this contract first, then link it to the profile // This will not allow to initialize follow modules that require funds from the msg.sender, // but we assume only simple follow modules should be set during profile creation. // Complex ones can be set after the profile is created. address destination = createProfileParams.to; createProfileParams.to = address(this); uint256 profileId = ILensHub(LENS_HUB).createProfile(createProfileParams); uint256 handleId = LENS_HANDLES.mintHandle(address(this), handle); TOKEN_HANDLE_REGISTRY.link({handleId: handleId, profileId: profileId}); // Transfer the handle & profile to the destination LENS_HANDLES.transferFrom(address(this), destination, handleId); ILensHub(LENS_HUB).transferFrom(address(this), destination, profileId); return (profileId, handleId); } function proxyCreateHandle(address to, string calldata handle) external onlyOwner returns (uint256) { return LENS_HANDLES.mintHandle(to, handle); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Types} from 'contracts/libraries/constants/Types.sol'; import {ERC2981CollectionRoyalties} from 'contracts/base/ERC2981CollectionRoyalties.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {HubRestricted} from 'contracts/base/HubRestricted.sol'; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import {IERC721Timestamped} from 'contracts/interfaces/IERC721Timestamped.sol'; import {IFollowNFT} from 'contracts/interfaces/IFollowNFT.sol'; import {ILensHub} from 'contracts/interfaces/ILensHub.sol'; import {LensBaseERC721} from 'contracts/base/LensBaseERC721.sol'; import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import {StorageLib} from 'contracts/libraries/StorageLib.sol'; import {FollowTokenURILib} from 'contracts/libraries/token-uris/FollowTokenURILib.sol'; import {Types} from 'contracts/libraries/constants/Types.sol'; /** * @custom:upgradeable Beacon proxy. The beacon, responsible for returning the implementation address, is the LensHub. */ contract FollowNFT is HubRestricted, LensBaseERC721, ERC2981CollectionRoyalties, IFollowNFT { using Strings for uint256; string constant FOLLOW_NFT_NAME_SUFFIX = '-Follower'; string constant FOLLOW_NFT_SYMBOL_SUFFIX = '-Fl'; uint256[5] ___DEPRECATED_SLOTS; // Deprecated slots, previously used for delegations. uint256 internal _followedProfileId; // Old uint256 `_lastFollowTokenId` slot splitted into two uint128s to include `_followerCount`. uint128 internal _lastFollowTokenId; // `_followerCount` will not be decreased when a follower profile is burned, making the counter not fully accurate. // New variable added in V2 in the same slot, lower-ordered to not conflict with previous storage layout. uint128 internal _followerCount; bool private _initialized; // Introduced in v2 mapping(uint256 => Types.FollowData) internal _followDataByFollowTokenId; mapping(uint256 => uint256) internal _followTokenIdByFollowerProfileId; mapping(uint256 => uint256) internal _followApprovalByFollowTokenId; uint256 internal _royaltiesInBasisPoints; event FollowApproval(uint256 indexed followerProfileId, uint256 indexed followTokenId); modifier whenNotPaused() { if (ILensHub(HUB).getState() == Types.ProtocolState.Paused) { revert Errors.Paused(); } _; } constructor(address hub) HubRestricted(hub) { _initialized = true; } /// @inheritdoc IFollowNFT function initialize(uint256 profileId) external override { // This is called right after deployment by the LensHub, so we can skip the onlyHub check. if (_initialized) { revert Errors.Initialized(); } _initialized = true; _followedProfileId = profileId; _setRoyalty(1000); // 10% of royalties } /// @inheritdoc IFollowNFT function follow( uint256 followerProfileId, address transactionExecutor, uint256 followTokenId ) external override onlyHub returns (uint256) { if (_followTokenIdByFollowerProfileId[followerProfileId] != 0) { revert AlreadyFollowing(); } if (followTokenId == 0) { // Fresh follow. return _followMintingNewToken(followerProfileId); } address followTokenOwner = _unsafeOwnerOf(followTokenId); if (followTokenOwner != address(0)) { // Provided follow token is wrapped. return _followWithWrappedToken({ followerProfileId: followerProfileId, transactionExecutor: transactionExecutor, followTokenId: followTokenId }); } uint256 currentFollowerProfileId = _followDataByFollowTokenId[followTokenId].followerProfileId; if (currentFollowerProfileId != 0) { // Provided follow token is unwrapped. // It has a follower profile set already, it can only be used to follow if that profile was burnt. return _followWithUnwrappedTokenFromBurnedProfile({ followerProfileId: followerProfileId, followTokenId: followTokenId, currentFollowerProfileId: currentFollowerProfileId, transactionExecutor: transactionExecutor }); } // Provided follow token does not exist anymore, it can only be used if the profile attempting to follow is // allowed to recover it. return _followByRecoveringToken({followerProfileId: followerProfileId, followTokenId: followTokenId}); } /// @inheritdoc IFollowNFT function unfollow(uint256 unfollowerProfileId) external override onlyHub { uint256 followTokenId = _followTokenIdByFollowerProfileId[unfollowerProfileId]; if (followTokenId == 0) { revert NotFollowing(); } address followTokenOwner = _unsafeOwnerOf(followTokenId); // LensHub already validated that this action can only be performed by the unfollower profile's owner or one of // his approved delegated executors. _unfollow({unfollower: unfollowerProfileId, followTokenId: followTokenId}); if (followTokenOwner == address(0)) { // Follow token was unwrapped, allowing recovery. _followDataByFollowTokenId[followTokenId].profileIdAllowedToRecover = unfollowerProfileId; } } /// @inheritdoc IFollowNFT function removeFollower(uint256 followTokenId) external override whenNotPaused { if (_isApprovedOrOwner(msg.sender, followTokenId)) { _unfollowIfHasFollower(followTokenId, msg.sender); } else { revert DoesNotHavePermissions(); } } /// @inheritdoc IFollowNFT function approveFollow(uint256 followerProfileId, uint256 followTokenId) external override { if (!IERC721Timestamped(HUB).exists(followerProfileId)) { revert Errors.TokenDoesNotExist(); } // `followTokenId` allowed to be zero as a way to clear the approval. if (followTokenId != 0 && _unsafeOwnerOf(followTokenId) == address(0)) { revert OnlyWrappedFollowTokens(); } if (_isApprovedOrOwner(msg.sender, followTokenId)) { _approveFollow(followerProfileId, followTokenId); } else { revert DoesNotHavePermissions(); } } /// @inheritdoc IFollowNFT function wrap(uint256 followTokenId, address wrappedTokenReceiver) external override whenNotPaused { if (wrappedTokenReceiver == address(0)) { revert Errors.InvalidParameter(); } _wrap(followTokenId, wrappedTokenReceiver); } /// @inheritdoc IFollowNFT function wrap(uint256 followTokenId) external override whenNotPaused { _wrap(followTokenId, address(0)); } function _wrap(uint256 followTokenId, address wrappedTokenReceiver) internal { if (_isFollowTokenWrapped(followTokenId)) { revert AlreadyWrapped(); } uint256 followerProfileId = _followDataByFollowTokenId[followTokenId].followerProfileId; if (followerProfileId == 0) { followerProfileId = _followDataByFollowTokenId[followTokenId].profileIdAllowedToRecover; if (followerProfileId == 0) { revert FollowTokenDoesNotExist(); } delete _followDataByFollowTokenId[followTokenId].profileIdAllowedToRecover; } address followerProfileOwner = IERC721(HUB).ownerOf(followerProfileId); if (msg.sender != followerProfileOwner) { revert DoesNotHavePermissions(); } _mint(wrappedTokenReceiver == address(0) ? followerProfileOwner : wrappedTokenReceiver, followTokenId); } /// @inheritdoc IFollowNFT function unwrap(uint256 followTokenId) external override whenNotPaused { if (_followDataByFollowTokenId[followTokenId].followerProfileId == 0) { revert NotFollowing(); } super.burn(followTokenId); } /// @inheritdoc IFollowNFT function processBlock(uint256 followerProfileId) external override onlyHub returns (bool) { bool hasUnfollowed; uint256 followTokenId = _followTokenIdByFollowerProfileId[followerProfileId]; if (followTokenId != 0) { if (!_isFollowTokenWrapped(followTokenId)) { // Wrap it first, so the user stops following but does not lose the token when being blocked. _mint(IERC721(HUB).ownerOf(followerProfileId), followTokenId); } _unfollow(followerProfileId, followTokenId); hasUnfollowed = true; } return hasUnfollowed; } /// @inheritdoc IFollowNFT function getFollowerProfileId(uint256 followTokenId) external view override returns (uint256) { return _followDataByFollowTokenId[followTokenId].followerProfileId; } /// @inheritdoc IFollowNFT function isFollowing(uint256 followerProfileId) external view override returns (bool) { return _followTokenIdByFollowerProfileId[followerProfileId] != 0; } /// @inheritdoc IFollowNFT function getFollowTokenId(uint256 followerProfileId) external view override returns (uint256) { return _followTokenIdByFollowerProfileId[followerProfileId]; } /// @inheritdoc IFollowNFT function getOriginalFollowTimestamp(uint256 followTokenId) external view override returns (uint256) { return _followDataByFollowTokenId[followTokenId].originalFollowTimestamp; } /// @inheritdoc IFollowNFT function getFollowTimestamp(uint256 followTokenId) external view override returns (uint256) { return _followDataByFollowTokenId[followTokenId].followTimestamp; } /// @inheritdoc IFollowNFT function getProfileIdAllowedToRecover(uint256 followTokenId) external view override returns (uint256) { return _followDataByFollowTokenId[followTokenId].profileIdAllowedToRecover; } /// @inheritdoc IFollowNFT function getFollowData(uint256 followTokenId) external view override returns (Types.FollowData memory) { return _followDataByFollowTokenId[followTokenId]; } /// @inheritdoc IFollowNFT function getFollowApproved(uint256 followTokenId) external view override returns (uint256) { return _followApprovalByFollowTokenId[followTokenId]; } /// @inheritdoc IFollowNFT function getFollowerCount() external view override returns (uint256) { return _followerCount; } function burn(uint256 followTokenId) public override whenNotPaused { _unfollowIfHasFollower(followTokenId, msg.sender); super.burn(followTokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(LensBaseERC721, ERC2981CollectionRoyalties) returns (bool) { return LensBaseERC721.supportsInterface(interfaceId) || ERC2981CollectionRoyalties.supportsInterface(interfaceId); } function name() public view override returns (string memory) { return string(abi.encodePacked(_followedProfileId.toString(), FOLLOW_NFT_NAME_SUFFIX)); } function symbol() public view override returns (string memory) { return string(abi.encodePacked(_followedProfileId.toString(), FOLLOW_NFT_SYMBOL_SUFFIX)); } /** * @dev This returns the follow NFT URI fetched from the hub. */ function tokenURI(uint256 followTokenId) public view override returns (string memory) { if (!_exists(followTokenId)) { revert Errors.TokenDoesNotExist(); } return FollowTokenURILib.getTokenURI( followTokenId, _followedProfileId, _followDataByFollowTokenId[followTokenId].originalFollowTimestamp ); } function _followMintingNewToken(uint256 followerProfileId) internal returns (uint256) { uint256 followTokenIdAssigned; unchecked { followTokenIdAssigned = ++_lastFollowTokenId; _followerCount++; } _baseFollow({ followerProfileId: followerProfileId, followTokenId: followTokenIdAssigned, isOriginalFollow: true }); return followTokenIdAssigned; } function _followWithWrappedToken( uint256 followerProfileId, address transactionExecutor, uint256 followTokenId ) internal returns (uint256) { bool isFollowApproved = _followApprovalByFollowTokenId[followTokenId] == followerProfileId; address followerProfileOwner = IERC721(HUB).ownerOf(followerProfileId); if ( !isFollowApproved && !_isApprovedOrOwner(followerProfileOwner, followTokenId) && !_isApprovedOrOwner(transactionExecutor, followTokenId) ) { revert DoesNotHavePermissions(); } // The transactionExecutor is allowed to write the follower in that wrapped token. if (isFollowApproved) { // The `_followApprovalByFollowTokenId` was used, and now it needs to be cleared. _approveFollow(0, followTokenId); } _replaceFollower({ currentFollowerProfileId: _followDataByFollowTokenId[followTokenId].followerProfileId, newFollowerProfileId: followerProfileId, followTokenId: followTokenId, transactionExecutor: transactionExecutor }); return followTokenId; } function _followWithUnwrappedTokenFromBurnedProfile( uint256 followerProfileId, uint256 followTokenId, uint256 currentFollowerProfileId, address transactionExecutor ) internal returns (uint256) { if (IERC721Timestamped(HUB).exists(currentFollowerProfileId)) { revert DoesNotHavePermissions(); } _replaceFollower({ currentFollowerProfileId: currentFollowerProfileId, newFollowerProfileId: followerProfileId, followTokenId: followTokenId, transactionExecutor: transactionExecutor }); return followTokenId; } function _followByRecoveringToken(uint256 followerProfileId, uint256 followTokenId) internal returns (uint256) { if (_followDataByFollowTokenId[followTokenId].profileIdAllowedToRecover != followerProfileId) { revert FollowTokenDoesNotExist(); } unchecked { _followerCount++; } _baseFollow({followerProfileId: followerProfileId, followTokenId: followTokenId, isOriginalFollow: false}); return followTokenId; } function _replaceFollower( uint256 currentFollowerProfileId, uint256 newFollowerProfileId, uint256 followTokenId, address transactionExecutor ) internal { if (currentFollowerProfileId != 0) { // As it has a follower, unfollow first, removing the current follower. delete _followTokenIdByFollowerProfileId[currentFollowerProfileId]; ILensHub(HUB).emitUnfollowedEvent(currentFollowerProfileId, _followedProfileId, transactionExecutor); } else { unchecked { _followerCount++; } } // Perform the follow, setting a new follower. _baseFollow({followerProfileId: newFollowerProfileId, followTokenId: followTokenId, isOriginalFollow: false}); } function _baseFollow(uint256 followerProfileId, uint256 followTokenId, bool isOriginalFollow) internal { _followTokenIdByFollowerProfileId[followerProfileId] = followTokenId; _followDataByFollowTokenId[followTokenId].followerProfileId = uint160(followerProfileId); _followDataByFollowTokenId[followTokenId].followTimestamp = uint48(block.timestamp); delete _followDataByFollowTokenId[followTokenId].profileIdAllowedToRecover; if (isOriginalFollow) { _followDataByFollowTokenId[followTokenId].originalFollowTimestamp = uint48(block.timestamp); } else { // Migration code. // If the follow token was minted before the originalFollowTimestamp was introduced, it will be 0. // In that case, we need to fetch the mint timestamp from the token data. if (_followDataByFollowTokenId[followTokenId].originalFollowTimestamp == 0) { uint48 mintTimestamp = uint48(StorageLib.getTokenData(followTokenId).mintTimestamp); _followDataByFollowTokenId[followTokenId].originalFollowTimestamp = mintTimestamp; } } } function _unfollowIfHasFollower(uint256 followTokenId, address transactionExecutor) internal { uint256 followerProfileId = _followDataByFollowTokenId[followTokenId].followerProfileId; if (followerProfileId != 0) { _unfollow(followerProfileId, followTokenId); ILensHub(HUB).emitUnfollowedEvent(followerProfileId, _followedProfileId, transactionExecutor); } } function _unfollow(uint256 unfollower, uint256 followTokenId) internal { unchecked { // This is safe, as this line can only be reached if the unfollowed profile is being followed by the // unfollower profile, so _followerCount is guaranteed to be greater than zero. _followerCount--; } delete _followTokenIdByFollowerProfileId[unfollower]; delete _followDataByFollowTokenId[followTokenId].followerProfileId; delete _followDataByFollowTokenId[followTokenId].followTimestamp; delete _followDataByFollowTokenId[followTokenId].profileIdAllowedToRecover; } function _approveFollow(uint256 approvedProfileId, uint256 followTokenId) internal { _followApprovalByFollowTokenId[followTokenId] = approvedProfileId; emit FollowApproval(approvedProfileId, followTokenId); } /** * @dev Upon transfers, we clear follow approvals and emit the transfer event in the hub. */ function _beforeTokenTransfer(address from, address to, uint256 followTokenId) internal override whenNotPaused { if (from != address(0)) { // It is cleared on unwrappings and transfers, and it can not be set on unwrapped tokens. // As a consequence, there is no need to clear it on wrappings. _approveFollow(0, followTokenId); } super._beforeTokenTransfer(from, to, followTokenId); } function _getReceiver(uint256 /* followTokenId */) internal view override returns (address) { if (!ILensHub(HUB).exists(_followedProfileId)) { return address(0); } return IERC721(HUB).ownerOf(_followedProfileId); } function _beforeRoyaltiesSet(uint256 /* royaltiesInBasisPoints */) internal view override { if (IERC721(HUB).ownerOf(_followedProfileId) != msg.sender) { revert Errors.NotProfileOwner(); } } function _isFollowTokenWrapped(uint256 followTokenId) internal view returns (bool) { return _exists(followTokenId); } function _getRoyaltiesInBasisPointsSlot() internal pure override returns (uint256) { uint256 slot; assembly { slot := _royaltiesInBasisPoints.slot } return slot; } ////////////////// /// Migrations /// ////////////////// // This function shouldn't fail under no circumstances, except if wrong parameters are passed. function tryMigrate( uint256 followerProfileId, address followerProfileOwner, uint256 followTokenId ) external onlyHub returns (uint48) { // Migrated FollowNFTs should have `originalFollowTimestamp` set if (_followDataByFollowTokenId[followTokenId].originalFollowTimestamp != 0) { return 0; // Already migrated } if (_followTokenIdByFollowerProfileId[followerProfileId] != 0) { return 0; // Already following } Types.TokenData memory tokenData = StorageLib.getTokenData(followTokenId); address followTokenOwner = tokenData.owner; if (followTokenOwner == address(0)) { return 0; // Doesn't exist } // ProfileNFT and FollowNFT should be in the same account if (followerProfileOwner != followTokenOwner) { return 0; // Not holding both Profile & Follow NFTs together } unchecked { ++_followerCount; } _followTokenIdByFollowerProfileId[followerProfileId] = followTokenId; _followDataByFollowTokenId[followTokenId].followerProfileId = uint160(followerProfileId); _followDataByFollowTokenId[followTokenId].originalFollowTimestamp = uint48(tokenData.mintTimestamp); _followDataByFollowTokenId[followTokenId].followTimestamp = uint48(tokenData.mintTimestamp); super._burn(followTokenId); return uint48(tokenData.mintTimestamp); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol'; import {IERC2981} from '@openzeppelin/contracts/interfaces/IERC2981.sol'; abstract contract ERC2981CollectionRoyalties is IERC2981 { uint16 internal constant BASIS_POINTS = 10000; // bytes4(keccak256('royaltyInfo(uint256,uint256)')) == 0x2a55205a bytes4 internal constant INTERFACE_ID_ERC2981 = 0x2a55205a; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == INTERFACE_ID_ERC2981 || interfaceId == type(IERC165).interfaceId; } /** * @notice Changes the royalty percentage for secondary sales. * * @param royaltiesInBasisPoints The royalty percentage (measured in basis points). */ function setRoyalty(uint256 royaltiesInBasisPoints) external { _beforeRoyaltiesSet(royaltiesInBasisPoints); _setRoyalty(royaltiesInBasisPoints); } /** * @notice Called with the sale price to determine how much royalty is owed and to whom. * * @param tokenId The ID of the token queried for royalty information. * @param salePrice The sale price of the token specified. * @return A tuple with the address that should receive the royalties and the royalty * payment amount for the given sale price. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address, uint256) { return (_getReceiver(tokenId), _getRoyaltyAmount(tokenId, salePrice)); } function _setRoyalty(uint256 royaltiesInBasisPoints) internal virtual { if (royaltiesInBasisPoints > BASIS_POINTS) { revert Errors.InvalidParameter(); } _storeRoyaltiesInBasisPoints(royaltiesInBasisPoints); } function _getRoyaltyAmount(uint256 /* tokenId */, uint256 salePrice) internal view virtual returns (uint256) { return (salePrice * _loadRoyaltiesInBasisPoints()) / BASIS_POINTS; } function _storeRoyaltiesInBasisPoints(uint256 royaltiesInBasisPoints) internal virtual { uint256 royaltiesInBasisPointsSlot = _getRoyaltiesInBasisPointsSlot(); assembly { sstore(royaltiesInBasisPointsSlot, royaltiesInBasisPoints) } } function _loadRoyaltiesInBasisPoints() internal view virtual returns (uint256) { uint256 royaltiesInBasisPointsSlot = _getRoyaltiesInBasisPointsSlot(); uint256 royaltyAmount; assembly { royaltyAmount := sload(royaltiesInBasisPointsSlot) } return royaltyAmount; } function _beforeRoyaltiesSet(uint256 royaltiesInBasisPoints) internal view virtual; function _getRoyaltiesInBasisPointsSlot() internal view virtual returns (uint256); function _getReceiver(uint256 tokenId) internal view virtual returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Errors} from 'contracts/libraries/constants/Errors.sol'; /** * @title HubRestricted * @author Lens Protocol * * @notice This abstract contract adds a public `HUB` immutable field, as well as an `onlyHub` modifier, * to inherit from contracts that have functions restricted to be only called by the Lens hub. */ abstract contract HubRestricted { address public immutable HUB; modifier onlyHub() { if (msg.sender != HUB) { revert Errors.NotHub(); } _; } constructor(address hub) { HUB = hub; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {Types} from 'contracts/libraries/constants/Types.sol'; import {MetaTxLib} from 'contracts/libraries/MetaTxLib.sol'; import {ILensERC721} from 'contracts/interfaces/ILensERC721.sol'; import {IERC721Timestamped} from 'contracts/interfaces/IERC721Timestamped.sol'; import {IERC721Burnable} from 'contracts/interfaces/IERC721Burnable.sol'; import {IERC721MetaTx} from 'contracts/interfaces/IERC721MetaTx.sol'; import {IERC721Receiver} from '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import {IERC721Metadata} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import {ERC165} from '@openzeppelin/contracts/utils/introspection/ERC165.sol'; import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol'; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. * * Modifications: * 1. Refactored _operatorApprovals setter into an internal function to allow meta-transactions. * 2. Constructor replaced with an initializer. * 3. Mint timestamp is now stored in a TokenData struct alongside the owner address. */ abstract contract LensBaseERC721 is ERC165, ILensERC721 { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to token Data (owner address and mint timestamp uint96), this // replaces the original mapping(uint256 => address) private _owners; mapping(uint256 => Types.TokenData) private _tokenData; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Deprecated in V2 after removing ERC712Enumerable logic. mapping(address => mapping(uint256 => uint256)) private __DEPRECATED__ownedTokens; mapping(uint256 => uint256) private __DEPRECATED__ownedTokensIndex; // Dirty hack on a deprecated slot: uint256 private _totalSupply; // uint256[] private __DEPRECATED__allTokens; // Deprecated in V2 after removing ERC712Enumerable logic. mapping(uint256 => uint256) private __DEPRECATED__allTokensIndex; mapping(address => uint256) private _nonces; /** * @dev Initializes the ERC721 name and symbol. * * @param name_ The name to set. * @param symbol_ The symbol to set. */ function _initialize(string calldata name_, string calldata symbol_) internal { _name = name_; _symbol = symbol_; } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view virtual returns (string memory); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Timestamped).interfaceId || interfaceId == type(IERC721Burnable).interfaceId || interfaceId == type(IERC721MetaTx).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function nonces(address signer) public view override returns (uint256) { return _nonces[signer]; } /// @inheritdoc IERC721MetaTx function getDomainSeparator() external view virtual override returns (bytes32) { return MetaTxLib.calculateDomainSeparator(); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) { revert Errors.InvalidParameter(); } return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _tokenData[tokenId].owner; if (owner == address(0)) { revert Errors.TokenDoesNotExist(); } return owner; } /** * @dev See {IERC721Timestamped-mintTimestampOf} */ function mintTimestampOf(uint256 tokenId) public view virtual override returns (uint256) { uint96 mintTimestamp = _tokenData[tokenId].mintTimestamp; if (mintTimestamp == 0) { revert Errors.TokenDoesNotExist(); } return mintTimestamp; } /** * @dev See {IERC721Timestamped-tokenDataOf} */ function tokenDataOf(uint256 tokenId) public view virtual override returns (Types.TokenData memory) { if (!_exists(tokenId)) { revert Errors.TokenDoesNotExist(); } return _tokenData[tokenId]; } /** * @dev See {IERC721Timestamped-exists} */ function exists(uint256 tokenId) public view virtual override returns (bool) { return _exists(tokenId); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); if (to == owner) { revert Errors.InvalidParameter(); } if (msg.sender != owner && !isApprovedForAll(owner, msg.sender)) { revert Errors.NotOwnerOrApproved(); } _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) { revert Errors.TokenDoesNotExist(); } return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == msg.sender) { revert Errors.InvalidParameter(); } _setOperatorApproval(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length if (!_isApprovedOrOwner(msg.sender, tokenId)) { revert Errors.NotOwnerOrApproved(); } _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { if (!_isApprovedOrOwner(msg.sender, tokenId)) { revert Errors.NotOwnerOrApproved(); } _safeTransfer(from, to, tokenId, _data); } /** * @dev Burns `tokenId`. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual override { if (!_isApprovedOrOwner(msg.sender, tokenId)) { revert Errors.NotOwnerOrApproved(); } _burn(tokenId); } /** * @notice Returns the owner of the `tokenId` token. * * @dev It is prefixed as `unsafe` as it does not revert when the token does not exist. * * @param tokenId The token whose owner is being queried. * * @return address The address owning the given token, zero address if the token does not exist. */ function _unsafeOwnerOf(uint256 tokenId) internal view returns (address) { return _tokenData[tokenId].owner; } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform a token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert Errors.NonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenData[tokenId].owner != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { address owner = ownerOf(tokenId); // We don't check owner for != address(0) cause it's done inside ownerOf() return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { if (to == address(0) || _exists(tokenId)) { revert Errors.InvalidParameter(); } _beforeTokenTransfer(address(0), to, tokenId); unchecked { ++_balances[to]; ++_totalSupply; } _tokenData[tokenId].owner = to; _tokenData[tokenId].mintTimestamp = uint96(block.timestamp); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); unchecked { --_balances[owner]; --_totalSupply; } delete _tokenData[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { if (ownerOf(tokenId) != from) { revert Errors.InvalidOwner(); } if (to == address(0)) { revert Errors.InvalidParameter(); } _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); unchecked { --_balances[from]; ++_balances[to]; } _tokenData[tokenId].owner = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Refactored from the original OZ ERC721 implementation: approve or revoke approval from * `operator` to operate on all tokens owned by `owner`. * * Emits a {ApprovalForAll} event. */ function _setOperatorApproval( address owner, address operator, bool approved ) internal virtual { _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert Errors.NonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title IERC721Burnable * @author Lens Protocol * * @notice Extension of ERC-721 including a function that allows the token to be burned. */ interface IERC721Burnable { /** * @notice Burns an NFT, removing it from circulation and essentially destroying it. * @custom:permission Owner of the NFT. * * @param tokenId The token ID of the token to burn. */ function burn(uint256 tokenId) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title IERC721MetaTx * @author Lens Protocol * * @notice Extension of ERC-721 including meta-tx signatures related functions. */ interface IERC721MetaTx { /** * @notice Returns the current signature nonce of the given signer. * * @param signer The address for which to query the nonce. * * @return uint256 The current nonce of the given signer. */ function nonces(address signer) external view returns (uint256); /** * @notice Returns the EIP-712 domain separator for this contract. * * @return bytes32 The domain separator. */ function getDomainSeparator() external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {Types} from 'contracts/libraries/constants/Types.sol'; /** * @title IERC721Timestamped * @author Lens Protocol * * @notice Extension of ERC-721 including a struct for token data, which contains the owner and the mint timestamp, as * well as their associated getters. */ interface IERC721Timestamped { /** * @notice Returns the mint timestamp associated with a given NFT. * * @param tokenId The token ID of the NFT to query the mint timestamp for. * * @return uint256 Mint timestamp, this is stored as a uint96 but returned as a uint256 to reduce unnecessary * padding. */ function mintTimestampOf(uint256 tokenId) external view returns (uint256); /** * @notice Returns the token data associated with a given NFT. This allows fetching the token owner and * mint timestamp in a single call. * * @param tokenId The token ID of the NFT to query the token data for. * * @return TokenData A struct containing both the owner address and the mint timestamp. */ function tokenDataOf(uint256 tokenId) external view returns (Types.TokenData memory); /** * @notice Returns whether a token with the given token ID exists. * * @param tokenId The token ID of the NFT to check existence for. * * @return bool True if the token exists. */ function exists(uint256 tokenId) external view returns (bool); /** * @notice Returns the amount of tokens in circulation. * * @return uint256 The current total supply of tokens. */ function totalSupply() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title IFollowModule * @author Lens Protocol * * @notice This is the standard interface for all Lens-compatible Follow Modules. * These are responsible for processing the follow actions and can be used to implement any kind of follow logic. * For example: * - Token-gated follows (e.g. a user must hold a certain amount of a token to follow a profile). * - Paid follows (e.g. a user must pay a certain amount of a token to follow a profile). * - Rewarding users for following a profile. * - Etc. */ interface IFollowModule { /** * @notice Initializes a follow module for a given Lens profile. * @custom:permissions LensHub. * * @param profileId The Profile ID to initialize this follow module for. * @param transactionExecutor The address of the transaction executor (e.g. for any funds to transferFrom). * @param data Arbitrary data passed from the user to be decoded by the Follow Module during initialization. * * @return bytes The encoded data to be emitted from the hub. */ function initializeFollowModule( uint256 profileId, address transactionExecutor, bytes calldata data ) external returns (bytes memory); /** * @notice Processes a given follow. * @custom:permissions LensHub. * * @param followerProfileId The Profile ID of the follower's profile. * @param followTokenId The Follow Token ID that is being used to follow. Zero if we are processing a new fresh * follow, in this case, the follow ID assigned can be queried from the Follow NFT collection if needed. * @param transactionExecutor The address of the transaction executor (e.g. for any funds to transferFrom). * @param targetProfileId The token ID of the profile being followed. * @param data Arbitrary data passed by the follower. * * @return bytes Any custom ABI-encoded data. This will be a LensHub event params that can be used by * indexers or UIs. */ function processFollow( uint256 followerProfileId, uint256 followTokenId, address transactionExecutor, uint256 targetProfileId, bytes calldata data ) external returns (bytes memory); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {Types} from 'contracts/libraries/constants/Types.sol'; /** * @title IFollowNFT * @author Lens Protocol * * @notice This is the interface for the FollowNFT contract, which is cloned upon the first follow for any profile. * By default the Follow tokens are tied to the follower profile, which means that they will be automatically * transferred with it. * This is achieved by them not being ERC-721 initially. However, the Follow NFT collections support converting them to * ERC-721 tokens (i.e. wrapping) natively, enabling composability with existing ERC-721-based protocols. */ interface IFollowNFT { error AlreadyFollowing(); error NotFollowing(); error FollowTokenDoesNotExist(); error AlreadyWrapped(); error OnlyWrappedFollowTokens(); error DoesNotHavePermissions(); /** * @notice Initializes the follow NFT. * @custom:permissions LensHub. * * @dev Sets the targeted profile, and the token royalties. * * @param profileId The ID of the profile targeted by the follow tokens minted by this collection. */ function initialize(uint256 profileId) external; /** * @notice Makes the passed profile follow the profile targeted in this contract. * @custom:permissions LensHub. * * @param followerProfileId The ID of the profile acting as the follower. * @param transactionExecutor The address of the transaction executor (e.g. for any funds to transferFrom). * @param followTokenId The ID of the follow token to be used for this follow operation. Zero if a new follow token * should be minted. * * @return uint256 The ID of the token used to follow. */ function follow( uint256 followerProfileId, address transactionExecutor, uint256 followTokenId ) external returns (uint256); /** * @notice Makes the passed profile unfollow the profile targeted in this contract. * @custom:permissions LensHub. * * @param unfollowerProfileId The ID of the profile that is performing the unfollow operation. */ function unfollow(uint256 unfollowerProfileId) external; /** * @notice Removes the follower from the given follow NFT. * @custom:permissions Follow token owner or approved-for-all. * @dev Only on wrapped token. * * @param followTokenId The ID of the follow token to remove the follower from. */ function removeFollower(uint256 followTokenId) external; /** * @notice Approves the given profile to follow with the given wrapped token. * @custom:permissions Follow token owner or approved-for-all. * * @dev Only on wrapped tokens. * It approves setting a follower on the given wrapped follow token, which lets the follow token owner to allow * a profile to follow with his token without losing its ownership. This approval is cleared on transfers, as well * as when unwrapping. * * @param approvedProfileId The ID of the profile approved to follow with the given token. * @param followTokenId The ID of the follow token to be approved for the given profile. */ function approveFollow(uint256 approvedProfileId, uint256 followTokenId) external; /** * @notice Unties the follow token from the follower's profile one, and wraps it into the ERC-721 untied follow * tokens collection. Untied follow tokens will NOT be automatically transferred with their follower profile. * @custom:permissions Follower profile owner. * * @dev Only on unwrapped follow tokens. * * @param followTokenId The ID of the follow token to untie and wrap. */ function wrap(uint256 followTokenId) external; /** * @notice Unties the follow token from the follower's profile one, and wraps it into the ERC-721 untied follow * tokens collection. Untied follow tokens will NOT be automatically transferred with their follower profile. * @custom:permissions Follower profile owner. * * @dev Only on unwrapped follow tokens. * * @param followTokenId The ID of the follow token to untie and wrap. * @param wrappedTokenReceiver The address where the follow token is minted to when being wrapped as ERC-721. */ function wrap(uint256 followTokenId, address wrappedTokenReceiver) external; /** * @notice Unwraps the follow token from the ERC-721 untied follow tokens collection, and ties it to the follower's * profile token. Tokens that are tied to the follower profile will be automatically transferred with it. * * @param followTokenId The ID of the follow token to unwrap and tie to its follower. */ function unwrap(uint256 followTokenId) external; /** * @notice Processes logic when the given profile is being blocked. If it was following the targeted profile, * this will make it unfollow. * @custom:permissions LensHub. * * @param followerProfileId The ID of the follow token to unwrap and tie. * * @return bool True if the given profile was following and now has unfollowed, false otherwise. */ function processBlock(uint256 followerProfileId) external returns (bool); /////////////////////////// /// GETTERS /// /////////////////////////// /** * @notice Gets the ID of the profile following with the given follow token. * * @param followTokenId The ID of the follow token whose follower should be queried. * * @return uint256 The ID of the profile following with the given token, zero if it is not being used to follow. */ function getFollowerProfileId(uint256 followTokenId) external view returns (uint256); /** * @notice Gets the original follow timestamp of the given follow token. * * @param followTokenId The ID of the follow token whose original follow timestamp should be queried. * * @return uint256 The timestamp of the first follow performed with the token, zero if was not used to follow yet. */ function getOriginalFollowTimestamp(uint256 followTokenId) external view returns (uint256); /** * @notice Gets the current follow timestamp of the given follow token. * * @param followTokenId The ID of the follow token whose follow timestamp should be queried. * * @return uint256 The timestamp of the current follow of the token, zero if it is not being used to follow. */ function getFollowTimestamp(uint256 followTokenId) external view returns (uint256); /** * @notice Gets the ID of the profile allowed to recover the given follow token. * * @param followTokenId The ID of the follow token whose allowed profile to recover should be queried. * * @return uint256 The ID of the profile allowed to recover the given follow token, zero if none of them is allowed. */ function getProfileIdAllowedToRecover(uint256 followTokenId) external view returns (uint256); /** * @notice Gets the follow data of the given follow token. * * @param followTokenId The ID of the follow token whose follow data should be queried. * * @return FollowData The token data associated with the given follow token. */ function getFollowData(uint256 followTokenId) external view returns (Types.FollowData memory); /** * @notice Tells if the given profile is following the profile targeted in this contract. * * @param followerProfileId The ID of the profile whose following state should be queried. * * @return uint256 The ID of the profile set as a follower in the given token, zero if it is not being used to follow. */ function isFollowing(uint256 followerProfileId) external view returns (bool); /** * @notice Gets the ID of the token being used to follow by the given follower. * * @param followerProfileId The ID of the profile whose follow ID should be queried. * * @return uint256 The ID of the token being used to follow by the given follower, zero if he is not following. */ function getFollowTokenId(uint256 followerProfileId) external view returns (uint256); /** * @notice Gets the ID of the profile approved to follow with the given token. * * @param followTokenId The ID of the token whose approved to follow should be queried. * * @return uint256 The ID of the profile approved to follow with the given token, zero if none of them is approved. */ function getFollowApproved(uint256 followTokenId) external view returns (uint256); /** * @notice Gets the count of the followers of the profile targeted in this contract. * @notice This number might be out of sync if one of the followers burns their profile. * * @return uint256 The count of the followers of the profile targeted in this contract. */ function getFollowerCount() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title IReferenceModule * @author Lens Protocol * @custom:pending-deprecation * * @notice This is the deprecated interface for previously Lens-compatible ReferenceModules. */ interface ILegacyReferenceModule { /** * @notice Initializes data for a given publication being published. This can only be called by the hub. * * @param profileId The token ID of the profile publishing the publication. * @param pubId The associated publication's LensHub publication ID. * @param data Arbitrary data passed from the user to be decoded. * * @return bytes An ABI-encoded data encapsulating the execution's state changes. This will be emitted by the * hub alongside the collect module's address and should be consumed by front ends. */ function initializeReferenceModule( uint256 profileId, uint256 pubId, bytes calldata data ) external returns (bytes memory); /** * @notice Processes a comment action referencing a given publication. This can only be called by the hub. * * @param profileId The token ID of the profile associated with the publication being published. * @param pointedProfileId The profile ID of the profile associated with the publication being referenced. * @param pointedPubId The publication ID of the publication being referenced. * @param data Arbitrary data __passed from the commenter!__ to be decoded. */ function processComment( uint256 profileId, uint256 pointedProfileId, uint256 pointedPubId, bytes calldata data ) external; /** * @notice Processes a mirror action referencing a given publication. This can only be called by the hub. * * @param profileId The token ID of the profile associated with the publication being published. * @param pointedProfileId The profile ID of the profile associated with the publication being referenced. * @param pointedPubId The publication ID of the publication being referenced. * @param data Arbitrary data __passed from the mirrorer!__ to be decoded. */ function processMirror( uint256 profileId, uint256 pointedProfileId, uint256 pointedPubId, bytes calldata data ) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import {IERC721Timestamped} from 'contracts/interfaces/IERC721Timestamped.sol'; import {IERC721Burnable} from 'contracts/interfaces/IERC721Burnable.sol'; import {IERC721MetaTx} from 'contracts/interfaces/IERC721MetaTx.sol'; import {IERC721Metadata} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; interface ILensERC721 is IERC721, IERC721Timestamped, IERC721Burnable, IERC721MetaTx, IERC721Metadata {}
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {Types} from 'contracts/libraries/constants/Types.sol'; /** * @title ILensGovernable * @author Lens Protocol * * @notice This is the interface for the Lens Protocol main governance functions. */ interface ILensGovernable { /** * @notice Sets the privileged governance role. * @custom:permissions Governance. * * @param newGovernance The new governance address to set. */ function setGovernance(address newGovernance) external; /** * @notice Sets the emergency admin, which is a permissioned role able to set the protocol state. * @custom:permissions Governance. * * @param newEmergencyAdmin The new emergency admin address to set. */ function setEmergencyAdmin(address newEmergencyAdmin) external; /** * @notice Sets the protocol state to either a global pause, a publishing pause or an unpaused state. * @custom:permissions Governance or Emergency Admin. Emergency Admin can only restrict more. * * @param newState The state to set. It can be one of the following: * - Unpaused: The protocol is fully operational. * - PublishingPaused: The protocol is paused for publishing, but it is still operational for others operations. * - Paused: The protocol is paused for all operations. */ function setState(Types.ProtocolState newState) external; /** * @notice Adds or removes a profile creator from the whitelist. * @custom:permissions Governance. * * @param profileCreator The profile creator address to add or remove from the whitelist. * @param whitelist Whether or not the profile creator should be whitelisted. */ function whitelistProfileCreator(address profileCreator, bool whitelist) external; /** * @notice Sets the treasury address. * @custom:permissions Governance * * @param newTreasury The new treasury address to set. */ function setTreasury(address newTreasury) external; /** * @notice Sets the treasury fee. * @custom:permissions Governance * * @param newTreasuryFee The new treasury fee to set. */ function setTreasuryFee(uint16 newTreasuryFee) external; /** * @notice Returns the currently configured governance address. * * @return address The address of the currently configured governance. */ function getGovernance() external view returns (address); /** * @notice Gets the state currently set in the protocol. It could be a global pause, a publishing pause or an * unpaused state. * @custom:permissions Anyone. * * @return Types.ProtocolState The state currently set in the protocol. */ function getState() external view returns (Types.ProtocolState); /** * @notice Returns whether or not a profile creator is whitelisted. * * @param profileCreator The address of the profile creator to check. * * @return bool True if the profile creator is whitelisted, false otherwise. */ function isProfileCreatorWhitelisted(address profileCreator) external view returns (bool); /** * @notice Returns the treasury address. * * @return address The treasury address. */ function getTreasury() external view returns (address); /** * @notice Returns the treasury fee. * * @return uint16 The treasury fee. */ function getTreasuryFee() external view returns (uint16); /** * @notice Returns the treasury address and treasury fee in a single call. * * @return tuple First, the treasury address, second, the treasury fee. */ function getTreasuryData() external view returns (address, uint16); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /** * @title ILensHandles * @author Lens Protocol * * @notice This is the interface for the LensHandles contract that is responsible for minting and burning handle NFTs. * A handle is composed of a local name and a namespace, separated by a dot. * Example: `satoshi.lens` is a handle composed of the local name `satoshi` and the namespace `lens`. */ interface ILensHandles is IERC721 { /** * @notice Mints a handle NFT in the given namespace. * @custom:permissions Only LensHandles contract's owner or LensHub. * * @param to The address to mint the handle to. * @param localName The local name of the handle (the part before ".lens"). * * @return uint256 The ID of the handle NFT minted. */ function mintHandle(address to, string calldata localName) external returns (uint256); /** * @notice Burns a handle NFT. * @custom:permissions Owner of Handle NFT. * * @param tokenId The ID of the handle NFT to burn. */ function burn(uint256 tokenId) external; /** * @notice Gets the namespace of the contract. It's 'lens' for the LensHandles contract. * * @return string The namespace of the contract. */ function getNamespace() external pure returns (string memory); /** * @notice Gets the hash of the namespace of the contract. It's keccak256('lens') for the LensHandles contract. * * @return bytes32 The hash of the namespace of the contract. */ function getNamespaceHash() external pure returns (bytes32); /** * @notice Returns whether `tokenId` exists. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). * * @return bool Whether the token exists. */ function exists(uint256 tokenId) external view returns (bool); /** * @notice Returns the amount of tokens in circulation. * * @return uint256 The current total supply of tokens. */ function totalSupply() external view returns (uint256); /** * @notice DANGER: Triggers disabling the profile protection mechanism for the msg.sender, which will allow * transfers or approvals over profiles held by it. * Disabling the mechanism will have a timelock before it becomes effective, allowing the owner to re-enable * the protection back in case of being under attack. * The protection layer only applies to EOA wallets. */ function DANGER__disableTokenGuardian() external; /** * @notice Enables back the profile protection mechanism for the msg.sender, preventing profile transfers or * approvals (except when revoking them). * The protection layer only applies to EOA wallets. */ function enableTokenGuardian() external; /** * @notice Returns the timestamp at which the Token Guardian will become effectively disabled. * * @param wallet The address to check the timestamp for. * * @return uint256 The timestamp at which the Token Guardian will become effectively disabled. * Max 256-bit unsigned integer value if enabled. */ function getTokenGuardianDisablingTimestamp(address wallet) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {ILensProtocol} from 'contracts/interfaces/ILensProtocol.sol'; import {ILensGovernable} from 'contracts/interfaces/ILensGovernable.sol'; import {ILensHubEventHooks} from 'contracts/interfaces/ILensHubEventHooks.sol'; import {ILensImplGetters} from 'contracts/interfaces/ILensImplGetters.sol'; import {ILensProfiles} from 'contracts/interfaces/ILensProfiles.sol'; import {ILensVersion} from 'contracts/interfaces/ILensVersion.sol'; interface ILensHub is ILensProfiles, ILensProtocol, ILensGovernable, ILensHubEventHooks, ILensImplGetters, ILensVersion {}
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title ILensHubEventHooks * @author Lens Protocol * * @notice This is the interface for the LensHub contract's event hooks. As we want most of the core events to be * emitted by the LensHub contract, event hooks are needed for core events generated by pheripheral contracts. */ interface ILensHubEventHooks { /** * @dev Helper function to emit an `Unfollowed` event from the hub, to be consumed by indexers to track unfollows. * @custom:permissions FollowNFT of the Profile unfollowed. * * @param unfollowerProfileId The ID of the profile that executed the unfollow. * @param idOfProfileUnfollowed The ID of the profile that was unfollowed. * @param transactionExecutor The address of the account executing the unfollow operation. */ function emitUnfollowedEvent( uint256 unfollowerProfileId, uint256 idOfProfileUnfollowed, address transactionExecutor ) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title ILensImplGetters * @author Lens Protocol * * @notice This is the interface for the LensHub contract's implementation getters. These implementations will be used * for deploying each respective contract for each profile. */ interface ILensImplGetters { /** * @notice Returns the Follow NFT implementation address that is used for all deployed Follow NFTs. * * @return address The Follow NFT implementation address. */ function getFollowNFTImpl() external view returns (address); /** * @notice Returns the Collect NFT implementation address that is used for each new deployed Collect NFT. * @custom:pending-deprecation * * @return address The Collect NFT implementation address. */ function getLegacyCollectNFTImpl() external view returns (address); /** * @notice Returns the address of the registry that stores all modules that are used by the Lens Protocol. * * @return address The address of the Module Registry contract. */ function getModuleRegistry() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {ILensERC721} from 'contracts/interfaces/ILensERC721.sol'; interface ILensProfiles is ILensERC721 { /** * @notice DANGER: Triggers disabling the profile protection mechanism for the msg.sender, which will allow * transfers or approvals over profiles held by it. * Disabling the mechanism will have a timelock before it becomes effective, allowing the owner to re-enable * the protection back in case of being under attack. * The protection layer only applies to EOA wallets. */ function DANGER__disableTokenGuardian() external; /** * @notice Enables back the profile protection mechanism for the msg.sender, preventing profile transfers or * approvals (except when revoking them). * The protection layer only applies to EOA wallets. */ function enableTokenGuardian() external; /** * @notice Returns the timestamp at which the Token Guardian will become effectively disabled. * * @param wallet The address to check the timestamp for. * * @return uint256 The timestamp at which the Token Guardian will become effectively disabled. Zero if enabled. */ function getTokenGuardianDisablingTimestamp(address wallet) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {Types} from 'contracts/libraries/constants/Types.sol'; /** * @title ILensProtocol * @author Lens Protocol * * @notice This is the interface for Lens Protocol's core functions. It contains all the entry points for performing * social operations. */ interface ILensProtocol { /** * @notice Creates a profile with the specified parameters, minting a Profile NFT to the given recipient. * @custom:permissions Any whitelisted profile creator. * * @param createProfileParams A CreateProfileParams struct containing the needed params. */ function createProfile(Types.CreateProfileParams calldata createProfileParams) external returns (uint256); /** * @notice Sets the metadata URI for the given profile. * @custom:permissions Profile Owner or Delegated Executor. * * @param profileId The token ID of the profile to set the metadata URI for. * @param metadataURI The metadata URI to set for the given profile. */ function setProfileMetadataURI(uint256 profileId, string calldata metadataURI) external; /** * @custom:meta-tx setProfileMetadataURI. */ function setProfileMetadataURIWithSig( uint256 profileId, string calldata metadataURI, Types.EIP712Signature calldata signature ) external; /** * @notice Sets the follow module for the given profile. * @custom:permissions Profile Owner or Delegated Executor. * * @param profileId The token ID of the profile to set the follow module for. * @param followModule The follow module to set for the given profile, must be whitelisted. * @param followModuleInitData The data to be passed to the follow module for initialization. */ function setFollowModule(uint256 profileId, address followModule, bytes calldata followModuleInitData) external; /** * @custom:meta-tx setFollowModule. */ function setFollowModuleWithSig( uint256 profileId, address followModule, bytes calldata followModuleInitData, Types.EIP712Signature calldata signature ) external; /** * @notice Changes the delegated executors configuration for the given profile. It allows setting the approvals for * delegated executors in the specified configuration, as well as switching to it. * @custom:permissions Profile Owner. * * @param delegatorProfileId The ID of the profile to which the delegated executor is being changed for. * @param delegatedExecutors The array of delegated executors to set the approval for. * @param approvals The array of booleans indicating the corresponding executor's new approval status. * @param configNumber The number of the configuration where the executor approval state is being set. * @param switchToGivenConfig A boolean indicating if the configuration must be switched to the one with the given * number. */ function changeDelegatedExecutorsConfig( uint256 delegatorProfileId, address[] calldata delegatedExecutors, bool[] calldata approvals, uint64 configNumber, bool switchToGivenConfig ) external; /** * @notice Changes the delegated executors configuration for the given profile under the current configuration. * @custom:permissions Profile Owner. * * @param delegatorProfileId The ID of the profile to which the delegated executor is being changed for. * @param delegatedExecutors The array of delegated executors to set the approval for. * @param approvals The array of booleans indicating the corresponding executor's new approval status. */ function changeDelegatedExecutorsConfig( uint256 delegatorProfileId, address[] calldata delegatedExecutors, bool[] calldata approvals ) external; /** * @custom:meta-tx changeDelegatedExecutorsConfig. */ function changeDelegatedExecutorsConfigWithSig( uint256 delegatorProfileId, address[] calldata delegatedExecutors, bool[] calldata approvals, uint64 configNumber, bool switchToGivenConfig, Types.EIP712Signature calldata signature ) external; /** * @notice Publishes a post. * Post is the most basic publication type, and can be used to publish any kind of content. * Posts can have these types of modules initialized: * - Action modules: any number of publication actions (e.g. collect, tip, etc.) * - Reference module: a module handling the rules when referencing this post (e.g. token-gated comments) * @custom:permissions Profile Owner or Delegated Executor. * * @param postParams A PostParams struct containing the needed parameters. * * @return uint256 An integer representing the post's publication ID. */ function post(Types.PostParams calldata postParams) external returns (uint256); /** * @custom:meta-tx post. */ function postWithSig( Types.PostParams calldata postParams, Types.EIP712Signature calldata signature ) external returns (uint256); /** * @notice Publishes a comment on the given publication. * Comment is a type of reference publication that points to another publication. * Comments can have these types of modules initialized: * - Action modules: any number of publication actions (e.g. collect, tip, etc.) * - Reference module: a module handling the rules when referencing this comment (e.g. token-gated mirrors) * Comments can have referrers (e.g. publications or profiles that helped to discover the pointed publication). * @custom:permissions Profile Owner or Delegated Executor. * * @param commentParams A CommentParams struct containing the needed parameters. * * @return uint256 An integer representing the comment's publication ID. */ function comment(Types.CommentParams calldata commentParams) external returns (uint256); /** * @custom:meta-tx comment. */ function commentWithSig( Types.CommentParams calldata commentParams, Types.EIP712Signature calldata signature ) external returns (uint256); /** * @notice Publishes a mirror of the given publication. * Mirror is a type of reference publication that points to another publication but doesn't have content. * Mirrors don't have any modules initialized. * Mirrors can have referrers (e.g. publications or profiles that allowed to discover the pointed publication). * You cannot mirror a mirror, comment on a mirror, or quote a mirror. * @custom:permissions Profile Owner or Delegated Executor. * * @param mirrorParams A MirrorParams struct containing the necessary parameters. * * @return uint256 An integer representing the mirror's publication ID. */ function mirror(Types.MirrorParams calldata mirrorParams) external returns (uint256); /** * @custom:meta-tx mirror. */ function mirrorWithSig( Types.MirrorParams calldata mirrorParams, Types.EIP712Signature calldata signature ) external returns (uint256); /** * @notice Publishes a quote of the given publication. * Quote is a type of reference publication similar to mirror, but it has content and modules. * Quotes can have these types of modules initialized: * - Action modules: any number of publication actions (e.g. collect, tip, etc.) * - Reference module: a module handling the rules when referencing this quote (e.g. token-gated comments on quote) * Quotes can have referrers (e.g. publications or profiles that allowed to discover the pointed publication). * Unlike mirrors, you can mirror a quote, comment on a quote, or quote a quote. * @custom:permissions Profile Owner or Delegated Executor. * * @param quoteParams A QuoteParams struct containing the needed parameters. * * @return uint256 An integer representing the quote's publication ID. */ function quote(Types.QuoteParams calldata quoteParams) external returns (uint256); /** * @custom:meta-tx quote. */ function quoteWithSig( Types.QuoteParams calldata quoteParams, Types.EIP712Signature calldata signature ) external returns (uint256); /** * @notice Follows given profiles, executing each profile's follow module logic (if any). * @custom:permissions Profile Owner or Delegated Executor. * * @dev Both the `idsOfProfilesToFollow`, `followTokenIds`, and `datas` arrays must be of the same length, * regardless if the profiles do not have a follow module set. * * @param followerProfileId The ID of the profile the follows are being executed for. * @param idsOfProfilesToFollow The array of IDs of profiles to follow. * @param followTokenIds The array of follow token IDs to use for each follow (0 if you don't own a follow token). * @param datas The arbitrary data array to pass to the follow module for each profile if needed. * * @return uint256[] An array of follow token IDs representing the follow tokens created for each follow. */ function follow( uint256 followerProfileId, uint256[] calldata idsOfProfilesToFollow, uint256[] calldata followTokenIds, bytes[] calldata datas ) external returns (uint256[] memory); /** * @custom:meta-tx follow. */ function followWithSig( uint256 followerProfileId, uint256[] calldata idsOfProfilesToFollow, uint256[] calldata followTokenIds, bytes[] calldata datas, Types.EIP712Signature calldata signature ) external returns (uint256[] memory); /** * @notice Unfollows given profiles. * @custom:permissions Profile Owner or Delegated Executor. * * @param unfollowerProfileId The ID of the profile the unfollows are being executed for. * @param idsOfProfilesToUnfollow The array of IDs of profiles to unfollow. */ function unfollow(uint256 unfollowerProfileId, uint256[] calldata idsOfProfilesToUnfollow) external; /** * @custom:meta-tx unfollow. */ function unfollowWithSig( uint256 unfollowerProfileId, uint256[] calldata idsOfProfilesToUnfollow, Types.EIP712Signature calldata signature ) external; /** * @notice Sets the block status for the given profiles. Changing a profile's block status to `true` (i.e. blocked), * when will also force them to unfollow. * Blocked profiles cannot perform any actions with the profile that blocked them: they cannot comment or mirror * their publications, they cannot follow them, they cannot collect, tip them, etc. * @custom:permissions Profile Owner or Delegated Executor. * * @dev Both the `idsOfProfilesToSetBlockStatus` and `blockStatus` arrays must be of the same length. * * @param byProfileId The ID of the profile that is blocking/unblocking somebody. * @param idsOfProfilesToSetBlockStatus The array of IDs of profiles to set block status. * @param blockStatus The array of block statuses to use for each (true is blocked). */ function setBlockStatus( uint256 byProfileId, uint256[] calldata idsOfProfilesToSetBlockStatus, bool[] calldata blockStatus ) external; /** * @custom:meta-tx setBlockStatus. */ function setBlockStatusWithSig( uint256 byProfileId, uint256[] calldata idsOfProfilesToSetBlockStatus, bool[] calldata blockStatus, Types.EIP712Signature calldata signature ) external; /** * @notice Collects a given publication via signature with the specified parameters. * Collect can have referrers (e.g. publications or profiles that allowed to discover the pointed publication). * @custom:permissions Collector Profile Owner or its Delegated Executor. * @custom:pending-deprecation Collect modules were replaced by PublicationAction Collect modules in V2. This method * is left here for backwards compatibility with posts made in V1 that had Collect modules. * * @param collectParams A CollectParams struct containing the parameters. * * @return uint256 An integer representing the minted token ID. */ function collectLegacy(Types.LegacyCollectParams calldata collectParams) external returns (uint256); /** * @custom:meta-tx collect. * @custom:pending-deprecation */ function collectLegacyWithSig( Types.LegacyCollectParams calldata collectParams, Types.EIP712Signature calldata signature ) external returns (uint256); /** * @notice Acts on a given publication with the specified parameters. * You can act on a publication except a mirror (if it has at least one action module initialized). * Actions can have referrers (e.g. publications or profiles that allowed to discover the pointed publication). * @custom:permissions Actor Profile Owner or its Delegated Executor. * * @param publicationActionParams A PublicationActionParams struct containing the parameters. * * @return bytes Arbitrary data the action module returns. */ function act(Types.PublicationActionParams calldata publicationActionParams) external returns (bytes memory); /** * @custom:meta-tx act. */ function actWithSig( Types.PublicationActionParams calldata publicationActionParams, Types.EIP712Signature calldata signature ) external returns (bytes memory); /** * @dev This function is used to invalidate signatures by incrementing the nonce of the signer. * @param increment The amount to increment the nonce by (max 255). */ function incrementNonce(uint8 increment) external; ///////////////////////////////// /// VIEW FUNCTIONS /// ///////////////////////////////// /** * @notice Returns whether or not `followerProfileId` is following `followedProfileId`. * * @param followerProfileId The ID of the profile whose following state should be queried. * @param followedProfileId The ID of the profile whose followed state should be queried. * * @return bool True if `followerProfileId` is following `followedProfileId`, false otherwise. */ function isFollowing(uint256 followerProfileId, uint256 followedProfileId) external view returns (bool); /** * @notice Returns whether the given address is approved as delegated executor, in the configuration with the given * number, to act on behalf of the given profile. * * @param delegatorProfileId The ID of the profile to check the delegated executor approval for. * @param delegatedExecutor The address to query the delegated executor approval for. * @param configNumber The number of the configuration where the executor approval state is being queried. * * @return bool True if the address is approved as a delegated executor to act on behalf of the profile in the * given configuration, false otherwise. */ function isDelegatedExecutorApproved( uint256 delegatorProfileId, address delegatedExecutor, uint64 configNumber ) external view returns (bool); /** * @notice Returns whether the given address is approved as delegated executor, in the current configuration, to act * on behalf of the given profile. * * @param delegatorProfileId The ID of the profile to check the delegated executor approval for. * @param delegatedExecutor The address to query the delegated executor approval for. * * @return bool True if the address is approved as a delegated executor to act on behalf of the profile in the * current configuration, false otherwise. */ function isDelegatedExecutorApproved( uint256 delegatorProfileId, address delegatedExecutor ) external view returns (bool); /** * @notice Returns the current delegated executor config number for the given profile. * * @param delegatorProfileId The ID of the profile from which the delegated executors config number is being queried * * @return uint256 The current delegated executor configuration number. */ function getDelegatedExecutorsConfigNumber(uint256 delegatorProfileId) external view returns (uint64); /** * @notice Returns the previous used delegated executor config number for the given profile. * * @param delegatorProfileId The ID of the profile from which the delegated executors' previous configuration number * set is being queried. * * @return uint256 The delegated executor configuration number previously set. It will coincide with the current * configuration set if it was never switched from the default one. */ function getDelegatedExecutorsPrevConfigNumber(uint256 delegatorProfileId) external view returns (uint64); /** * @notice Returns the maximum delegated executor config number for the given profile. * This is the maximum config number that was ever used by this profile. * When creating a new clean configuration, you can only use a number that is maxConfigNumber + 1. * * @param delegatorProfileId The ID of the profile from which the delegated executors' maximum configuration number * set is being queried. * * @return uint256 The delegated executor maximum configuration number set. */ function getDelegatedExecutorsMaxConfigNumberSet(uint256 delegatorProfileId) external view returns (uint64); /** * @notice Returns whether `profileId` is blocked by `byProfileId`. * See setBlockStatus() for more information on how blocking works on the platform. * * @param profileId The ID of the profile whose blocked status should be queried. * @param byProfileId The ID of the profile whose blocker status should be queried. * * @return bool True if `profileId` is blocked by `byProfileId`, false otherwise. */ function isBlocked(uint256 profileId, uint256 byProfileId) external view returns (bool); /** * @notice Returns the URI associated with a given publication. * This is used to store the publication's metadata, e.g.: content, images, etc. * * @param profileId The token ID of the profile that published the publication to query. * @param pubId The publication ID of the publication to query. * * @return string The URI associated with a given publication. */ function getContentURI(uint256 profileId, uint256 pubId) external view returns (string memory); /** * @notice Returns the full profile struct associated with a given profile token ID. * * @param profileId The token ID of the profile to query. * * @return Profile The profile struct of the given profile. */ function getProfile(uint256 profileId) external view returns (Types.Profile memory); /** * @notice Returns the full publication struct for a given publication. * * @param profileId The token ID of the profile that published the publication to query. * @param pubId The publication ID of the publication to query. * * @return Publication The publication struct associated with the queried publication. */ function getPublication(uint256 profileId, uint256 pubId) external view returns (Types.PublicationMemory memory); /** * @notice Returns the type of a given publication. * The type can be one of the following (see PublicationType enum): * - Nonexistent * - Post * - Comment * - Mirror * - Quote * * @param profileId The token ID of the profile that published the publication to query. * @param pubId The publication ID of the publication to query. * * @return PublicationType The publication type of the queried publication. */ function getPublicationType(uint256 profileId, uint256 pubId) external view returns (Types.PublicationType); /** * @notice Returns wether a given Action Module is enabled for a given publication. * * @param profileId The token ID of the profile that published the publication to query. * @param pubId The publication ID of the publication to query. * @param module The address of the Action Module to query. * * @return bool True if the Action Module is enabled for the queried publication, false if not. */ function isActionModuleEnabledInPublication( uint256 profileId, uint256 pubId, address module ) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title ILensVersion * @author Lens Protocol * * @notice This is the interface for the LensHub Version getters and emitter. * It allows to emit a LensHub version during an upgrade, and also to get the current version. */ interface ILensVersion { /** * @notice Returns the LensHub current Version. * * @return version The LensHub current Version. */ function getVersion() external view returns (string memory); /** * @notice Returns the LensHub current Git Commit. * * @return gitCommit The LensHub current Git Commit. */ function getGitCommit() external view returns (bytes20); /** * @notice Emits the LensHub current Version. Used in upgradeAndCall(). */ function emitVersion() external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; interface IModuleRegistry { enum ModuleType { __, // Just to avoid 0 as valid ModuleType PUBLICATION_ACTION_MODULE, REFERENCE_MODULE, FOLLOW_MODULE } // Modules functions function verifyModule(address moduleAddress, uint256 moduleType) external returns (bool); function registerModule(address moduleAddress, uint256 moduleType) external returns (bool); function getModuleTypes(address moduleAddress) external view returns (uint256); function isModuleRegistered(address moduleAddress) external view returns (bool); function isModuleRegisteredAs(address moduleAddress, uint256 moduleType) external view returns (bool); // Currencies functions function verifyErc20Currency(address currencyAddress) external returns (bool); function registerErc20Currency(address currencyAddress) external returns (bool); function isErc20CurrencyRegistered(address currencyAddress) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {Types} from 'contracts/libraries/constants/Types.sol'; /** * @title IPublicationAction * @author Lens Protocol * * @notice This is the standard interface for all Lens-compatible Publication Actions. * Publication action modules allow users to execute actions directly from a publication, like: * - Minting NFTs. * - Collecting a publication. * - Sending funds to the publication author (e.g. tipping). * - Etc. * Referrers are supported, so any publication or profile that references the publication can receive a share from the * publication's action if the action module supports it. */ interface IPublicationActionModule { /** * @notice Initializes the action module for the given publication being published with this Action module. * @custom:permissions LensHub. * * @param profileId The profile ID of the author publishing the content with this Publication Action. * @param pubId The publication ID being published. * @param transactionExecutor The address of the transaction executor (e.g. for any funds to transferFrom). * @param data Arbitrary data passed from the user to be decoded by the Action Module during initialization. * * @return bytes Any custom ABI-encoded data. This will be a LensHub event params that can be used by * indexers or UIs. */ function initializePublicationAction( uint256 profileId, uint256 pubId, address transactionExecutor, bytes calldata data ) external returns (bytes memory); /** * @notice Processes the action for a given publication. This includes the action's logic and any monetary/token * operations. * @custom:permissions LensHub. * * @param processActionParams The parameters needed to execute the publication action. * * @return bytes Any custom ABI-encoded data. This will be a LensHub event params that can be used by * indexers or UIs. */ function processPublicationAction(Types.ProcessActionParams calldata processActionParams) external returns (bytes memory); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {Types} from 'contracts/libraries/constants/Types.sol'; /** * @title IReferenceModule * @author Lens Protocol * * @notice This is the standard interface for all Lens-compatible ReferenceModules. * Reference modules allow executing some action when a publication is referenced, like: * - Rewards for mirroring/commenting/quoting a publication. * - Token-gated comments/mirrors/quotes of a publication. * - Etc. */ interface IReferenceModule { /** * @notice Initializes data for the given publication being published with this Reference module. * @custom:permissions LensHub. * * @param profileId The token ID of the profile publishing the publication. * @param pubId The associated publication's LensHub publication ID. * @param transactionExecutor The address of the transaction executor (e.g. for any funds to transferFrom). * @param data Arbitrary data passed from the user to be decoded by the Reference Module during initialization. * * @return bytes Any custom ABI-encoded data. This will be a LensHub event params that can be used by * indexers or UIs. */ function initializeReferenceModule( uint256 profileId, uint256 pubId, address transactionExecutor, bytes calldata data ) external returns (bytes memory); /** * @notice Processes a comment being published. This includes any module logic like transferring tokens, * checking for conditions (e.g. token-gated), etc. * @custom:permissions LensHub. * * @param processCommentParams The parameters for processing a comment. * * @return bytes Any custom ABI-encoded data. This will be a LensHub event params that can be used by * indexers or UIs. */ function processComment(Types.ProcessCommentParams calldata processCommentParams) external returns (bytes memory); /** * @notice Processes a quote being published. This includes any module logic like transferring tokens, * checking for conditions (e.g. token-gated), etc. * @custom:permissions LensHub * * @param processQuoteParams The parameters for processing a quote. * * @return bytes Any custom ABI-encoded data. This will be a LensHub event params that can be used by * indexers or UIs. */ function processQuote(Types.ProcessQuoteParams calldata processQuoteParams) external returns (bytes memory); /** * @notice Processes a mirror being published. This includes any module logic like transferring tokens, * checking for conditions (e.g. token-gated), etc. * @custom:permissions LensHub * * @param processMirrorParams The parameters for processing a mirror. * * @return bytes Any custom ABI-encoded data. This will be a LensHub event params that can be used by * indexers or UIs. */ function processMirror(Types.ProcessMirrorParams calldata processMirrorParams) external returns (bytes memory); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title ITokenHandleRegistry * @author Lens Protocol * * @notice The interface for TokenHandleRegistry contract that is responsible for linking a handle NFT to a token NFT. * Linking means a connection between the two NFTs is created, and the handle NFT can be used to resolve the token NFT * or vice versa. * The registry is responsible for keeping track of the links between the NFTs, and for resolving them. * The first version of the registry is hard-coded to support only the .lens namespace and the Lens Protocol Profiles. */ interface ITokenHandleRegistry { /** * @notice Lens V1 -> V2 migration function. Links a handle NFT to a profile NFT without additional checks to save * gas. * Will be called by the migration function (in MigrationLib) in LensHub, only for new handles being migrated. * * @custom:permissions LensHub * * @param handleId ID of the .lens namespace handle NFT * @param profileId ID of the Lens Protocol Profile NFT */ function migrationLink(uint256 handleId, uint256 profileId) external; /** * @notice Links a handle NFT with a profile NFT. * Linking means a connection between the two NFTs is created, and the handle NFT can be used to resolve the profile * NFT or vice versa. * @custom:permissions Both NFTs must be owned by the same address, and caller must be the owner of profile or its * approved DelegatedExecutor. * * @dev In the first version of the registry, the NFT contracts are hard-coded: * - Handle is hard-coded to be of the .lens namespace * - Token is hard-coded to be of the Lens Protocol Profile * In future versions, the registry will be more flexible and allow for different namespaces and tokens, so this * function might be deprecated and replaced with a new one accepting addresses of the handle and token contracts. * * @param handleId ID of the .lens namespace handle NFT * @param profileId ID of the Lens Protocol Profile NFT */ function link(uint256 handleId, uint256 profileId) external; /** * @notice Unlinks a handle NFT from a profile NFT. * @custom:permissions Caller can be the owner of either of the NFTs. * * @dev In the first version of the registry, the contracts are hard-coded: * - Handle is hard-coded to be of the .lens namespace * - Token is hard-coded to be of the Lens Protocol Profile * In future versions, the registry will be more flexible and allow for different namespaces and tokens, so this * function might be deprecated and replaced with a new one accepting addresses of the handle and token contracts. * * @param handleId ID of the .lens namespace handle NFT * @param profileId ID of the Lens Protocol Profile NFT */ function unlink(uint256 handleId, uint256 profileId) external; /** * @notice Resolves a handle NFT to a profile NFT. * * @dev In the first version of the registry, the contracts are hard-coded: * - Handle is hard-coded to be of the .lens namespace * - Token is hard-coded to be of the Lens Protocol Profile * In future versions, the registry will be more flexible and allow for different namespaces and tokens, so this * function might be deprecated and replaced with a new one. * * @param handleId ID of the .lens namespace handle NFT * * @return tokenId ID of the Lens Protocol Profile NFT */ function resolve(uint256 handleId) external view returns (uint256); /** * @notice Gets a default handle for a profile NFT (aka reverse resolution). * * @dev In the first version of the registry, the contracts are hard-coded: * - Handle is hard-coded to be of the .lens namespace * - Token is hard-coded to be of the Lens Protocol Profile * In future versions, the registry will be more flexible and allow for different namespaces and tokens, so this * function might be deprecated and replaced with a new one. * * @param tokenId ID of the Lens Protocol Profile NFT * * @return handleId ID of the .lens namespace handle NFT */ function getDefaultHandle(uint256 tokenId) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {IERC1271} from '@openzeppelin/contracts/interfaces/IERC1271.sol'; import {ILensERC721} from 'contracts/interfaces/ILensERC721.sol'; import {Types} from 'contracts/libraries/constants/Types.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {Typehash} from 'contracts/libraries/constants/Typehash.sol'; import {StorageLib} from 'contracts/libraries/StorageLib.sol'; import {Events} from 'contracts/libraries/constants/Events.sol'; /** * @title MetaTxLib * @author Lens Protocol * * NOTE: the functions in this contract operate under the assumption that the passed signer is already validated * to either be the originator or one of their delegated executors. * * @dev User nonces are incremented from this library as well. */ library MetaTxLib { string constant EIP712_DOMAIN_VERSION = '2'; bytes32 constant EIP712_DOMAIN_VERSION_HASH = keccak256(bytes(EIP712_DOMAIN_VERSION)); bytes4 constant EIP1271_MAGIC_VALUE = 0x1626ba7e; /** * @dev We store the domain separator and LensHub Proxy address as constants to save gas. * * keccak256( * abi.encode( * keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), * keccak256('Lens Protocol Profiles'), // Contract Name * keccak256('2'), // Version Hash * 137, // Polygon Chain ID * address(0xDb46d1Dc155634FbC732f92E853b10B288AD5a1d) // Verifying Contract Address - LensHub Address * ) * ); */ bytes32 constant LENS_HUB_CACHED_POLYGON_DOMAIN_SEPARATOR = 0xbf9544cf7d7a0338fc4f071be35409a61e51e9caef559305410ad74e16a05f2d; address constant LENS_HUB_ADDRESS = 0xDb46d1Dc155634FbC732f92E853b10B288AD5a1d; uint256 constant POLYGON_CHAIN_ID = 137; function validateSetProfileMetadataURISignature( Types.EIP712Signature calldata signature, uint256 profileId, string calldata metadataURI ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.SET_PROFILE_METADATA_URI, profileId, _encodeUsingEip712Rules(metadataURI), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateSetFollowModuleSignature( Types.EIP712Signature calldata signature, uint256 profileId, address followModule, bytes calldata followModuleInitData ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.SET_FOLLOW_MODULE, profileId, followModule, _encodeUsingEip712Rules(followModuleInitData), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateChangeDelegatedExecutorsConfigSignature( Types.EIP712Signature calldata signature, uint256 delegatorProfileId, address[] calldata delegatedExecutors, bool[] calldata approvals, uint64 configNumber, bool switchToGivenConfig ) external { address signer = signature.signer; uint256 deadline = signature.deadline; _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.CHANGE_DELEGATED_EXECUTORS_CONFIG, delegatorProfileId, _encodeUsingEip712Rules(delegatedExecutors), _encodeUsingEip712Rules(approvals), configNumber, switchToGivenConfig, _getNonceIncrementAndEmitEvent(signer), deadline ) ) ), signature ); } function validatePostSignature( Types.EIP712Signature calldata signature, Types.PostParams calldata postParams ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.POST, postParams.profileId, _encodeUsingEip712Rules(postParams.contentURI), _encodeUsingEip712Rules(postParams.actionModules), _encodeUsingEip712Rules(postParams.actionModulesInitDatas), postParams.referenceModule, _encodeUsingEip712Rules(postParams.referenceModuleInitData), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateCommentSignature( Types.EIP712Signature calldata signature, Types.CommentParams calldata commentParams ) external { bytes memory encodedAbi = abi.encode( Typehash.COMMENT, commentParams.profileId, _encodeUsingEip712Rules(commentParams.contentURI), commentParams.pointedProfileId, commentParams.pointedPubId, _encodeUsingEip712Rules(commentParams.referrerProfileIds), _encodeUsingEip712Rules(commentParams.referrerPubIds), _encodeUsingEip712Rules(commentParams.referenceModuleData), _encodeUsingEip712Rules(commentParams.actionModules), _encodeUsingEip712Rules(commentParams.actionModulesInitDatas), commentParams.referenceModule, _encodeUsingEip712Rules(commentParams.referenceModuleInitData), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ); _validateRecoveredAddress(_calculateDigest(keccak256(encodedAbi)), signature); } function validateQuoteSignature( Types.EIP712Signature calldata signature, Types.QuoteParams calldata quoteParams ) external { bytes memory encodedAbi = abi.encode( Typehash.QUOTE, quoteParams.profileId, _encodeUsingEip712Rules(quoteParams.contentURI), quoteParams.pointedProfileId, quoteParams.pointedPubId, _encodeUsingEip712Rules(quoteParams.referrerProfileIds), _encodeUsingEip712Rules(quoteParams.referrerPubIds), _encodeUsingEip712Rules(quoteParams.referenceModuleData), _encodeUsingEip712Rules(quoteParams.actionModules), _encodeUsingEip712Rules(quoteParams.actionModulesInitDatas), quoteParams.referenceModule, _encodeUsingEip712Rules(quoteParams.referenceModuleInitData), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ); _validateRecoveredAddress(_calculateDigest(keccak256(encodedAbi)), signature); } function validateMirrorSignature( Types.EIP712Signature calldata signature, Types.MirrorParams calldata mirrorParams ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.MIRROR, mirrorParams.profileId, _encodeUsingEip712Rules(mirrorParams.metadataURI), mirrorParams.pointedProfileId, mirrorParams.pointedPubId, _encodeUsingEip712Rules(mirrorParams.referrerProfileIds), _encodeUsingEip712Rules(mirrorParams.referrerPubIds), _encodeUsingEip712Rules(mirrorParams.referenceModuleData), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateFollowSignature( Types.EIP712Signature calldata signature, uint256 followerProfileId, uint256[] calldata idsOfProfilesToFollow, uint256[] calldata followTokenIds, bytes[] calldata datas ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.FOLLOW, followerProfileId, _encodeUsingEip712Rules(idsOfProfilesToFollow), _encodeUsingEip712Rules(followTokenIds), _encodeUsingEip712Rules(datas), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateUnfollowSignature( Types.EIP712Signature calldata signature, uint256 unfollowerProfileId, uint256[] calldata idsOfProfilesToUnfollow ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.UNFOLLOW, unfollowerProfileId, _encodeUsingEip712Rules(idsOfProfilesToUnfollow), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateSetBlockStatusSignature( Types.EIP712Signature calldata signature, uint256 byProfileId, uint256[] calldata idsOfProfilesToSetBlockStatus, bool[] calldata blockStatus ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.SET_BLOCK_STATUS, byProfileId, _encodeUsingEip712Rules(idsOfProfilesToSetBlockStatus), _encodeUsingEip712Rules(blockStatus), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateLegacyCollectSignature( Types.EIP712Signature calldata signature, Types.LegacyCollectParams calldata collectParams ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.COLLECT_LEGACY, collectParams.publicationCollectedProfileId, collectParams.publicationCollectedId, collectParams.collectorProfileId, collectParams.referrerProfileId, collectParams.referrerPubId, _encodeUsingEip712Rules(collectParams.collectModuleData), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function validateActSignature( Types.EIP712Signature calldata signature, Types.PublicationActionParams calldata publicationActionParams ) external { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.ACT, publicationActionParams.publicationActedProfileId, publicationActionParams.publicationActedId, publicationActionParams.actorProfileId, _encodeUsingEip712Rules(publicationActionParams.referrerProfileIds), _encodeUsingEip712Rules(publicationActionParams.referrerPubIds), publicationActionParams.actionModuleAddress, _encodeUsingEip712Rules(publicationActionParams.actionModuleData), _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } /// @dev This function is used to invalidate signatures by incrementing the nonce function incrementNonce(uint8 increment) external { uint256 currentNonce = StorageLib.nonces()[msg.sender]; StorageLib.nonces()[msg.sender] = currentNonce + increment; emit Events.NonceUpdated(msg.sender, currentNonce + increment, block.timestamp); } function calculateDomainSeparator() internal view returns (bytes32) { if (address(this) == LENS_HUB_ADDRESS && block.chainid == POLYGON_CHAIN_ID) { return LENS_HUB_CACHED_POLYGON_DOMAIN_SEPARATOR; } return keccak256( abi.encode( Typehash.EIP712_DOMAIN, keccak256(bytes(ILensERC721(address(this)).name())), EIP712_DOMAIN_VERSION_HASH, block.chainid, address(this) ) ); } /** * @dev Wrapper for ecrecover to reduce code size, used in meta-tx specific functions. */ function _validateRecoveredAddress(bytes32 digest, Types.EIP712Signature calldata signature) private view { if (block.timestamp > signature.deadline) revert Errors.SignatureExpired(); // If the expected address is a contract, check the signature there. if (signature.signer.code.length != 0) { bytes memory concatenatedSig = abi.encodePacked(signature.r, signature.s, signature.v); if (IERC1271(signature.signer).isValidSignature(digest, concatenatedSig) != EIP1271_MAGIC_VALUE) { revert Errors.SignatureInvalid(); } } else { address recoveredAddress = ecrecover(digest, signature.v, signature.r, signature.s); if (recoveredAddress == address(0) || recoveredAddress != signature.signer) { revert Errors.SignatureInvalid(); } } } /** * @dev Calculates EIP712 digest based on the current DOMAIN_SEPARATOR. * * @param hashedMessage The message hash from which the digest should be calculated. * * @return bytes32 A 32-byte output representing the EIP712 digest. */ function _calculateDigest(bytes32 hashedMessage) private view returns (bytes32) { return keccak256(abi.encodePacked('\x19\x01', calculateDomainSeparator(), hashedMessage)); } /** * @dev This fetches a signer's current nonce and increments it so it's ready for the next meta-tx. Also emits * the `NonceUpdated` event. * * @param signer The address to get and increment the nonce for. * * @return uint256 The current nonce for the given signer prior to being incremented. */ function _getNonceIncrementAndEmitEvent(address signer) private returns (uint256) { uint256 currentNonce; unchecked { currentNonce = StorageLib.nonces()[signer]++; } emit Events.NonceUpdated(signer, currentNonce + 1, block.timestamp); return currentNonce; } function _encodeUsingEip712Rules(bytes[] memory bytesArray) private pure returns (bytes32) { bytes32[] memory bytesArrayEncodedElements = new bytes32[](bytesArray.length); uint256 i; while (i < bytesArray.length) { // A `bytes` type is encoded as its keccak256 hash. bytesArrayEncodedElements[i] = _encodeUsingEip712Rules(bytesArray[i]); unchecked { ++i; } } // An array is encoded as the keccak256 hash of the concatenation of their encoded elements. return _encodeUsingEip712Rules(bytesArrayEncodedElements); } function _encodeUsingEip712Rules(bool[] memory boolArray) private pure returns (bytes32) { return keccak256(abi.encodePacked(boolArray)); } function _encodeUsingEip712Rules(address[] memory addressArray) private pure returns (bytes32) { return keccak256(abi.encodePacked(addressArray)); } function _encodeUsingEip712Rules(uint256[] memory uint256Array) private pure returns (bytes32) { return keccak256(abi.encodePacked(uint256Array)); } function _encodeUsingEip712Rules(bytes32[] memory bytes32Array) private pure returns (bytes32) { return keccak256(abi.encodePacked(bytes32Array)); } function _encodeUsingEip712Rules(string memory stringValue) private pure returns (bytes32) { return keccak256(bytes(stringValue)); } function _encodeUsingEip712Rules(bytes memory bytesValue) private pure returns (bytes32) { return keccak256(bytesValue); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {Events} from 'contracts/libraries/constants/Events.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {StorageLib} from 'contracts/libraries/StorageLib.sol'; import {FollowNFT} from 'contracts/FollowNFT.sol'; import {LensHandles} from 'contracts/namespaces/LensHandles.sol'; import {TokenHandleRegistry} from 'contracts/namespaces/TokenHandleRegistry.sol'; import {IFollowModule} from 'contracts/interfaces/IFollowModule.sol'; interface ILegacyFeeFollowModule { struct ProfileData { address currency; uint256 amount; address recipient; } function getProfileData(uint256 profileId) external view returns (ProfileData memory); } library MigrationLib { uint256 internal constant LENS_PROTOCOL_PROFILE_ID = 1; uint256 internal constant DOT_LENS_SUFFIX_LENGTH = 5; // Profiles Handles Migration: event ProfileMigrated(uint256 indexed profileId); /** * @notice Migrates an array of profiles from V1 to V2. This function can be callable by anyone. * We would still perform the migration in batches by ourselves, but good to allow users to migrate on their own if they want to. * * @param profileIds The array of profile IDs to migrate. */ function batchMigrateProfiles( uint256[] calldata profileIds, LensHandles lensHandles, TokenHandleRegistry tokenHandleRegistry ) external { uint256 i; while (i < profileIds.length) { _migrateProfile(profileIds[i], lensHandles, tokenHandleRegistry); unchecked { ++i; } } } /** * @notice Migrates a profile from V1 to V2. * * @dev We do not revert in any case, as we want to allow the migration to continue even if one profile fails * (and it usually fails if already migrated or profileNFT moved). * @dev Estimated gas cost of one profile migration is around 178k gas. * * @param profileId The profile ID to migrate. */ function _migrateProfile( uint256 profileId, LensHandles lensHandles, TokenHandleRegistry tokenHandleRegistry ) private { address profileOwner = StorageLib.getTokenData(profileId).owner; // We check if the profile exists by checking owner != address(0). if (profileOwner != address(0)) { // We check if the profile has already been migrated by checking __DEPRECATED__handle != "". string memory handle = StorageLib.getProfile(profileId).__DEPRECATED__handle; if (bytes(handle).length == 0) { return; // Already migrated } bytes32 handleHash = keccak256(bytes(handle)); // We check if the profile is the "lensprotocol" profile by checking profileId != 1. // "lensprotocol" is the only edge case without the .lens suffix: if (profileId != LENS_PROTOCOL_PROFILE_ID) { assembly { let handle_length := mload(handle) mstore(handle, sub(handle_length, DOT_LENS_SUFFIX_LENGTH)) // Cut 5 chars (.lens) from the end } } // We mint a new handle on the LensHandles contract. The resulting handle NFT is sent to the profile owner. uint256 handleId = lensHandles.migrateHandle(profileOwner, handle); // We link it to the profile in the TokenHandleRegistry contract. tokenHandleRegistry.migrationLink(handleId, profileId); emit ProfileMigrated(profileId); delete StorageLib.getProfile(profileId).__DEPRECATED__handle; delete StorageLib.getProfile(profileId).__DEPRECATED__followNFTURI; delete StorageLib.profileIdByHandleHash()[handleHash]; if (StorageLib.getDelegatedExecutorsConfig(profileId).configNumber == 0) { // This event can be duplicated, and then redundant, if the profile has already configured the Delegated // Executors before being migrated. Given that this is an edge case, we exceptionally accept this // redundancy considering that the event is still consistent with the state. emit Events.DelegatedExecutorsConfigApplied(profileId, 0, block.timestamp); } } } // FollowNFT Migration: function batchMigrateFollows( uint256 followerProfileId, uint256[] calldata idsOfProfileFollowed, uint256[] calldata followTokenIds ) external { if (idsOfProfileFollowed.length != followTokenIds.length) { revert Errors.ArrayMismatch(); } uint256 i; while (i < idsOfProfileFollowed.length) { _migrateFollow( StorageLib.getProfile(idsOfProfileFollowed[i]).followNFT, followerProfileId, // one follower for all the follows idsOfProfileFollowed[i], followTokenIds[i] ); unchecked { ++i; } } } function batchMigrateFollowers( uint256[] calldata followerProfileIds, uint256 idOfProfileFollowed, uint256[] calldata followTokenIds ) external { if (followerProfileIds.length != followTokenIds.length) { revert Errors.ArrayMismatch(); } address followNFT = StorageLib.getProfile(idOfProfileFollowed).followNFT; uint256 i; while (i < followTokenIds.length) { _migrateFollow( followNFT, followerProfileIds[i], idOfProfileFollowed, // one profile followed -> one FollowNFT followTokenIds[i] ); unchecked { ++i; } } } function _migrateFollow( address followNFT, uint256 followerProfileId, uint256 idOfProfileFollowed, uint256 followTokenId ) private { if (StorageLib.blockedStatus(idOfProfileFollowed)[followerProfileId]) { return; // Cannot follow if blocked } if (followerProfileId == idOfProfileFollowed) { return; // Cannot self-follow } uint48 mintTimestamp = FollowNFT(followNFT).tryMigrate({ followerProfileId: followerProfileId, followerProfileOwner: StorageLib.getTokenData(followerProfileId).owner, followTokenId: followTokenId }); // `mintTimestamp` will be 0 if: // - Follow NFT was already migrated // - Follow NFT does not exist or was burnt // - Follower profile Owner is different from Follow NFT Owner if (mintTimestamp != 0) { emit Events.Followed({ followerProfileId: followerProfileId, idOfProfileFollowed: idOfProfileFollowed, followTokenIdAssigned: followTokenId, followModuleData: '', processFollowModuleReturnData: '', transactionExecutor: address(0), // For migrations, we use this special value as transaction executor. timestamp: mintTimestamp // The only case where this won't match block.timestamp is during the migration }); } } function batchMigrateFollowModules( uint256[] calldata profileIds, address legacyFeeFollowModule, address legacyProfileFollowModule, address newFeeFollowModule ) external { uint256 i; while (i < profileIds.length) { address currentFollowModule = StorageLib.getProfile(profileIds[i]).followModule; if (currentFollowModule == legacyFeeFollowModule) { // If the profile had the legacy 'feeFollowModule' set, we need to read its parameters // and initialize the new feeFollowModule with them. StorageLib.getProfile(profileIds[i]).followModule = newFeeFollowModule; ILegacyFeeFollowModule.ProfileData memory feeFollowModuleData = ILegacyFeeFollowModule( legacyFeeFollowModule ).getProfileData(profileIds[i]); bytes memory followModuleInitData = abi.encode( feeFollowModuleData.currency, feeFollowModuleData.amount, feeFollowModuleData.recipient ); bytes memory followModuleReturnData = IFollowModule(newFeeFollowModule).initializeFollowModule({ profileId: profileIds[i], transactionExecutor: address(0), data: followModuleInitData }); emit Events.FollowModuleSet( profileIds[i], newFeeFollowModule, followModuleInitData, followModuleReturnData, address(0), block.timestamp ); } else if (currentFollowModule == legacyProfileFollowModule) { // If the profile had `ProfileFollowModule` set, we just remove the follow module, as in Lens V2 // you can only follow with a Lens profile. delete StorageLib.getProfile(profileIds[i]).followModule; emit Events.FollowModuleSet(profileIds[i], address(0), '', '', address(0), block.timestamp); } unchecked { ++i; } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {ValidationLib} from 'contracts/libraries/ValidationLib.sol'; import {Types} from 'contracts/libraries/constants/Types.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {Events} from 'contracts/libraries/constants/Events.sol'; import {StorageLib} from 'contracts/libraries/StorageLib.sol'; import {IFollowModule} from 'contracts/interfaces/IFollowModule.sol'; import {IFollowNFT} from 'contracts/interfaces/IFollowNFT.sol'; import {IModuleRegistry} from 'contracts/interfaces/IModuleRegistry.sol'; import {ILensHub} from 'contracts/interfaces/ILensHub.sol'; library ProfileLib { function MODULE_REGISTRY() internal view returns (IModuleRegistry) { return IModuleRegistry(ILensHub(address(this)).getModuleRegistry()); } function ownerOf(uint256 profileId) internal view returns (address) { address profileOwner = StorageLib.getTokenData(profileId).owner; if (profileOwner == address(0)) { revert Errors.TokenDoesNotExist(); } return profileOwner; } function exists(uint256 profileId) internal view returns (bool) { return StorageLib.getTokenData(profileId).owner != address(0); } /** * @notice Creates a profile with the given parameters to the given address. Minting happens * in the hub. * * @param createProfileParams The CreateProfileParams struct containing the following parameters: * to: The address receiving the profile. * followModule: The follow module to use, can be the zero address. * followModuleInitData: The follow module initialization data, if any * @param profileId The profile ID to associate with this profile NFT (token ID). */ function createProfile(Types.CreateProfileParams calldata createProfileParams, uint256 profileId) external { emit Events.ProfileCreated(profileId, msg.sender, createProfileParams.to, block.timestamp); emit Events.DelegatedExecutorsConfigApplied(profileId, 0, block.timestamp); _setFollowModule( profileId, createProfileParams.followModule, createProfileParams.followModuleInitData, msg.sender // Sender accounts for any initialization requirements (e.g. pay fees, stake asset, etc.). ); } /** * @notice Sets the follow module for a given profile. * * @param profileId The profile ID to set the follow module for. * @param followModule The follow module to set for the given profile, if any. * @param followModuleInitData The data to pass to the follow module for profile initialization. */ function setFollowModule( uint256 profileId, address followModule, bytes calldata followModuleInitData, address transactionExecutor ) external { _setFollowModule(profileId, followModule, followModuleInitData, transactionExecutor); } function setProfileMetadataURI( uint256 profileId, string calldata metadataURI, address transactionExecutor ) external { StorageLib.getProfile(profileId).metadataURI = metadataURI; emit Events.ProfileMetadataSet(profileId, metadataURI, transactionExecutor, block.timestamp); } function _initFollowModule( uint256 profileId, address transactionExecutor, address followModule, bytes memory followModuleInitData ) private returns (bytes memory) { MODULE_REGISTRY().verifyModule(followModule, uint256(IModuleRegistry.ModuleType.FOLLOW_MODULE)); return IFollowModule(followModule).initializeFollowModule(profileId, transactionExecutor, followModuleInitData); } function setBlockStatus( uint256 byProfileId, uint256[] calldata idsOfProfilesToSetBlockStatus, bool[] calldata blockStatus, address transactionExecutor ) external { if (idsOfProfilesToSetBlockStatus.length != blockStatus.length) { revert Errors.ArrayMismatch(); } address followNFT = StorageLib.getProfile(byProfileId).followNFT; uint256 i; uint256 idOfProfileToSetBlockStatus; bool blockedStatus; mapping(uint256 => bool) storage _blockedStatus = StorageLib.blockedStatus(byProfileId); while (i < idsOfProfilesToSetBlockStatus.length) { idOfProfileToSetBlockStatus = idsOfProfilesToSetBlockStatus[i]; ValidationLib.validateProfileExists(idOfProfileToSetBlockStatus); if (byProfileId == idOfProfileToSetBlockStatus) { revert Errors.SelfBlock(); } blockedStatus = blockStatus[i]; if (followNFT != address(0) && blockedStatus) { bool hasUnfollowed = IFollowNFT(followNFT).processBlock(idOfProfileToSetBlockStatus); if (hasUnfollowed) { emit Events.Unfollowed( idOfProfileToSetBlockStatus, byProfileId, transactionExecutor, block.timestamp ); } } _blockedStatus[idOfProfileToSetBlockStatus] = blockedStatus; if (blockedStatus) { emit Events.Blocked(byProfileId, idOfProfileToSetBlockStatus, transactionExecutor, block.timestamp); } else { emit Events.Unblocked(byProfileId, idOfProfileToSetBlockStatus, transactionExecutor, block.timestamp); } unchecked { ++i; } } } function switchToNewFreshDelegatedExecutorsConfig(uint256 profileId) external { Types.DelegatedExecutorsConfig storage _delegatedExecutorsConfig = StorageLib.getDelegatedExecutorsConfig({ delegatorProfileId: profileId }); _changeDelegatedExecutorsConfig({ _delegatedExecutorsConfig: _delegatedExecutorsConfig, delegatorProfileId: profileId, delegatedExecutors: new address[](0), approvals: new bool[](0), configNumber: _delegatedExecutorsConfig.maxConfigNumberSet + 1, switchToGivenConfig: true }); } function changeDelegatedExecutorsConfig( uint256 delegatorProfileId, address[] calldata delegatedExecutors, bool[] calldata approvals ) external { Types.DelegatedExecutorsConfig storage _delegatedExecutorsConfig = StorageLib.getDelegatedExecutorsConfig( delegatorProfileId ); _changeDelegatedExecutorsConfig( _delegatedExecutorsConfig, delegatorProfileId, delegatedExecutors, approvals, _delegatedExecutorsConfig.configNumber, false ); } function changeGivenDelegatedExecutorsConfig( uint256 delegatorProfileId, address[] calldata delegatedExecutors, bool[] calldata approvals, uint64 configNumber, bool switchToGivenConfig ) external { _changeDelegatedExecutorsConfig( StorageLib.getDelegatedExecutorsConfig(delegatorProfileId), delegatorProfileId, delegatedExecutors, approvals, configNumber, switchToGivenConfig ); } function isExecutorApproved(uint256 delegatorProfileId, address delegatedExecutor) external view returns (bool) { Types.DelegatedExecutorsConfig storage _delegatedExecutorsConfig = StorageLib.getDelegatedExecutorsConfig( delegatorProfileId ); return _delegatedExecutorsConfig.isApproved[_delegatedExecutorsConfig.configNumber][delegatedExecutor]; } function _changeDelegatedExecutorsConfig( Types.DelegatedExecutorsConfig storage _delegatedExecutorsConfig, uint256 delegatorProfileId, address[] memory delegatedExecutors, bool[] memory approvals, uint64 configNumber, bool switchToGivenConfig ) private { if (delegatedExecutors.length != approvals.length) { revert Errors.ArrayMismatch(); } bool configSwitched = _prepareStorageToApplyChangesUnderGivenConfig( _delegatedExecutorsConfig, configNumber, switchToGivenConfig ); uint256 i; while (i < delegatedExecutors.length) { _delegatedExecutorsConfig.isApproved[configNumber][delegatedExecutors[i]] = approvals[i]; unchecked { ++i; } } emit Events.DelegatedExecutorsConfigChanged( delegatorProfileId, configNumber, delegatedExecutors, approvals, block.timestamp ); if (configSwitched) { emit Events.DelegatedExecutorsConfigApplied(delegatorProfileId, configNumber, block.timestamp); } } function _prepareStorageToApplyChangesUnderGivenConfig( Types.DelegatedExecutorsConfig storage _delegatedExecutorsConfig, uint64 configNumber, bool switchToGivenConfig ) private returns (bool) { uint64 nextAvailableConfigNumber = _delegatedExecutorsConfig.maxConfigNumberSet + 1; if (configNumber > nextAvailableConfigNumber) { revert Errors.InvalidParameter(); } bool configSwitched; if (configNumber == nextAvailableConfigNumber) { // The next configuration available is being changed, it must be marked. // Otherwise, on a profile transfer, the next owner can inherit a used/dirty configuration. _delegatedExecutorsConfig.maxConfigNumberSet = nextAvailableConfigNumber; configSwitched = switchToGivenConfig; if (configSwitched) { // The configuration is being switched, previous and current configuration numbers must be updated. _delegatedExecutorsConfig.prevConfigNumber = _delegatedExecutorsConfig.configNumber; _delegatedExecutorsConfig.configNumber = nextAvailableConfigNumber; } } else { // The configuration corresponding to the given number is not a fresh/clean one. uint64 currentConfigNumber = _delegatedExecutorsConfig.configNumber; // If the given configuration matches the one that is already in use, we keep `configSwitched` as `false`. if (configNumber != currentConfigNumber) { configSwitched = switchToGivenConfig; } if (configSwitched) { // The configuration is being switched, previous and current configuration numbers must be updated. _delegatedExecutorsConfig.prevConfigNumber = currentConfigNumber; _delegatedExecutorsConfig.configNumber = configNumber; } } return configSwitched; } function _setFollowModule( uint256 profileId, address followModule, bytes calldata followModuleInitData, address transactionExecutor ) private { StorageLib.getProfile(profileId).followModule = followModule; bytes memory followModuleReturnData; if (followModule != address(0)) { followModuleReturnData = _initFollowModule( profileId, transactionExecutor, followModule, followModuleInitData ); } emit Events.FollowModuleSet( profileId, followModule, followModuleInitData, followModuleReturnData, transactionExecutor, block.timestamp ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {ValidationLib} from 'contracts/libraries/ValidationLib.sol'; import {Types} from 'contracts/libraries/constants/Types.sol'; import {Events} from 'contracts/libraries/constants/Events.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {IReferenceModule} from 'contracts/interfaces/IReferenceModule.sol'; import {ILegacyReferenceModule} from 'contracts/interfaces/ILegacyReferenceModule.sol'; import {StorageLib} from 'contracts/libraries/StorageLib.sol'; import {IPublicationActionModule} from 'contracts/interfaces/IPublicationActionModule.sol'; import {IModuleRegistry} from 'contracts/interfaces/IModuleRegistry.sol'; import {ILensHub} from 'contracts/interfaces/ILensHub.sol'; library PublicationLib { function MODULE_REGISTRY() internal view returns (IModuleRegistry) { return IModuleRegistry(ILensHub(address(this)).getModuleRegistry()); } /** * @notice Publishes a post to a given profile. * * @param postParams The PostParams struct. * * @return uint256 The created publication's pubId. */ function post(Types.PostParams calldata postParams, address transactionExecutor) external returns (uint256) { uint256 pubIdAssigned = ++StorageLib.getProfile(postParams.profileId).pubCount; Types.Publication storage _post = StorageLib.getPublication(postParams.profileId, pubIdAssigned); _post.contentURI = postParams.contentURI; _post.pubType = Types.PublicationType.Post; bytes memory referenceModuleReturnData = _initPubReferenceModule( InitReferenceModuleParams( postParams.profileId, transactionExecutor, pubIdAssigned, postParams.referenceModule, postParams.referenceModuleInitData ) ); bytes[] memory actionModulesReturnDatas = _initPubActionModules( InitActionModuleParams( postParams.profileId, transactionExecutor, pubIdAssigned, postParams.actionModules, postParams.actionModulesInitDatas ) ); emit Events.PostCreated( postParams, pubIdAssigned, actionModulesReturnDatas, referenceModuleReturnData, transactionExecutor, block.timestamp ); return pubIdAssigned; } /** * @notice Publishes a comment to a given profile via signature. * * @param commentParams the CommentParams struct. * * @return uint256 The created publication's pubId. */ function comment( Types.CommentParams calldata commentParams, address transactionExecutor ) external returns (uint256) { ( uint256 pubIdAssigned, bytes[] memory actionModulesInitReturnDatas, bytes memory referenceModuleInitReturnData, Types.PublicationType[] memory referrerPubTypes ) = _createReferencePublication( _asReferencePubParams(commentParams), transactionExecutor, Types.PublicationType.Comment ); bytes memory referenceModuleReturnData = _processCommentIfNeeded( commentParams, pubIdAssigned, transactionExecutor, referrerPubTypes ); emit Events.CommentCreated( commentParams, pubIdAssigned, referenceModuleReturnData, actionModulesInitReturnDatas, referenceModuleInitReturnData, transactionExecutor, block.timestamp ); return pubIdAssigned; } /** * @notice Publishes a mirror to a given profile. * * @param mirrorParams the MirrorParams struct. * * @return uint256 The created publication's pubId. */ function mirror(Types.MirrorParams calldata mirrorParams, address transactionExecutor) external returns (uint256) { ValidationLib.validatePointedPub(mirrorParams.pointedProfileId, mirrorParams.pointedPubId); ValidationLib.validateNotBlocked({profile: mirrorParams.profileId, byProfile: mirrorParams.pointedProfileId}); Types.PublicationType[] memory referrerPubTypes = ValidationLib.validateReferrersAndGetReferrersPubTypes( mirrorParams.referrerProfileIds, mirrorParams.referrerPubIds, mirrorParams.pointedProfileId, mirrorParams.pointedPubId ); uint256 pubIdAssigned = ++StorageLib.getProfile(mirrorParams.profileId).pubCount; Types.Publication storage _publication = StorageLib.getPublication(mirrorParams.profileId, pubIdAssigned); _publication.pointedProfileId = mirrorParams.pointedProfileId; _publication.pointedPubId = mirrorParams.pointedPubId; _publication.contentURI = mirrorParams.metadataURI; _publication.pubType = Types.PublicationType.Mirror; _fillRootOfPublicationInStorage(_publication, mirrorParams.pointedProfileId, mirrorParams.pointedPubId); bytes memory referenceModuleReturnData = _processMirrorIfNeeded( mirrorParams, pubIdAssigned, transactionExecutor, referrerPubTypes ); emit Events.MirrorCreated( mirrorParams, pubIdAssigned, referenceModuleReturnData, transactionExecutor, block.timestamp ); return pubIdAssigned; } /** * @notice Publishes a quote publication to a given profile via signature. * * @param quoteParams the QuoteParams struct. * * @return uint256 The created publication's pubId. */ function quote(Types.QuoteParams calldata quoteParams, address transactionExecutor) external returns (uint256) { ( uint256 pubIdAssigned, bytes[] memory actionModulesReturnDatas, bytes memory referenceModuleInitReturnData, Types.PublicationType[] memory referrerPubTypes ) = _createReferencePublication( _asReferencePubParams(quoteParams), transactionExecutor, Types.PublicationType.Quote ); bytes memory referenceModuleReturnData = _processQuoteIfNeeded( quoteParams, pubIdAssigned, transactionExecutor, referrerPubTypes ); emit Events.QuoteCreated( quoteParams, pubIdAssigned, referenceModuleReturnData, actionModulesReturnDatas, referenceModuleInitReturnData, transactionExecutor, block.timestamp ); return pubIdAssigned; } function getPublicationType(uint256 profileId, uint256 pubId) internal view returns (Types.PublicationType) { Types.Publication storage _publication = StorageLib.getPublication(profileId, pubId); Types.PublicationType pubType = _publication.pubType; if (uint8(pubType) == 0) { // Legacy V1: If the publication type is 0, we check using the legacy rules. if (_publication.pointedProfileId != 0) { // It is pointing to a publication, so it can be either a comment or a mirror, depending on if it has a // collect module or not. if (_publication.__DEPRECATED__collectModule == address(0)) { return Types.PublicationType.Mirror; } else { return Types.PublicationType.Comment; } } else if (_publication.__DEPRECATED__collectModule != address(0)) { return Types.PublicationType.Post; } } return pubType; } function getContentURI(uint256 profileId, uint256 pubId) external view returns (string memory) { Types.Publication storage _publication = StorageLib.getPublication(profileId, pubId); Types.PublicationType pubType = _publication.pubType; if (pubType == Types.PublicationType.Nonexistent) { pubType = getPublicationType(profileId, pubId); } if (pubType == Types.PublicationType.Mirror) { return StorageLib.getPublication(_publication.pointedProfileId, _publication.pointedPubId).contentURI; } else { return StorageLib.getPublication(profileId, pubId).contentURI; } } function _asReferencePubParams( Types.QuoteParams calldata quoteParams ) private pure returns (Types.ReferencePubParams calldata referencePubParams) { // We use assembly to cast the types keeping the params in calldata, as they match the fields. assembly { referencePubParams := quoteParams } } function _asReferencePubParams( Types.CommentParams calldata commentParams ) private pure returns (Types.ReferencePubParams calldata referencePubParams) { // We use assembly to cast the types keeping the params in calldata, as they match the fields. assembly { referencePubParams := commentParams } } function _createReferencePublication( Types.ReferencePubParams calldata referencePubParams, address transactionExecutor, Types.PublicationType referencePubType ) private returns (uint256, bytes[] memory, bytes memory, Types.PublicationType[] memory) { ValidationLib.validatePointedPub(referencePubParams.pointedProfileId, referencePubParams.pointedPubId); ValidationLib.validateNotBlocked({ profile: referencePubParams.profileId, byProfile: referencePubParams.pointedProfileId }); Types.PublicationType[] memory referrerPubTypes = ValidationLib.validateReferrersAndGetReferrersPubTypes( referencePubParams.referrerProfileIds, referencePubParams.referrerPubIds, referencePubParams.pointedProfileId, referencePubParams.pointedPubId ); (uint256 pubIdAssigned, uint256 rootProfileId) = _fillReferencePublicationStorage( referencePubParams, referencePubType ); if (rootProfileId != referencePubParams.pointedProfileId) { // We check the block state between the profile commenting/quoting and the root publication's author. ValidationLib.validateNotBlocked({profile: referencePubParams.profileId, byProfile: rootProfileId}); } bytes memory referenceModuleReturnData = _initPubReferenceModule( InitReferenceModuleParams( referencePubParams.profileId, transactionExecutor, pubIdAssigned, referencePubParams.referenceModule, referencePubParams.referenceModuleInitData ) ); bytes[] memory actionModulesReturnDatas = _initPubActionModules( InitActionModuleParams( referencePubParams.profileId, transactionExecutor, pubIdAssigned, referencePubParams.actionModules, referencePubParams.actionModulesInitDatas ) ); return (pubIdAssigned, actionModulesReturnDatas, referenceModuleReturnData, referrerPubTypes); } function _fillReferencePublicationStorage( Types.ReferencePubParams calldata referencePubParams, Types.PublicationType referencePubType ) private returns (uint256, uint256) { uint256 pubIdAssigned = ++StorageLib.getProfile(referencePubParams.profileId).pubCount; Types.Publication storage _referencePub; _referencePub = StorageLib.getPublication(referencePubParams.profileId, pubIdAssigned); _referencePub.pointedProfileId = referencePubParams.pointedProfileId; _referencePub.pointedPubId = referencePubParams.pointedPubId; _referencePub.contentURI = referencePubParams.contentURI; _referencePub.pubType = referencePubType; uint256 rootProfileId = _fillRootOfPublicationInStorage( _referencePub, referencePubParams.pointedProfileId, referencePubParams.pointedPubId ); return (pubIdAssigned, rootProfileId); } function _fillRootOfPublicationInStorage( Types.Publication storage _publication, uint256 pointedProfileId, uint256 pointedPubId ) internal returns (uint256) { Types.Publication storage _pubPointed = StorageLib.getPublication(pointedProfileId, pointedPubId); Types.PublicationType pubPointedType = _pubPointed.pubType; if (pubPointedType == Types.PublicationType.Post) { // The publication pointed is a Lens V2 post. _publication.rootPubId = pointedPubId; return _publication.rootProfileId = pointedProfileId; } else if (pubPointedType == Types.PublicationType.Comment || pubPointedType == Types.PublicationType.Quote) { // The publication pointed is either a Lens V2 comment or a Lens V2 quote. // Note that even when the publication pointed is a V2 one, it will lack `rootProfileId` and `rootPubId` if // there is a Lens V1 Legacy publication in the thread of interactions (including the root post itself). _publication.rootPubId = _pubPointed.rootPubId; return _publication.rootProfileId = _pubPointed.rootProfileId; } // Otherwise the root is not filled, as the pointed publication is a Lens V1 Legacy publication, which does not // support Lens V2 referral system. return 0; } function _processCommentIfNeeded( Types.CommentParams calldata commentParams, uint256 pubIdAssigned, address transactionExecutor, Types.PublicationType[] memory referrerPubTypes ) private returns (bytes memory) { address refModule = StorageLib .getPublication(commentParams.pointedProfileId, commentParams.pointedPubId) .referenceModule; if (refModule != address(0)) { try IReferenceModule(refModule).processComment( Types.ProcessCommentParams({ profileId: commentParams.profileId, pubId: pubIdAssigned, transactionExecutor: transactionExecutor, pointedProfileId: commentParams.pointedProfileId, pointedPubId: commentParams.pointedPubId, referrerProfileIds: commentParams.referrerProfileIds, referrerPubIds: commentParams.referrerPubIds, referrerPubTypes: referrerPubTypes, data: commentParams.referenceModuleData }) ) returns (bytes memory returnData) { return (returnData); } catch (bytes memory err) { assembly { /// Equivalent to reverting with the returned error selector if /// the length is not zero. let length := mload(err) if iszero(iszero(length)) { revert(add(err, 32), length) } } if (commentParams.referrerProfileIds.length > 0) { // Deprecated reference modules don't support referrers. revert Errors.InvalidReferrer(); } ILegacyReferenceModule(refModule).processComment( commentParams.profileId, commentParams.pointedProfileId, commentParams.pointedPubId, commentParams.referenceModuleData ); } } else { if (commentParams.referrerProfileIds.length > 0) { // We don't allow referrers if the reference module is not set. revert Errors.InvalidReferrer(); } } return ''; } function _processQuoteIfNeeded( Types.QuoteParams calldata quoteParams, uint256 pubIdAssigned, address transactionExecutor, Types.PublicationType[] memory referrerPubTypes ) private returns (bytes memory) { address refModule = StorageLib .getPublication(quoteParams.pointedProfileId, quoteParams.pointedPubId) .referenceModule; if (refModule != address(0)) { try IReferenceModule(refModule).processQuote( Types.ProcessQuoteParams({ profileId: quoteParams.profileId, pubId: pubIdAssigned, transactionExecutor: transactionExecutor, pointedProfileId: quoteParams.pointedProfileId, pointedPubId: quoteParams.pointedPubId, referrerProfileIds: quoteParams.referrerProfileIds, referrerPubIds: quoteParams.referrerPubIds, referrerPubTypes: referrerPubTypes, data: quoteParams.referenceModuleData }) ) returns (bytes memory returnData) { return (returnData); } catch (bytes memory err) { assembly { /// Equivalent to reverting with the returned error selector if /// the length is not zero. let length := mload(err) if iszero(iszero(length)) { revert(add(err, 32), length) } } if (quoteParams.referrerProfileIds.length > 0) { // Deprecated reference modules don't support referrers. revert Errors.InvalidReferrer(); } ILegacyReferenceModule(refModule).processComment( quoteParams.profileId, quoteParams.pointedProfileId, quoteParams.pointedPubId, quoteParams.referenceModuleData ); } } else { if (quoteParams.referrerProfileIds.length > 0) { // We don't allow referrers if the reference module is not set. revert Errors.InvalidReferrer(); } } return ''; } function _processMirrorIfNeeded( Types.MirrorParams calldata mirrorParams, uint256 pubIdAssigned, address transactionExecutor, Types.PublicationType[] memory referrerPubTypes ) private returns (bytes memory) { address refModule = StorageLib .getPublication(mirrorParams.pointedProfileId, mirrorParams.pointedPubId) .referenceModule; if (refModule != address(0)) { try IReferenceModule(refModule).processMirror( Types.ProcessMirrorParams({ profileId: mirrorParams.profileId, pubId: pubIdAssigned, transactionExecutor: transactionExecutor, pointedProfileId: mirrorParams.pointedProfileId, pointedPubId: mirrorParams.pointedPubId, referrerProfileIds: mirrorParams.referrerProfileIds, referrerPubIds: mirrorParams.referrerPubIds, referrerPubTypes: referrerPubTypes, data: mirrorParams.referenceModuleData }) ) returns (bytes memory returnData) { return (returnData); } catch (bytes memory err) { assembly { /// Equivalent to reverting with the returned error selector if /// the length is not zero. let length := mload(err) if iszero(iszero(length)) { revert(add(err, 32), length) } } if (mirrorParams.referrerProfileIds.length > 0) { // Deprecated reference modules don't support referrers. revert Errors.InvalidReferrer(); } ILegacyReferenceModule(refModule).processMirror( mirrorParams.profileId, mirrorParams.pointedProfileId, mirrorParams.pointedPubId, mirrorParams.referenceModuleData ); } } else { if (mirrorParams.referrerProfileIds.length > 0) { // We don't allow referrers if the reference module is not set. revert Errors.InvalidReferrer(); } } return ''; } // Needed to avoid 'stack too deep' issue. struct InitActionModuleParams { uint256 profileId; address transactionExecutor; uint256 pubId; address[] actionModules; bytes[] actionModulesInitDatas; } function _initPubActionModules(InitActionModuleParams memory params) private returns (bytes[] memory) { if (params.actionModules.length != params.actionModulesInitDatas.length) { revert Errors.ArrayMismatch(); } bytes[] memory actionModuleInitResults = new bytes[](params.actionModules.length); uint256 i; while (i < params.actionModules.length) { MODULE_REGISTRY().verifyModule( params.actionModules[i], uint256(IModuleRegistry.ModuleType.PUBLICATION_ACTION_MODULE) ); StorageLib.getPublication(params.profileId, params.pubId).actionModuleEnabled[ params.actionModules[i] ] = true; actionModuleInitResults[i] = IPublicationActionModule(params.actionModules[i]).initializePublicationAction( params.profileId, params.pubId, params.transactionExecutor, params.actionModulesInitDatas[i] ); unchecked { ++i; } } return actionModuleInitResults; } // Needed to avoid 'stack too deep' issue. struct InitReferenceModuleParams { uint256 profileId; address transactionExecutor; uint256 pubId; address referenceModule; bytes referenceModuleInitData; } function _initPubReferenceModule(InitReferenceModuleParams memory params) private returns (bytes memory) { if (params.referenceModule == address(0)) { return new bytes(0); } MODULE_REGISTRY().verifyModule(params.referenceModule, uint256(IModuleRegistry.ModuleType.REFERENCE_MODULE)); StorageLib.getPublication(params.profileId, params.pubId).referenceModule = params.referenceModule; return IReferenceModule(params.referenceModule).initializeReferenceModule( params.profileId, params.pubId, params.transactionExecutor, params.referenceModuleInitData ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Types} from 'contracts/libraries/constants/Types.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; library StorageLib { // uint256 constant NAME_SLOT = 0; // uint256 constant SYMBOL_SLOT = 1; uint256 constant TOKEN_DATA_MAPPING_SLOT = 2; // uint256 constant BALANCES_SLOT = 3; // uint256 constant TOKEN_APPROVAL_MAPPING_SLOT = 4; // uint256 constant OPERATOR_APPROVAL_MAPPING_SLOT = 5; // Slot 6 is deprecated in Lens V2. In V1 it was used for ERC-721 Enumerable's `ownedTokens`. // Slot 7 is deprecated in Lens V2. In V1 it was used for ERC-721 Enumerable's `ownedTokensIndex`. // uint256 constant TOTAL_SUPPLY_SLOT = 8; // Slot 9 is deprecated in Lens V2. In V1 it was used for ERC-721 Enumerable's `allTokensIndex`. uint256 constant SIG_NONCES_MAPPING_SLOT = 10; uint256 constant LAST_INITIALIZED_REVISION_SLOT = 11; // VersionedInitializable's `lastInitializedRevision` field. uint256 constant PROTOCOL_STATE_SLOT = 12; uint256 constant PROFILE_CREATOR_WHITELIST_MAPPING_SLOT = 13; // Slot 14 is deprecated in Lens V2. In V1 it was used for the follow module address whitelist. // Slot 15 is deprecated in Lens V2. In V1 it was used for the collect module address whitelist. // Slot 16 is deprecated in Lens V2. In V1 it was used for the reference module address whitelist. // Slot 17 is deprecated in Lens V2. In V1 it was used for the dispatcher address by profile ID. uint256 constant PROFILE_ID_BY_HANDLE_HASH_MAPPING_SLOT = 18; // Deprecated slot, but still needed for V2 migration. uint256 constant PROFILES_MAPPING_SLOT = 19; uint256 constant PUBLICATIONS_MAPPING_SLOT = 20; // Slot 21 is deprecated in Lens V2. In V1 it was used for the default profile ID by address. uint256 constant PROFILE_COUNTER_SLOT = 22; uint256 constant GOVERNANCE_SLOT = 23; uint256 constant EMERGENCY_ADMIN_SLOT = 24; ////////////////////////////////// /// Introduced in Lens V1.3: /// ////////////////////////////////// uint256 constant TOKEN_GUARDIAN_DISABLING_TIMESTAMP_MAPPING_SLOT = 25; ////////////////////////////////// /// Introduced in Lens V2: /// ////////////////////////////////// uint256 constant DELEGATED_EXECUTOR_CONFIG_MAPPING_SLOT = 26; uint256 constant BLOCKED_STATUS_MAPPING_SLOT = 27; uint256 constant PROFILE_ROYALTIES_BPS_SLOT = 28; uint256 constant MIGRATION_ADMINS_WHITELISTED_MAPPING_SLOT = 29; uint256 constant TREASURY_DATA_SLOT = 30; function getPublication( uint256 profileId, uint256 pubId ) internal pure returns (Types.Publication storage _publication) { assembly { mstore(0, profileId) mstore(32, PUBLICATIONS_MAPPING_SLOT) mstore(32, keccak256(0, 64)) mstore(0, pubId) _publication.slot := keccak256(0, 64) } } function getPublicationMemory( uint256 profileId, uint256 pubId ) internal pure returns (Types.PublicationMemory memory) { Types.PublicationMemory storage _publicationStorage; assembly { mstore(0, profileId) mstore(32, PUBLICATIONS_MAPPING_SLOT) mstore(32, keccak256(0, 64)) mstore(0, pubId) _publicationStorage.slot := keccak256(0, 64) } Types.PublicationMemory memory _publicationMemory; _publicationMemory = _publicationStorage; return _publicationMemory; } function getProfile(uint256 profileId) internal pure returns (Types.Profile storage _profiles) { assembly { mstore(0, profileId) mstore(32, PROFILES_MAPPING_SLOT) _profiles.slot := keccak256(0, 64) } } function getDelegatedExecutorsConfig( uint256 delegatorProfileId ) internal pure returns (Types.DelegatedExecutorsConfig storage _delegatedExecutorsConfig) { assembly { mstore(0, delegatorProfileId) mstore(32, DELEGATED_EXECUTOR_CONFIG_MAPPING_SLOT) _delegatedExecutorsConfig.slot := keccak256(0, 64) } } function tokenGuardianDisablingTimestamp() internal pure returns (mapping(address => uint256) storage _tokenGuardianDisablingTimestamp) { assembly { _tokenGuardianDisablingTimestamp.slot := TOKEN_GUARDIAN_DISABLING_TIMESTAMP_MAPPING_SLOT } } function getTokenData(uint256 tokenId) internal pure returns (Types.TokenData storage _tokenData) { assembly { mstore(0, tokenId) mstore(32, TOKEN_DATA_MAPPING_SLOT) _tokenData.slot := keccak256(0, 64) } } function blockedStatus( uint256 blockerProfileId ) internal pure returns (mapping(uint256 => bool) storage _blockedStatus) { assembly { mstore(0, blockerProfileId) mstore(32, BLOCKED_STATUS_MAPPING_SLOT) _blockedStatus.slot := keccak256(0, 64) } } function nonces() internal pure returns (mapping(address => uint256) storage _nonces) { assembly { _nonces.slot := SIG_NONCES_MAPPING_SLOT } } function profileIdByHandleHash() internal pure returns (mapping(bytes32 => uint256) storage _profileIdByHandleHash) { assembly { _profileIdByHandleHash.slot := PROFILE_ID_BY_HANDLE_HASH_MAPPING_SLOT } } function profileCreatorWhitelisted() internal pure returns (mapping(address => bool) storage _profileCreatorWhitelisted) { assembly { _profileCreatorWhitelisted.slot := PROFILE_CREATOR_WHITELIST_MAPPING_SLOT } } function migrationAdminWhitelisted() internal pure returns (mapping(address => bool) storage _migrationAdminWhitelisted) { assembly { _migrationAdminWhitelisted.slot := MIGRATION_ADMINS_WHITELISTED_MAPPING_SLOT } } function getGovernance() internal view returns (address _governance) { assembly { _governance := sload(GOVERNANCE_SLOT) } } function setGovernance(address newGovernance) internal { assembly { sstore(GOVERNANCE_SLOT, newGovernance) } } function getEmergencyAdmin() internal view returns (address _emergencyAdmin) { assembly { _emergencyAdmin := sload(EMERGENCY_ADMIN_SLOT) } } function setEmergencyAdmin(address newEmergencyAdmin) internal { assembly { sstore(EMERGENCY_ADMIN_SLOT, newEmergencyAdmin) } } function getState() internal view returns (Types.ProtocolState _state) { assembly { _state := sload(PROTOCOL_STATE_SLOT) } } function setState(Types.ProtocolState newState) internal { assembly { sstore(PROTOCOL_STATE_SLOT, newState) } } function getLastInitializedRevision() internal view returns (uint256 _lastInitializedRevision) { assembly { _lastInitializedRevision := sload(LAST_INITIALIZED_REVISION_SLOT) } } function setLastInitializedRevision(uint256 newLastInitializedRevision) internal { assembly { sstore(LAST_INITIALIZED_REVISION_SLOT, newLastInitializedRevision) } } function getTreasuryData() internal pure returns (Types.TreasuryData storage _treasuryData) { assembly { _treasuryData.slot := TREASURY_DATA_SLOT } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Types} from 'contracts/libraries/constants/Types.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {StorageLib} from 'contracts/libraries/StorageLib.sol'; import {ProfileLib} from 'contracts/libraries/ProfileLib.sol'; import {PublicationLib} from 'contracts/libraries/PublicationLib.sol'; /** * @title ValidationLib * @author Lens Protocol */ library ValidationLib { function validatePointedPub(uint256 profileId, uint256 pubId) internal view { // If it is pointing to itself it will fail because it will return a non-existent type. Types.PublicationType pointedPubType = PublicationLib.getPublicationType(profileId, pubId); if (pointedPubType == Types.PublicationType.Nonexistent || pointedPubType == Types.PublicationType.Mirror) { revert Errors.InvalidPointedPub(); } } function validateAddressIsProfileOwner(address expectedProfileOwner, uint256 profileId) internal view { if (expectedProfileOwner != ProfileLib.ownerOf(profileId)) { revert Errors.NotProfileOwner(); } } function validateAddressIsProfileOwnerOrDelegatedExecutor( address expectedOwnerOrDelegatedExecutor, uint256 profileId ) internal view { if (expectedOwnerOrDelegatedExecutor != ProfileLib.ownerOf(profileId)) { validateAddressIsDelegatedExecutor({ expectedDelegatedExecutor: expectedOwnerOrDelegatedExecutor, delegatorProfileId: profileId }); } } function validateAddressIsDelegatedExecutor( address expectedDelegatedExecutor, uint256 delegatorProfileId ) internal view { if (!ProfileLib.isExecutorApproved(delegatorProfileId, expectedDelegatedExecutor)) { revert Errors.ExecutorInvalid(); } } function validateProfileCreatorWhitelisted(address profileCreator) internal view { if (!StorageLib.profileCreatorWhitelisted()[profileCreator]) { revert Errors.NotWhitelisted(); } } function validateNotBlocked(uint256 profile, uint256 byProfile) internal view { // By default, block validation is bidirectional, meaning interactions are restricted in both ways. validateNotBlocked({profile: profile, byProfile: byProfile, unidirectionalCheck: false}); } function validateNotBlocked(uint256 profile, uint256 byProfile, bool unidirectionalCheck) internal view { if ( profile != byProfile && (StorageLib.blockedStatus(byProfile)[profile] || (!unidirectionalCheck && StorageLib.blockedStatus(profile)[byProfile])) ) { revert Errors.Blocked(); } } function validateProfileExists(uint256 profileId) internal view { if (!ProfileLib.exists(profileId)) { revert Errors.TokenDoesNotExist(); } } function validateCallerIsGovernance() internal view { if (msg.sender != StorageLib.getGovernance()) { revert Errors.NotGovernance(); } } function validateReferrersAndGetReferrersPubTypes( uint256[] memory referrerProfileIds, uint256[] memory referrerPubIds, uint256 targetedProfileId, uint256 targetedPubId ) internal view returns (Types.PublicationType[] memory) { if (referrerProfileIds.length != referrerPubIds.length) { revert Errors.ArrayMismatch(); } Types.PublicationType[] memory referrerPubTypes = new Types.PublicationType[](referrerProfileIds.length); // We decided not to check for duplicate referrals here due to gas cost. If transient storage opcodes (EIP-1153) // get included into the VM, this could be updated to implement an efficient duplicate check mechanism. // For now, if a module strongly needs to avoid duplicate referrals, it can check for them at its own expense. uint256 referrerProfileId; uint256 referrerPubId; uint256 i; while (i < referrerProfileIds.length) { referrerProfileId = referrerProfileIds[i]; referrerPubId = referrerPubIds[i]; referrerPubTypes[i] = _validateReferrerAndGetReferrerPubType( referrerProfileId, referrerPubId, targetedProfileId, targetedPubId ); unchecked { i++; } } return referrerPubTypes; } function validateLegacyCollectReferrer( uint256 referrerProfileId, uint256 referrerPubId, uint256 publicationCollectedProfileId, uint256 publicationCollectedId ) external view { if ( !ProfileLib.exists(referrerProfileId) || PublicationLib.getPublicationType(referrerProfileId, referrerPubId) != Types.PublicationType.Mirror ) { revert Errors.InvalidReferrer(); } Types.Publication storage _referrerMirror = StorageLib.getPublication(referrerProfileId, referrerPubId); // A mirror can only be a referrer of a legacy publication if it is pointing to it. if ( _referrerMirror.pointedProfileId != publicationCollectedProfileId || _referrerMirror.pointedPubId != publicationCollectedId ) { revert Errors.InvalidReferrer(); } } function _validateReferrerAndGetReferrerPubType( uint256 referrerProfileId, uint256 referrerPubId, uint256 targetedProfileId, uint256 targetedPubId ) private view returns (Types.PublicationType) { if (referrerPubId == 0) { // Unchecked/Unverified referral. Profile referrer, not attached to a publication. if (!ProfileLib.exists(referrerProfileId) || referrerProfileId == targetedProfileId) { revert Errors.InvalidReferrer(); } return Types.PublicationType.Nonexistent; } else { // Checked/Verified referral. Publication referrer. if ( // Cannot pass the targeted publication as a referrer. referrerProfileId == targetedProfileId && referrerPubId == targetedPubId ) { revert Errors.InvalidReferrer(); } Types.PublicationType referrerPubType = PublicationLib.getPublicationType(referrerProfileId, referrerPubId); if (referrerPubType == Types.PublicationType.Nonexistent) { revert Errors.InvalidReferrer(); } if (referrerPubType == Types.PublicationType.Post) { _validateReferrerAsPost(referrerProfileId, referrerPubId, targetedProfileId, targetedPubId); } else { _validateReferrerAsMirrorOrCommentOrQuote( referrerProfileId, referrerPubId, targetedProfileId, targetedPubId ); } return referrerPubType; } } function _validateReferrerAsPost( uint256 referrerProfileId, uint256 referrerPubId, uint256 targetedProfileId, uint256 targetedPubId ) private view { Types.Publication storage _targetedPub = StorageLib.getPublication(targetedProfileId, targetedPubId); // Publication targeted must have the referrer post as the root. This enables the use case of rewarding the // root publication for an action over any of its descendants. if (_targetedPub.rootProfileId != referrerProfileId || _targetedPub.rootPubId != referrerPubId) { revert Errors.InvalidReferrer(); } } /** * @dev Validates that the referrer publication and the interacted publication are linked. * * @param referrerProfileId The profile id of the referrer. * @param referrerPubId The publication id of the referrer. * @param targetedProfileId The ID of the profile who authored the publication being acted or referenced. * @param targetedPubId The pub ID being acted or referenced. */ function _validateReferrerAsMirrorOrCommentOrQuote( uint256 referrerProfileId, uint256 referrerPubId, uint256 targetedProfileId, uint256 targetedPubId ) private view { Types.Publication storage _referrerPub = StorageLib.getPublication(referrerProfileId, referrerPubId); // A mirror/quote/comment is allowed to be a referrer of a publication if it is pointing to it... if (_referrerPub.pointedProfileId != targetedProfileId || _referrerPub.pointedPubId != targetedPubId) { // ...or if the referrer pub's root is the target pub (i.e. target pub is a Lens V2 post)... if (_referrerPub.rootProfileId != targetedProfileId || _referrerPub.rootPubId != targetedPubId) { Types.Publication storage _targetedPub = StorageLib.getPublication(targetedProfileId, targetedPubId); // ...or if the referrer pub shares the root with the target pub. if ( // Here the target pub must be a "pure" Lens V2 comment/quote, which means there is no // Lens V1 Legacy comment or post on its tree of interactions, and its root pub is filled. // Otherwise, two Lens V2 "non-pure" publications could be passed as a referrer to each other, // even without having any interaction in common, as they would share the root as zero. _referrerPub.rootPubId == 0 || // The referrer publication and the target publication must share the same root. _referrerPub.rootProfileId != _targetedPub.rootProfileId || _referrerPub.rootPubId != _targetedPub.rootPubId ) { revert Errors.InvalidReferrer(); } } } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; library Errors { error CannotInitImplementation(); error Initialized(); error SignatureExpired(); error SignatureInvalid(); error InvalidOwner(); error NotOwnerOrApproved(); error NotHub(); error TokenDoesNotExist(); error NotGovernance(); error NotGovernanceOrEmergencyAdmin(); error EmergencyAdminCanOnlyPauseFurther(); error NotProfileOwner(); error PublicationDoesNotExist(); error CallerNotFollowNFT(); error CallerNotCollectNFT(); // Legacy error ArrayMismatch(); error NotWhitelisted(); error NotRegistered(); error InvalidParameter(); error ExecutorInvalid(); error Blocked(); error SelfBlock(); error NotFollowing(); error SelfFollow(); error InvalidReferrer(); error InvalidPointedPub(); error NonERC721ReceiverImplementer(); error AlreadyEnabled(); // Module Errors error InitParamsInvalid(); error ActionNotAllowed(); error CollectNotAllowed(); // Used in LegacyCollectLib (pending deprecation) // MultiState Errors error Paused(); error PublishingPaused(); // Profile Guardian Errors error GuardianEnabled(); error NotEOA(); error DisablingAlreadyTriggered(); // Migration Errors error NotMigrationAdmin(); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {Types} from 'contracts/libraries/constants/Types.sol'; library Events { /** * @dev Emitted when the NFT contract's name and symbol are set at initialization. * * @param name The NFT name set. * @param symbol The NFT symbol set. * @param timestamp The current block timestamp. */ event BaseInitialized(string name, string symbol, uint256 timestamp); /** * @dev Emitted when the hub state is set. * * @param caller The caller who set the state. * @param prevState The previous protocol state, an enum of either `Paused`, `PublishingPaused` or `Unpaused`. * @param newState The newly set state, an enum of either `Paused`, `PublishingPaused` or `Unpaused`. * @param timestamp The current block timestamp. */ event StateSet( address indexed caller, Types.ProtocolState indexed prevState, Types.ProtocolState indexed newState, uint256 timestamp ); /** * @dev Emitted when the governance address is changed. We emit the caller even though it should be the previous * governance address, as we cannot guarantee this will always be the case due to upgradeability. * * @param caller The caller who set the governance address. * @param prevGovernance The previous governance address. * @param newGovernance The new governance address set. * @param timestamp The current block timestamp. */ event GovernanceSet( address indexed caller, address indexed prevGovernance, address indexed newGovernance, uint256 timestamp ); /** * @dev Emitted when the emergency admin is changed. We emit the caller even though it should be the previous * governance address, as we cannot guarantee this will always be the case due to upgradeability. * * @param caller The caller who set the emergency admin address. * @param oldEmergencyAdmin The previous emergency admin address. * @param newEmergencyAdmin The new emergency admin address set. * @param timestamp The current block timestamp. */ event EmergencyAdminSet( address indexed caller, address indexed oldEmergencyAdmin, address indexed newEmergencyAdmin, uint256 timestamp ); /** * @dev Emitted when a profile creator is added to or removed from the whitelist. * * @param profileCreator The address of the profile creator. * @param whitelisted Whether or not the profile creator is being added to the whitelist. * @param timestamp The current block timestamp. */ event ProfileCreatorWhitelisted(address indexed profileCreator, bool indexed whitelisted, uint256 timestamp); /** * @dev Emitted when a profile is created. * * @param profileId The newly created profile's token ID. * @param creator The profile creator, who created the token with the given profile ID. * @param to The address receiving the profile with the given profile ID. * @param timestamp The current block timestamp. */ event ProfileCreated(uint256 indexed profileId, address indexed creator, address indexed to, uint256 timestamp); /** * @dev Emitted when a delegated executors configuration is changed. * * @param delegatorProfileId The ID of the profile for which the delegated executor was changed. * @param configNumber The number of the configuration where the executor approval state was set. * @param delegatedExecutors The array of delegated executors whose approval was set for. * @param approvals The array of booleans indicating the corresponding executor new approval status. * @param timestamp The current block timestamp. */ event DelegatedExecutorsConfigChanged( uint256 indexed delegatorProfileId, uint256 indexed configNumber, address[] delegatedExecutors, bool[] approvals, uint256 timestamp ); /** * @dev Emitted when a delegated executors configuration is applied. * * @param delegatorProfileId The ID of the profile applying the configuration. * @param configNumber The number of the configuration applied. * @param timestamp The current block timestamp. */ event DelegatedExecutorsConfigApplied( uint256 indexed delegatorProfileId, uint256 indexed configNumber, uint256 timestamp ); /** * @dev Emitted when a profile's follow module is set. * * @param profileId The profile's token ID. * @param followModule The profile's newly set follow module. This CAN be the zero address. * @param followModuleInitData The data passed to the follow module, if any. * @param followModuleReturnData The data returned from the follow module's initialization. This is ABI-encoded * and depends on the follow module chosen. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The current block timestamp. */ event FollowModuleSet( uint256 indexed profileId, address followModule, bytes followModuleInitData, bytes followModuleReturnData, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted when a post is successfully published. * * @param postParams The parameters passed to create the post publication. * @param pubId The publication ID assigned to the created post. * @param actionModulesInitReturnDatas The data returned from the action modules' initialization for this given * publication. This is ABI-encoded and depends on the action module chosen. * @param referenceModuleInitReturnData The data returned from the reference module at initialization. This is * ABI-encoded and depends on the reference module chosen. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The current block timestamp. */ event PostCreated( Types.PostParams postParams, uint256 indexed pubId, bytes[] actionModulesInitReturnDatas, bytes referenceModuleInitReturnData, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted when a comment is successfully published. * * @param commentParams The parameters passed to create the comment publication. * @param pubId The publication ID assigned to the created comment. * @param referenceModuleReturnData The data returned by the commented publication reference module's * processComment function, if the commented publication has a reference module set. * @param actionModulesInitReturnDatas The data returned from the action modules' initialization for this given * publication. This is ABI-encoded and depends on the action module chosen. * @param referenceModuleInitReturnData The data returned from the reference module at initialization. This is * ABI-encoded and depends on the reference module chosen. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The current block timestamp. */ event CommentCreated( Types.CommentParams commentParams, uint256 indexed pubId, bytes referenceModuleReturnData, bytes[] actionModulesInitReturnDatas, bytes referenceModuleInitReturnData, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted when a mirror is successfully published. * * @param mirrorParams The parameters passed to create the mirror publication. * @param pubId The publication ID assigned to the created mirror. * @param referenceModuleReturnData The data returned by the mirrored publication reference module's * processMirror function, if the mirrored publication has a reference module set. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The current block timestamp. */ event MirrorCreated( Types.MirrorParams mirrorParams, uint256 indexed pubId, bytes referenceModuleReturnData, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted when a quote is successfully published. * * @param quoteParams The parameters passed to create the quote publication. * @param pubId The publication ID assigned to the created quote. * @param referenceModuleReturnData The data returned by the quoted publication reference module's * processQuote function, if the quoted publication has a reference module set. * @param actionModulesInitReturnDatas The data returned from the action modules' initialization for this given * publication. This is ABI-encoded and depends on the action module chosen. * @param referenceModuleInitReturnData The data returned from the reference module at initialization. This is * ABI-encoded and depends on the reference module chosen. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The current block timestamp. */ event QuoteCreated( Types.QuoteParams quoteParams, uint256 indexed pubId, bytes referenceModuleReturnData, bytes[] actionModulesInitReturnDatas, bytes referenceModuleInitReturnData, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted when a followNFT clone is deployed using a lazy deployment pattern. * * @param profileId The token ID of the profile to which this followNFT is associated. * @param followNFT The address of the newly deployed followNFT clone. * @param timestamp The current block timestamp. */ event FollowNFTDeployed(uint256 indexed profileId, address indexed followNFT, uint256 timestamp); /** * @dev Emitted when a collectNFT clone is deployed using a lazy deployment pattern. * * @param profileId The publisher's profile token ID. * @param pubId The publication associated with the newly deployed collectNFT clone's ID. * @param collectNFT The address of the newly deployed collectNFT clone. * @param timestamp The current block timestamp. */ event LegacyCollectNFTDeployed( uint256 indexed profileId, uint256 indexed pubId, address indexed collectNFT, uint256 timestamp ); /** * @dev Emitted upon a successful action. * * @param publicationActionParams The parameters passed to act on a publication. * @param actionModuleReturnData The data returned from the action modules. This is ABI-encoded and the format * depends on the action module chosen. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The current block timestamp. */ event Acted( Types.PublicationActionParams publicationActionParams, bytes actionModuleReturnData, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted upon a successful follow operation. * * @param followerProfileId The ID of the profile that executed the follow. * @param idOfProfileFollowed The ID of the profile that was followed. * @param followTokenIdAssigned The ID of the follow token assigned to the follower. * @param followModuleData The data to pass to the follow module, if any. * @param processFollowModuleReturnData The data returned by the followed profile follow module's processFollow * function, if the followed profile has a reference module set. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The timestamp of the follow operation. */ event Followed( uint256 indexed followerProfileId, uint256 idOfProfileFollowed, uint256 followTokenIdAssigned, bytes followModuleData, bytes processFollowModuleReturnData, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted upon a successful unfollow operation. * * @param unfollowerProfileId The ID of the profile that executed the unfollow. * @param idOfProfileUnfollowed The ID of the profile that was unfollowed. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The timestamp of the unfollow operation. */ event Unfollowed( uint256 indexed unfollowerProfileId, uint256 idOfProfileUnfollowed, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted upon a successful block, through a block status setting operation. * * @param byProfileId The ID of the profile that executed the block status change. * @param idOfProfileBlocked The ID of the profile whose block status have been set to blocked. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The timestamp of the block operation. */ event Blocked( uint256 indexed byProfileId, uint256 idOfProfileBlocked, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted upon a successful unblock, through a block status setting operation. * * @param byProfileId The ID of the profile that executed the block status change. * @param idOfProfileUnblocked The ID of the profile whose block status have been set to unblocked. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The timestamp of the unblock operation. */ event Unblocked( uint256 indexed byProfileId, uint256 idOfProfileUnblocked, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted via callback when a collectNFT is transferred. * * @param profileId The token ID of the profile associated with the collectNFT being transferred. * @param pubId The publication ID associated with the collectNFT being transferred. * @param collectNFTId The collectNFT being transferred's token ID. * @param from The address the collectNFT is being transferred from. * @param to The address the collectNFT is being transferred to. * @param timestamp The current block timestamp. */ event CollectNFTTransferred( uint256 indexed profileId, uint256 indexed pubId, uint256 indexed collectNFTId, address from, address to, uint256 timestamp ); /** * @notice Emitted when the treasury address is set. * * @param prevTreasury The previous treasury address. * @param newTreasury The new treasury address set. * @param timestamp The current block timestamp. */ event TreasurySet(address indexed prevTreasury, address indexed newTreasury, uint256 timestamp); /** * @notice Emitted when the treasury fee is set. * * @param prevTreasuryFee The previous treasury fee in BPS. * @param newTreasuryFee The new treasury fee in BPS. * @param timestamp The current block timestamp. */ event TreasuryFeeSet(uint16 indexed prevTreasuryFee, uint16 indexed newTreasuryFee, uint256 timestamp); /** * @dev Emitted when the metadata associated with a profile is set in the `LensPeriphery`. * * @param profileId The profile ID the metadata is set for. * @param metadata The metadata set for the profile and user. * @param transactionExecutor The address of the account that executed this operation. * @param timestamp The current block timestamp. */ event ProfileMetadataSet( uint256 indexed profileId, string metadata, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted when an address' Profile Guardian state change is triggered. * * @param wallet The address whose Token Guardian state change is being triggered. * @param enabled True if the Token Guardian is being enabled, false if it is being disabled. * @param tokenGuardianDisablingTimestamp The UNIX timestamp when disabling the Token Guardian will take effect, * if disabling it. Zero if the protection is being enabled. * @param timestamp The UNIX timestamp of the change being triggered. */ event TokenGuardianStateChanged( address indexed wallet, bool indexed enabled, uint256 tokenGuardianDisablingTimestamp, uint256 timestamp ); /** * @dev Emitted when a signer's nonce is used and, as a consequence, the next available nonce is updated. * * @param signer The signer whose next available nonce was updated. * @param nonce The next available nonce that can be used to execute a meta-tx successfully. * @param timestamp The UNIX timestamp of the nonce being used. */ event NonceUpdated(address indexed signer, uint256 nonce, uint256 timestamp); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; library Typehash { bytes32 constant ACT = keccak256('Act(uint256 publicationActedProfileId,uint256 publicationActedId,uint256 actorProfileId,uint256[] referrerProfileIds,uint256[] referrerPubIds,address actionModuleAddress,bytes actionModuleData,uint256 nonce,uint256 deadline)'); bytes32 constant CHANGE_DELEGATED_EXECUTORS_CONFIG = keccak256('ChangeDelegatedExecutorsConfig(uint256 delegatorProfileId,address[] delegatedExecutors,bool[] approvals,uint64 configNumber,bool switchToGivenConfig,uint256 nonce,uint256 deadline)'); bytes32 constant COLLECT_LEGACY = keccak256('CollectLegacy(uint256 publicationCollectedProfileId,uint256 publicationCollectedId,uint256 collectorProfileId,uint256 referrerProfileId,uint256 referrerPubId,bytes collectModuleData,uint256 nonce,uint256 deadline)'); bytes32 constant COMMENT = keccak256('Comment(uint256 profileId,string contentURI,uint256 pointedProfileId,uint256 pointedPubId,uint256[] referrerProfileIds,uint256[] referrerPubIds,bytes referenceModuleData,address[] actionModules,bytes[] actionModulesInitDatas,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'); bytes32 constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 constant FOLLOW = keccak256('Follow(uint256 followerProfileId,uint256[] idsOfProfilesToFollow,uint256[] followTokenIds,bytes[] datas,uint256 nonce,uint256 deadline)'); bytes32 constant MIRROR = keccak256('Mirror(uint256 profileId,string metadataURI,uint256 pointedProfileId,uint256 pointedPubId,uint256[] referrerProfileIds,uint256[] referrerPubIds,bytes referenceModuleData,uint256 nonce,uint256 deadline)'); bytes32 constant POST = keccak256('Post(uint256 profileId,string contentURI,address[] actionModules,bytes[] actionModulesInitDatas,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'); bytes32 constant QUOTE = keccak256('Quote(uint256 profileId,string contentURI,uint256 pointedProfileId,uint256 pointedPubId,uint256[] referrerProfileIds,uint256[] referrerPubIds,bytes referenceModuleData,address[] actionModules,bytes[] actionModulesInitDatas,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'); bytes32 constant SET_BLOCK_STATUS = keccak256('SetBlockStatus(uint256 byProfileId,uint256[] idsOfProfilesToSetBlockStatus,bool[] blockStatus,uint256 nonce,uint256 deadline)'); bytes32 constant SET_FOLLOW_MODULE = keccak256('SetFollowModule(uint256 profileId,address followModule,bytes followModuleInitData,uint256 nonce,uint256 deadline)'); bytes32 constant SET_PROFILE_METADATA_URI = keccak256('SetProfileMetadataURI(uint256 profileId,string metadataURI,uint256 nonce,uint256 deadline)'); bytes32 constant UNFOLLOW = keccak256('Unfollow(uint256 unfollowerProfileId,uint256[] idsOfProfilesToUnfollow,uint256 nonce,uint256 deadline)'); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title Types * @author Lens Protocol * * @notice A standard library of data types used throughout the Lens Protocol. */ library Types { /** * @notice ERC721Timestamped storage. Contains the owner address and the mint timestamp for every NFT. * * Note: Instead of the owner address in the _tokenOwners private mapping, we now store it in the * _tokenData mapping, alongside the mint timestamp. * * @param owner The token owner. * @param mintTimestamp The mint timestamp. */ struct TokenData { address owner; uint96 mintTimestamp; } /** * @notice A struct containing token follow-related data. * * @param followerProfileId The ID of the profile using the token to follow. * @param originalFollowTimestamp The timestamp of the first follow performed with the token. * @param followTimestamp The timestamp of the current follow, if a profile is using the token to follow. * @param profileIdAllowedToRecover The ID of the profile allowed to recover the follow ID, if any. */ struct FollowData { uint160 followerProfileId; uint48 originalFollowTimestamp; uint48 followTimestamp; uint256 profileIdAllowedToRecover; } /** * @notice An enum containing the different states the protocol can be in, limiting certain actions. * * @param Unpaused The fully unpaused state. * @param PublishingPaused The state where only publication creation functions are paused. * @param Paused The fully paused state. */ enum ProtocolState { Unpaused, PublishingPaused, Paused } /** * @notice An enum specifically used in a helper function to easily retrieve the publication type for integrations. * * @param Nonexistent An indicator showing the queried publication does not exist. * @param Post A standard post, having an URI, action modules and no pointer to another publication. * @param Comment A comment, having an URI, action modules and a pointer to another publication. * @param Mirror A mirror, having a pointer to another publication, but no URI or action modules. * @param Quote A quote, having an URI, action modules, and a pointer to another publication. */ enum PublicationType { Nonexistent, Post, Comment, Mirror, Quote } /** * @notice A struct containing the necessary information to reconstruct an EIP-712 typed data signature. * * @param signer The address of the signer. Specially needed as a parameter to support EIP-1271. * @param v The signature's recovery parameter. * @param r The signature's r parameter. * @param s The signature's s parameter. * @param deadline The signature's deadline. */ struct EIP712Signature { address signer; uint8 v; bytes32 r; bytes32 s; uint256 deadline; } /** * @notice A struct containing profile data. * * @param pubCount The number of publications made to this profile. * @param followModule The address of the current follow module in use by this profile, can be address(0) in none. * @param followNFT The address of the followNFT associated with this profile. It can be address(0) if the * profile has not been followed yet, as the collection is lazy-deployed upon the first follow. * @param __DEPRECATED__handle DEPRECATED in V2: handle slot, was replaced with LensHandles. * @param __DEPRECATED__imageURI DEPRECATED in V2: The URI to be used for the profile image. * @param __DEPRECATED__followNFTURI DEPRECATED in V2: The URI used for the follow NFT image. * @param metadataURI MetadataURI is used to store the profile's metadata, for example: displayed name, description, * interests, etc. */ struct Profile { uint256 pubCount; // offset 0 address followModule; // offset 1 address followNFT; // offset 2 string __DEPRECATED__handle; // offset 3 string __DEPRECATED__imageURI; // offset 4 string __DEPRECATED__followNFTURI; // Deprecated in V2 as we have a common tokenURI for all Follows, offset 5 string metadataURI; // offset 6 } /** * @notice A struct containing publication data. * * @param pointedProfileId The profile token ID to point the publication to. * @param pointedPubId The publication ID to point the publication to. * These are used to implement the "reference" feature of the platform and is used in: * - Mirrors * - Comments * - Quotes * There are (0,0) if the publication is not pointing to any other publication (i.e. the publication is a Post). * @param contentURI The URI to set for the content of publication (can be ipfs, arweave, http, etc). * @param referenceModule Reference module associated with this profile, if any. * @param __DEPRECATED__collectModule Collect module associated with this publication, if any. Deprecated in V2. * @param __DEPRECATED__collectNFT Collect NFT associated with this publication, if any. Deprecated in V2. * @param pubType The type of publication, can be Nonexistent, Post, Comment, Mirror or Quote. * @param rootProfileId The profile ID of the root post (to determine if comments/quotes and mirrors come from it). * Posts, V1 publications and publications rooted in V1 publications don't have it set. * @param rootPubId The publication ID of the root post (to determine if comments/quotes and mirrors come from it). * Posts, V1 publications and publications rooted in V1 publications don't have it set. * @param actionModuleEnabled The action modules enabled in a given publication. */ struct Publication { uint256 pointedProfileId; uint256 pointedPubId; string contentURI; address referenceModule; address __DEPRECATED__collectModule; // Deprecated in V2 address __DEPRECATED__collectNFT; // Deprecated in V2 // Added in Lens V2, so these will be zero for old publications: PublicationType pubType; uint256 rootProfileId; uint256 rootPubId; mapping(address => bool) actionModuleEnabled; } struct PublicationMemory { uint256 pointedProfileId; uint256 pointedPubId; string contentURI; address referenceModule; address __DEPRECATED__collectModule; // Deprecated in V2 address __DEPRECATED__collectNFT; // Deprecated in V2 // Added in Lens V2, so these will be zero for old publications: PublicationType pubType; uint256 rootProfileId; uint256 rootPubId; // bytes32 __ACTION_MODULE_ENABLED_MAPPING; // Mappings are not supported in memory. } /** * @notice A struct containing the parameters required for the `createProfile()` function. * * @param to The address receiving the profile. * @param followModule The follow module to use, can be the zero address. * @param followModuleInitData The follow module initialization data, if any. */ struct CreateProfileParams { address to; address followModule; bytes followModuleInitData; } /** * @notice A struct containing the parameters required for the `post()` function. * * @param profileId The token ID of the profile to publish to. * @param contentURI The URI to set for this new publication. * @param actionModules The action modules to set for this new publication. * @param actionModulesInitDatas The data to pass to the action modules' initialization. * @param referenceModule The reference module to set for the given publication, must be whitelisted. * @param referenceModuleInitData The data to be passed to the reference module for initialization. */ struct PostParams { uint256 profileId; string contentURI; address[] actionModules; bytes[] actionModulesInitDatas; address referenceModule; bytes referenceModuleInitData; } /** * @notice A struct containing the parameters required for the `comment()` function. * * @param profileId The token ID of the profile to publish to. * @param contentURI The URI to set for this new publication. * @param pointedProfileId The profile token ID to point the comment to. * @param pointedPubId The publication ID to point the comment to. * @param referrerProfileId The profile token ID of the publication that referred to the publication being commented on/quoted. * @param referrerPubId The ID of the publication that referred to the publication being commented on/quoted. * @param referenceModuleData The data passed to the reference module. * @param actionModules The action modules to set for this new publication. * @param actionModulesInitDatas The data to pass to the action modules' initialization. * @param referenceModule The reference module to set for the given publication, must be whitelisted. * @param referenceModuleInitData The data to be passed to the reference module for initialization. */ struct CommentParams { uint256 profileId; string contentURI; uint256 pointedProfileId; uint256 pointedPubId; uint256[] referrerProfileIds; uint256[] referrerPubIds; bytes referenceModuleData; address[] actionModules; bytes[] actionModulesInitDatas; address referenceModule; bytes referenceModuleInitData; } /** * @notice A struct containing the parameters required for the `quote()` function. * * @param profileId The token ID of the profile to publish to. * @param contentURI The URI to set for this new publication. * @param pointedProfileId The profile token ID of the publication author that is quoted. * @param pointedPubId The publication ID that is quoted. * @param referrerProfileId The profile token ID of the publication that referred to the publication being commented on/quoted. * @param referrerPubId The ID of the publication that referred to the publication being commented on/quoted. * @param referenceModuleData The data passed to the reference module. * @param actionModules The action modules to set for this new publication. * @param actionModulesInitDatas The data to pass to the action modules' initialization. * @param referenceModule The reference module to set for the given publication, must be whitelisted. * @param referenceModuleInitData The data to be passed to the reference module for initialization. */ struct QuoteParams { uint256 profileId; string contentURI; uint256 pointedProfileId; uint256 pointedPubId; uint256[] referrerProfileIds; uint256[] referrerPubIds; bytes referenceModuleData; address[] actionModules; bytes[] actionModulesInitDatas; address referenceModule; bytes referenceModuleInitData; } /** * @notice A struct containing the parameters required for the `comment()` or `quote()` internal functions. * * @param profileId The token ID of the profile to publish to. * @param contentURI The URI to set for this new publication. * @param pointedProfileId The profile token ID of the publication author that is commented on/quoted. * @param pointedPubId The publication ID that is commented on/quoted. * @param referrerProfileId The profile token ID of the publication that referred to the publication being commented on/quoted. * @param referrerPubId The ID of the publication that referred to the publication being commented on/quoted. * @param referenceModuleData The data passed to the reference module. * @param actionModules The action modules to set for this new publication. * @param actionModulesInitDatas The data to pass to the action modules' initialization. * @param referenceModule The reference module to set for the given publication, must be whitelisted. * @param referenceModuleInitData The data to be passed to the reference module for initialization. */ struct ReferencePubParams { uint256 profileId; string contentURI; uint256 pointedProfileId; uint256 pointedPubId; uint256[] referrerProfileIds; uint256[] referrerPubIds; bytes referenceModuleData; address[] actionModules; bytes[] actionModulesInitDatas; address referenceModule; bytes referenceModuleInitData; } /** * @notice A struct containing the parameters required for the `mirror()` function. * * @param profileId The token ID of the profile to publish to. * @param metadataURI the URI containing metadata attributes to attach to this mirror publication. * @param pointedProfileId The profile token ID to point the mirror to. * @param pointedPubId The publication ID to point the mirror to. * @param referenceModuleData The data passed to the reference module. */ struct MirrorParams { uint256 profileId; string metadataURI; uint256 pointedProfileId; uint256 pointedPubId; uint256[] referrerProfileIds; uint256[] referrerPubIds; bytes referenceModuleData; } /** * Deprecated in V2: Will be removed after some time after upgrading to V2. * @notice A struct containing the parameters required for the legacy `collect()` function. * @dev The referrer can only be a mirror of the publication being collected. * * @param publicationCollectedProfileId The token ID of the profile that published the publication to collect. * @param publicationCollectedId The publication to collect's publication ID. * @param collectorProfileId The collector profile. * @param referrerProfileId The ID of a profile that authored a mirror that helped discovering the collected pub. * @param referrerPubId The ID of the mirror that helped discovering the collected pub. * @param collectModuleData The arbitrary data to pass to the collectModule if needed. */ struct LegacyCollectParams { uint256 publicationCollectedProfileId; uint256 publicationCollectedId; uint256 collectorProfileId; uint256 referrerProfileId; uint256 referrerPubId; bytes collectModuleData; } /** * @notice A struct containing the parameters required for the `action()` function. * * @param publicationActedProfileId The token ID of the profile that published the publication to action. * @param publicationActedId The publication to action's publication ID. * @param actorProfileId The actor profile. * @param referrerProfileId * @param referrerPubId * @param actionModuleAddress * @param actionModuleData The arbitrary data to pass to the actionModule if needed. */ struct PublicationActionParams { uint256 publicationActedProfileId; uint256 publicationActedId; uint256 actorProfileId; uint256[] referrerProfileIds; uint256[] referrerPubIds; address actionModuleAddress; bytes actionModuleData; } struct ProcessActionParams { uint256 publicationActedProfileId; uint256 publicationActedId; uint256 actorProfileId; address actorProfileOwner; address transactionExecutor; uint256[] referrerProfileIds; uint256[] referrerPubIds; Types.PublicationType[] referrerPubTypes; bytes actionModuleData; } struct ProcessCommentParams { uint256 profileId; uint256 pubId; address transactionExecutor; uint256 pointedProfileId; uint256 pointedPubId; uint256[] referrerProfileIds; uint256[] referrerPubIds; Types.PublicationType[] referrerPubTypes; bytes data; } struct ProcessQuoteParams { uint256 profileId; uint256 pubId; address transactionExecutor; uint256 pointedProfileId; uint256 pointedPubId; uint256[] referrerProfileIds; uint256[] referrerPubIds; Types.PublicationType[] referrerPubTypes; bytes data; } struct ProcessMirrorParams { uint256 profileId; uint256 pubId; address transactionExecutor; uint256 pointedProfileId; uint256 pointedPubId; uint256[] referrerProfileIds; uint256[] referrerPubIds; Types.PublicationType[] referrerPubTypes; bytes data; } /** * @notice A struct containing a profile's delegated executors configuration. * * @param isApproved Tells when an address is approved as delegated executor in the given configuration number. * @param configNumber Current configuration number in use. * @param prevConfigNumber Previous configuration number set, before switching to the current one. * @param maxConfigNumberSet Maximum configuration number ever used. */ struct DelegatedExecutorsConfig { mapping(uint256 => mapping(address => bool)) isApproved; // isApproved[configNumber][delegatedExecutor] uint64 configNumber; uint64 prevConfigNumber; uint64 maxConfigNumberSet; } struct TreasuryData { address treasury; uint16 treasuryFeeBPS; } struct MigrationParams { address lensHandlesAddress; address tokenHandleRegistryAddress; address legacyFeeFollowModule; address legacyProfileFollowModule; address newFeeFollowModule; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Base64} from '@openzeppelin/contracts/utils/Base64.sol'; import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import {ImageTokenURILib} from 'contracts/libraries/token-uris/ImageTokenURILib.sol'; library FollowTokenURILib { using Strings for uint96; using Strings for uint256; function getTokenURI( uint256 followTokenId, uint256 followedProfileId, uint256 originalFollowTimestamp ) external pure returns (string memory) { string memory followTokenIdAsString = followTokenId.toString(); string memory followedProfileIdAsString = followedProfileId.toString(); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( abi.encodePacked( '{"name":"Follower #', followTokenIdAsString, '","description":"Lens Protocol - Follower #', followTokenIdAsString, ' of Profile #', followedProfileIdAsString, '","image":"data:image/svg+xml;base64,', ImageTokenURILib.getSVGImageBase64Encoded(), '","attributes":[{"display_type": "number", "trait_type":"ID","value":"', followTokenIdAsString, '"},{"trait_type":"DIGITS","value":"', bytes(followTokenIdAsString).length.toString(), '"},{"trait_type":"MINTED AT","value":"', originalFollowTimestamp.toString(), '"}]}' ) ) ) ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Base64} from '@openzeppelin/contracts/utils/Base64.sol'; import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import {ImageTokenURILib} from 'contracts/libraries/token-uris/ImageTokenURILib.sol'; library HandleTokenURILib { using Strings for uint256; function getTokenURI( uint256 tokenId, string memory localName, string memory namespace ) external pure returns (string memory) { return string.concat( 'data:application/json;base64,', Base64.encode( bytes( string.concat( '{"name":"@', localName, '","description":"Lens Protocol - Handle @', localName, '","image":"data:image/svg+xml;base64,', ImageTokenURILib.getSVGImageBase64Encoded(), '","attributes":[{"display_type": "number", "trait_type":"ID","value":"', tokenId.toString(), '"},{"trait_type":"NAMESPACE","value":"', namespace, '"},{"trait_type":"LENGTH","value":"', bytes(localName).length.toString(), '"}]}' ) ) ) ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Base64} from '@openzeppelin/contracts/utils/Base64.sol'; library ImageTokenURILib { function getSVGImageBase64Encoded() internal pure returns (string memory) { return Base64.encode( '<svg xmlns="http://www.w3.org/2000/svg" width="263" height="263" fill="none"><g clip-path="url(#a)"><g clip-path="url(#b)"><path fill="url(#c)" d="M0 0h262.6v262.6H0V0Z"/></g><path fill="#93A97D" d="m98.7 242.8 16.3 5.4 16 1.3 16-1.3 16.3-5.4v30.7l-7.5 3.4-8 2.4-16.8-4.4-15.4 4.4-9.4-2.4-7.5-3.4v-30.7Z"/><path stroke="#000" stroke-dasharray="3.97 3.97" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M105 271v-22.3M157.5 271v-22.3"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="3" d="M131 273.8v-16.6"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="4" d="M100.1 243c0 10.2 0 20.4-.2 30.9m62-30.8.1 30.8"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="3" d="M100.3 242.2a57.8 57.8 0 0 0 30.2 7.8c10.7 0 21.7-2.4 31-7.8"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="2" d="M135.5 256.2s-2.7.5-4.5.5c-1.8 0-4.5-.5-4.5-.5"/><path fill="#A0D170" d="m81.9 202.2 13.9 6.7-4.5 17.8 2 12-3 5.8-8.4 1.4H70.4l-9.4-7.2 1.5-13.4 10.4-6.8 9-16.3ZM180.2 203.2l-14 6.7 4.5 17.8-2 12 3 4.8 8.5 2.4h11.4l9.4-7.2-1.5-13.5-10.4-6.7-9-16.3Z"/><path fill="#F4FFDC" d="M99.7 179.1s18.8-4.1 31.3-4.1a186 186 0 0 1 31.3 4.1l8.4 6.3 11.4 13-15.6 9 4.2 28.4-8.4 8.7-15.4 4.8-15.9 1.4-15.9-1.4-15.4-4.8-8.4-8.7 4.2-28.3-14.1-9.2 9.9-13 8.4-6.2Z"/><path stroke="#000" stroke-dasharray="5 5" stroke-linecap="round" stroke-miterlimit="10" stroke-opacity=".1" stroke-width="2" d="M151 184.3c0 9.2-9 16.7-20 16.7s-20-7.5-20-16.7 9-9.3 20-9.3 20 0 20 9.3Z"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="4" d="M81.9 202.4c-2.6 4.3-5.1 8.6-7.7 13.5a16.2 16.2 0 0 1-6 5.8 15 15 0 0 0-7 10.1 13.6 13.6 0 0 0 7.4 14.1c4.2 2 9.5 1.4 13.3-1.2"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="2" d="M83.8 240.6a11.2 11.2 0 0 1-5 4.8M178.2 240.6c1.5 2.4 2.4 3.4 5 4.8"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="4" d="M82 244.7a8 8 0 0 0 7.9 0 7.1 7.1 0 0 0 3.7-6.5"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="3" d="m96.1 211.2 3.1-10.7M165.8 211.2l-3-10.7M93.8 238.3a55.3 55.3 0 0 0 36.7 12.4"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="4" d="M100.1 243.8c-2-2-4.1-3.3-5.9-5a10 10 0 0 1-3.2-6c-.2-1.6.2-3.2.6-4.8l4.7-19.4a25.6 25.6 0 0 1-13.7-8.2c-1.1-1.3-1-3.1 0-4.5 2.8-4 5.9-8 9.6-11.6 4.5-4.2 10-7.4 16.3-8h45c6.2.6 11.8 3.8 16.2 8 3.8 3.5 6.8 7.7 9.7 11.6 1 1.4 1 3.2 0 4.5-3.4 4-8.3 7-13.7 8.2l4.7 19.4c.4 1.6.7 3.2.6 4.8a10 10 0 0 1-3.3 6c-1.7 1.7-3.8 3-5.9 5"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="3" d="M168.2 238.3a58.7 58.7 0 0 1-37.7 12.4"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="4" d="M180 202.4c2.5 4.3 5 8.6 7.6 13.5 1.3 2.5 3.7 4.3 6.1 5.8a15 15 0 0 1 7 10.1c.9 5.6-2.2 11.6-7.4 14.1-4.2 2-9.6 1.4-13.3-1.2M179.8 244.7a8 8 0 0 1-7.8 0c-2.4-1.4-3.9-3.3-3.8-6"/><path fill="#A0D170" d="M147 183.6c0 7.5-7.2 13.5-16 13.5s-16-6-16-13.5 7.2-7.6 16-7.6 16 0 16 7.6Z"/><path stroke="#000" stroke-linecap="round" stroke-miterlimit="10" stroke-width="2.5" d="M147 183.6c0 7.5-7.2 13.5-16 13.5s-16-6-16-13.5 7.2-7.6 16-7.6 16 0 16 7.6Z"/><path fill="#A0D170" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m135.5 216.7-.3.3v-.8c-.1-5.4-8.3-5.4-8.4 0v.8l-.3-.3-.3-.2c-4-3.7-9.7 2-6 6l.3.2a16.3 16.3 0 0 0 10.5 4.5s6 0 10.5-4.5l.3-.3c3.7-3.9-2-9.6-6-6l-.3.3Z"/><path fill="#A0D170" d="M169.3 99.8c-.8.8-2.2.3-2.2-.9v-3.3c-1.3-46.1-71-46.1-72.2 0v3.3c0 1.1-1.4 1.7-2.2 1l-2.4-2.4c-33.6-31.7-82.8 17.4-51 50.9l2.3 2.4A138.4 138.4 0 0 0 131 189s51 0 89.4-38.2l2.4-2.4c31.7-33.5-17.5-82.6-51-51l-2.5 2.4Z"/><circle cx="4" cy="4" r="4" fill="#fff" fill-opacity=".5" transform="matrix(-1 0 0 1 225.3 121)"/><path fill="#fff" fill-opacity=".5" d="M221.5 112.5a5 5 0 0 1-9 4 6.7 6.7 0 0 0-.3-.7l-1.2-2c-1-1.7-2.3-3.5-3.6-4.6-1.5-1.2-2.6-2-3.7-2.5l-1.7-.8a3 3 0 0 1-1.4-4l.1-.3c.8-1.5 0-3.3-1.5-3.5-1.9-.3-3.4-.3-5-.2h-.1a1.8 1.8 0 0 1-.3-3.5 23.6 23.6 0 0 1 16.6 4.8c1 .7 2.2 1.5 3.3 2.5a29.2 29.2 0 0 1 7.7 10.4v.3h.1"/><path stroke="#000" stroke-linecap="square" stroke-linejoin="round" stroke-width="4" d="M169.3 99.8v0c-.8.8-2.2.3-2.2-.9v0-3.3c-1.3-46.1-71-46.1-72.2 0v3.3c0 1.1-1.4 1.7-2.2 1v0l-2.4-2.4c-33.6-31.7-82.8 17.4-51 50.9l2.3 2.4A138.4 138.4 0 0 0 131 189s51 0 89.4-38.2l2.4-2.4c31.7-33.5-17.5-82.6-51-51l-2.5 2.4Z"/><path stroke="#000" stroke-linecap="round" stroke-width="3" d="M117 154s4.3 6 14 6 14-6 14-6"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M115 154c.8-.4 1.5-1 2-2M147 154c-.8-.4-1.5-1-2-2"/><path fill="#000" fill-rule="evenodd" d="M120.1 134c.7-.4 1-1.1.8-1.8-1.4-3.6-4.5-6.2-8-6.2-5 0-8.9 4.7-8.9 10.4s4 10.4 8.8 10.4c3.5 0 6.5-2.4 8-5.8.3-.7-.1-1.5-.8-1.8l-3.6-1.5c-1-.4-1-1.8 0-2.2l3.7-1.6ZM140.9 136.4c0-5.7 4-10.4 8.8-10.4 3.7 0 7 2.7 8.2 6.5.3.7-.1 1.4-.8 1.7l-3 1.3c-1 .4-1 1.8 0 2.2l2.9 1.2c.7.3 1 1 .8 1.8-1.4 3.6-4.5 6.1-8 6.1-5 0-8.9-4.7-8.9-10.4Z" clip-rule="evenodd"/><path fill="#000" fill-opacity=".1" d="M100.7 149.2a1.5 1.5 0 1 1-2.5-1.5 1.5 1.5 0 0 1 2.5 1.5ZM105.8 152.1a1.5 1.5 0 1 1-2.5-1.4 1.5 1.5 0 0 1 2.5 1.4ZM101.3 154a1.5 1.5 0 1 1-2.5-1.4 1.5 1.5 0 0 1 2.5 1.5ZM156.7 150.7a1.5 1.5 0 1 1-2.5 1.4 1.5 1.5 0 0 1 2.5-1.4ZM161.8 147.7a1.5 1.5 0 1 1-2.5 1.5 1.5 1.5 0 0 1 2.5-1.5ZM161.2 152.6a1.5 1.5 0 1 1-2.5 1.4 1.5 1.5 0 0 1 2.5-1.4Z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="4" d="M124 61.5s4.2-.5 7-.5c2.6 0 6.8.5 6.8.5"/><path fill="#A0B884" d="m179.6 108-.8 2.6-3.3-.8-5.3-4.2-7.8-5-9.2-4.9-9.1-1-10.6-1h-10l-11 2L103 99l-10.6 5.2-8 6.5-2-.8 3-5.7.8-4.2 2.5-3.2 7.1-4.1 8.4-3.6 13.1-3.3 14.6-.9h10.3l23.3 6.8 8.1 5.1 2 4 4.1 7.3Z"/><path fill="#F4FFDC" d="m88.5 85.8-2.2 13.8 3.5-3c3-2.4 6.2-4.4 9.6-5.9l1.3-.5 7.2-2.6 7.2-1.9 3.2-.5a91 91 0 0 1 13-.9h4c5.4.4 10.8 1.2 16 2.5l1 .2 8.9 3 3.2 1.5c3.3 1.6 6.2 3.7 8.9 6.2l2.2 1.9-1.9-13.8-2-7.8a30.6 30.6 0 0 0-5-10.9l-.6-.7c-2-2.8-4.4-5.2-7-7.4l-.3-.2c-2.4-2-5-3.6-7.8-5l-1.1-.5a37.2 37.2 0 0 0-16.3-3.7H128.8a36.9 36.9 0 0 0-15 3.2l-1.9.8a39.4 39.4 0 0 0-15.1 12L95.6 67a29.2 29.2 0 0 0-5.1 10.8l-2 8Z"/><path fill="#000" fill-opacity=".1" d="m92.2 94.9-6.1 5.9 2.3-14.2 2.6-8.8 4.4-9.4L106.5 57s-8.4 10.6-11 17.5C91.8 83.7 92.1 95 92.1 95ZM169.9 93.9l6 5.9-2.3-14.2-2.6-8.8-4.4-9.4-11-11.4s8.3 10.6 11 17.5C170.1 82.7 170 94 170 94Z"/><path fill="#F4FFDC" d="M131.3 49.4h-4a1.4 1.4 0 0 1-1-2.2l.2-.4c.3-.3.6-.5 1-.6l.5-.3c.7-.3 1.5-.4 2.2-.4H131.9c.7 0 1.3 0 2 .3l.7.3c.4.2.8.5 1.2 1l.2.2a1.3 1.3 0 0 1-1 2.1h-3.7Z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="4" d="M125.8 49.4v-1.9c0-.4 0-.8.2-1.2.2-.4.5-.8 1-1l.1-.2a9.4 9.4 0 0 1 8 0l.2.1c.4.3.7.7.9 1.1l.2 1.2v2M111 53.6l-1.1.6a39.2 39.2 0 0 0-20.4 26.2c-1.5 6.3-1.8 12.8-3 19l-.4 2.2-3.8 6.9c-.8 1.5 1 3 2.2 2l8.1-6.4 2.5-1.7c4.5-2.5 9.2-4.6 14-6.3l.8-.2.4-.1a85.7 85.7 0 0 1 41.9 0h.3l.8.3a89.6 89.6 0 0 1 16.4 8l8 6.4c1.3 1 3-.5 2.2-2l-3.8-7-.3-2.5c-1.2-6-1.4-12.2-2.8-18.2a39.3 39.3 0 0 0-20.5-26.7l-1-.5c-5.7-2.9-12-4.4-18.3-4.4h-3.8c-6.4 0-12.7 1.5-18.4 4.4Z"/><path fill="#A0D170" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="m135.7 66.1-.2.3v-.7c-.2-5.4-8.4-5.4-8.5 0v.7l-.3-.3-.3-.2c-4-3.7-9.7 2-6 6l.3.2a16.3 16.3 0 0 0 10.5 4.5s6 0 10.5-4.5l.3-.3c3.7-3.9-2-9.6-6-6 0 .2-.2.3-.3.3Z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M86.9 101.5s13.6-17.7 45-17.7c31.3 0 43.6 17.7 43.6 17.7"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-opacity=".1" stroke-width="4" d="M84.6 110.6s17.5-14 46.7-14c29.3 0 45 14 45 14"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 9c0-5 4-9 9-9h245c5 0 9 4 9 9v254H0V9Z"/></clipPath><clipPath id="b"><path fill="#fff" d="M0 0h262.6v262.6H0z"/></clipPath><linearGradient id="c" x1="131.3" x2="131.3" y1="0" y2="262.6" gradientUnits="userSpaceOnUse"><stop stop-color="#DDFFBC"/><stop offset="1" stop-color="#fff"/></linearGradient></defs></svg>' ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; contract ImmutableOwnable { address public immutable OWNER; address public immutable LENS_HUB; error OnlyOwner(); error OnlyOwnerOrHub(); modifier onlyOwner() { if (msg.sender != OWNER) { revert OnlyOwner(); } _; } modifier onlyOwnerOrHub() { if (msg.sender != OWNER && msg.sender != LENS_HUB) { revert OnlyOwnerOrHub(); } _; } constructor(address owner, address lensHub) { OWNER = owner; LENS_HUB = lensHub; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.15; import {Types} from 'contracts/libraries/constants/Types.sol'; import {MigrationLib} from 'contracts/libraries/MigrationLib.sol'; import {StorageLib} from 'contracts/libraries/StorageLib.sol'; import {ValidationLib} from 'contracts/libraries/ValidationLib.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; // Handles import {LensHandles} from 'contracts/namespaces/LensHandles.sol'; import {TokenHandleRegistry} from 'contracts/namespaces/TokenHandleRegistry.sol'; contract LensV2Migration { address internal immutable FEE_FOLLOW_MODULE; address internal immutable PROFILE_FOLLOW_MODULE; address internal immutable NEW_FEE_FOLLOW_MODULE; LensHandles internal immutable lensHandles; TokenHandleRegistry internal immutable tokenHandleRegistry; constructor(Types.MigrationParams memory migrationParams) { FEE_FOLLOW_MODULE = migrationParams.legacyFeeFollowModule; PROFILE_FOLLOW_MODULE = migrationParams.legacyProfileFollowModule; NEW_FEE_FOLLOW_MODULE = migrationParams.newFeeFollowModule; lensHandles = LensHandles(migrationParams.lensHandlesAddress); tokenHandleRegistry = TokenHandleRegistry(migrationParams.tokenHandleRegistryAddress); } function batchMigrateProfiles(uint256[] calldata profileIds) external { MigrationLib.batchMigrateProfiles(profileIds, lensHandles, tokenHandleRegistry); } // This is for public migration by themselves (so we only check the ownership of profile once) function batchMigrateFollows( uint256 followerProfileId, uint256[] calldata idsOfProfileFollowed, uint256[] calldata followTokenIds ) external { ValidationLib.validateAddressIsProfileOwnerOrDelegatedExecutor(msg.sender, followerProfileId); MigrationLib.batchMigrateFollows(followerProfileId, idsOfProfileFollowed, followTokenIds); } // This is for Whitelisted MigrationAdmin (so we only read the FollowNFT once) function batchMigrateFollowers( uint256[] calldata followerProfileIds, uint256 idOfProfileFollowed, uint256[] calldata followTokenIds ) external { if (!StorageLib.migrationAdminWhitelisted()[msg.sender]) { revert Errors.NotMigrationAdmin(); } MigrationLib.batchMigrateFollowers(followerProfileIds, idOfProfileFollowed, followTokenIds); } function batchMigrateFollowModules(uint256[] calldata profileIds) external { MigrationLib.batchMigrateFollowModules( profileIds, FEE_FOLLOW_MODULE, PROFILE_FOLLOW_MODULE, NEW_FEE_FOLLOW_MODULE ); } function getProfileIdByHandleHash(bytes32 handleHash) external view returns (uint256) { return StorageLib.profileIdByHandleHash()[handleHash]; } function setMigrationAdmins(address[] memory migrationAdmins, bool whitelisted) external { ValidationLib.validateCallerIsGovernance(); uint256 i; while (i < migrationAdmins.length) { StorageLib.migrationAdminWhitelisted()[migrationAdmins[i]] = whitelisted; unchecked { ++i; } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.18; import {ERC721} from '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import {ImmutableOwnable} from 'contracts/misc/ImmutableOwnable.sol'; import {ILensHandles} from 'contracts/interfaces/ILensHandles.sol'; import {HandlesEvents} from 'contracts/namespaces/constants/Events.sol'; import {HandlesErrors} from 'contracts/namespaces/constants/Errors.sol'; import {HandleTokenURILib} from 'contracts/libraries/token-uris/HandleTokenURILib.sol'; import {ILensHub} from 'contracts/interfaces/ILensHub.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import {ERC2981CollectionRoyalties} from 'contracts/base/ERC2981CollectionRoyalties.sol'; import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * A handle is defined as a local name inside a namespace context. A handle is represented as the local name with its * namespace applied as a prefix, using the slash symbol as separator. * * handle = namespace /@ localName * * Handle and local name can be used interchangeably once you are in a context of a namespace, as it became redundant. * * handle === ${localName} ; inside some namespace. * * @custom:upgradeable Transparent upgradeable proxy without initializer. */ contract LensHandles is ERC721, ERC2981CollectionRoyalties, ImmutableOwnable, ILensHandles { using Address for address; // We used 31 to fit the handle in a single slot, with `.lens` that restricted localName to use 26 characters. // Can be extended later if needed. uint256 internal constant MAX_LOCAL_NAME_LENGTH = 26; string public constant NAMESPACE = 'lens'; uint256 internal immutable NAMESPACE_LENGTH = bytes(NAMESPACE).length; bytes32 public constant NAMESPACE_HASH = keccak256(bytes(NAMESPACE)); uint256 public immutable TOKEN_GUARDIAN_COOLDOWN; uint256 internal constant GUARDIAN_ENABLED = type(uint256).max; mapping(address => uint256) internal _tokenGuardianDisablingTimestamp; uint256 internal _profileRoyaltiesBps; // Slot 7 uint256 private _totalSupply; mapping(uint256 tokenId => string localName) internal _localNames; modifier onlyOwnerOrWhitelistedProfileCreator() { if (msg.sender != OWNER && !ILensHub(LENS_HUB).isProfileCreatorWhitelisted(msg.sender)) { revert HandlesErrors.NotOwnerNorWhitelisted(); } _; } modifier onlyEOA() { if (msg.sender.isContract()) { revert HandlesErrors.NotEOA(); } _; } modifier onlyHub() { if (msg.sender != LENS_HUB) { revert HandlesErrors.NotHub(); } _; } constructor( address owner, address lensHub, uint256 tokenGuardianCooldown ) ERC721('', '') ImmutableOwnable(owner, lensHub) { TOKEN_GUARDIAN_COOLDOWN = tokenGuardianCooldown; } function name() public pure override returns (string memory) { return string.concat(symbol(), ' Handles'); } function symbol() public pure override returns (string memory) { return string.concat(NAMESPACE); } function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { _requireMinted(tokenId); return HandleTokenURILib.getTokenURI(tokenId, _localNames[tokenId], NAMESPACE); } /// @inheritdoc ILensHandles function mintHandle( address to, string calldata localName ) external onlyOwnerOrWhitelistedProfileCreator returns (uint256) { _validateLocalName(localName); return _mintHandle(to, localName); } function migrateHandle(address to, string calldata localName) external onlyHub returns (uint256) { _validateLocalNameMigration(localName); return _mintHandle(to, localName); } function burn(uint256 tokenId) external { if (msg.sender != ownerOf(tokenId)) { revert HandlesErrors.NotOwner(); } --_totalSupply; _burn(tokenId); delete _localNames[tokenId]; } /// ************************************ /// **** TOKEN GUARDIAN FUNCTIONS **** /// ************************************ function DANGER__disableTokenGuardian() external override onlyEOA { if (_tokenGuardianDisablingTimestamp[msg.sender] != GUARDIAN_ENABLED) { revert HandlesErrors.DisablingAlreadyTriggered(); } _tokenGuardianDisablingTimestamp[msg.sender] = block.timestamp + TOKEN_GUARDIAN_COOLDOWN; emit HandlesEvents.TokenGuardianStateChanged({ wallet: msg.sender, enabled: false, tokenGuardianDisablingTimestamp: block.timestamp + TOKEN_GUARDIAN_COOLDOWN, timestamp: block.timestamp }); } function enableTokenGuardian() external override onlyEOA { if (_tokenGuardianDisablingTimestamp[msg.sender] == GUARDIAN_ENABLED) { revert HandlesErrors.AlreadyEnabled(); } _tokenGuardianDisablingTimestamp[msg.sender] = GUARDIAN_ENABLED; emit HandlesEvents.TokenGuardianStateChanged({ wallet: msg.sender, enabled: true, tokenGuardianDisablingTimestamp: GUARDIAN_ENABLED, timestamp: block.timestamp }); } function approve(address to, uint256 tokenId) public override(IERC721, ERC721) { // We allow removing approvals even if the wallet has the token guardian enabled if (to != address(0) && _hasTokenGuardianEnabled(ownerOf(tokenId))) { revert HandlesErrors.GuardianEnabled(); } super.approve(to, tokenId); } function setApprovalForAll(address operator, bool approved) public override(IERC721, ERC721) { // We allow removing approvals even if the wallet has the token guardian enabled if (approved && _hasTokenGuardianEnabled(msg.sender)) { revert HandlesErrors.GuardianEnabled(); } super.setApprovalForAll(operator, approved); } function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function getNamespace() external pure returns (string memory) { return NAMESPACE; } function getNamespaceHash() external pure returns (bytes32) { return NAMESPACE_HASH; } function getLocalName(uint256 tokenId) public view returns (string memory) { string memory localName = _localNames[tokenId]; if (bytes(localName).length == 0) { revert HandlesErrors.DoesNotExist(); } return _localNames[tokenId]; } function getHandle(uint256 tokenId) public view returns (string memory) { string memory localName = getLocalName(tokenId); return string.concat(NAMESPACE, '/@', localName); } function getTokenId(string memory localName) public pure returns (uint256) { return uint256(keccak256(bytes(localName))); } function getTokenGuardianDisablingTimestamp(address wallet) external view override returns (uint256) { return _tokenGuardianDisablingTimestamp[wallet]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC721, ERC2981CollectionRoyalties, IERC165) returns (bool) { return (ERC721.supportsInterface(interfaceId) || ERC2981CollectionRoyalties.supportsInterface(interfaceId)); } ////////////////////////////////////// /// INTERNAL FUNCTIONS /// ////////////////////////////////////// function _mintHandle(address to, string calldata localName) internal returns (uint256) { uint256 tokenId = getTokenId(localName); ++_totalSupply; _mint(to, tokenId); _localNames[tokenId] = localName; emit HandlesEvents.HandleMinted(localName, NAMESPACE, tokenId, to, block.timestamp); return tokenId; } /// @dev This function is used to validate the local name when migrating from V1 to V2. /// As in V1 we also allowed the Hyphen '-' character, we need to allow it here as well and use a separate /// validation function for migration VS newly created handles. function _validateLocalNameMigration(string memory localName) internal pure { bytes memory localNameAsBytes = bytes(localName); uint256 localNameLength = localNameAsBytes.length; if (localNameLength == 0 || localNameLength > MAX_LOCAL_NAME_LENGTH) { revert HandlesErrors.HandleLengthInvalid(); } bytes1 firstByte = localNameAsBytes[0]; if (firstByte == '-' || firstByte == '_') { revert HandlesErrors.HandleFirstCharInvalid(); } uint256 i; while (i < localNameLength) { if (!_isAlphaNumeric(localNameAsBytes[i]) && localNameAsBytes[i] != '-' && localNameAsBytes[i] != '_') { revert HandlesErrors.HandleContainsInvalidCharacters(); } unchecked { ++i; } } } /// @dev In V2 we only accept the following characters: [a-z0-9_] to be used in newly created handles. /// We also disallow the first character to be an underscore '_'. function _validateLocalName(string memory localName) internal pure { bytes memory localNameAsBytes = bytes(localName); uint256 localNameLength = localNameAsBytes.length; if (localNameLength == 0 || localNameLength > MAX_LOCAL_NAME_LENGTH) { revert HandlesErrors.HandleLengthInvalid(); } if (localNameAsBytes[0] == '_') { revert HandlesErrors.HandleFirstCharInvalid(); } uint256 i; while (i < localNameLength) { if (!_isAlphaNumeric(localNameAsBytes[i]) && localNameAsBytes[i] != '_') { revert HandlesErrors.HandleContainsInvalidCharacters(); } unchecked { ++i; } } } /// @dev We only accept lowercase characters to avoid confusion. /// @param char The character to check. /// @return True if the character is alphanumeric, false otherwise. function _isAlphaNumeric(bytes1 char) internal pure returns (bool) { return (char >= '0' && char <= '9') || (char >= 'a' && char <= 'z'); } function _hasTokenGuardianEnabled(address wallet) internal view returns (bool) { return !wallet.isContract() && (_tokenGuardianDisablingTimestamp[wallet] == GUARDIAN_ENABLED || block.timestamp < _tokenGuardianDisablingTimestamp[wallet]); } function _getRoyaltiesInBasisPointsSlot() internal pure override returns (uint256 slot) { assembly { slot := _profileRoyaltiesBps.slot } } function _getReceiver(uint256 /* tokenId */) internal view override returns (address) { return ILensHub(LENS_HUB).getTreasury(); } function _beforeRoyaltiesSet(uint256 /* royaltiesInBasisPoints */) internal view override { if (msg.sender != OWNER) { revert OnlyOwner(); } } function _beforeTokenTransfer( address from, address to, uint256 /* firstTokenId */, uint256 batchSize ) internal override { if (from != address(0) && _hasTokenGuardianEnabled(from)) { // Cannot transfer handle if the guardian is enabled, except at minting time. revert HandlesErrors.GuardianEnabled(); } super._beforeTokenTransfer(from, to, 0, batchSize); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.18; import {IERC1271} from '@openzeppelin/contracts/interfaces/IERC1271.sol'; import {ITokenHandleRegistry} from 'contracts/interfaces/ITokenHandleRegistry.sol'; import {RegistryTypes} from 'contracts/namespaces/constants/Types.sol'; import {Types} from 'contracts/libraries/constants/Types.sol'; import {Errors} from 'contracts/libraries/constants/Errors.sol'; import {RegistryErrors} from 'contracts/namespaces/constants/Errors.sol'; import {RegistryEvents} from 'contracts/namespaces/constants/Events.sol'; import {ILensHub} from 'contracts/interfaces/ILensHub.sol'; import {ILensHandles} from 'contracts/interfaces/ILensHandles.sol'; import {Typehash} from 'contracts/namespaces/constants/Typehash.sol'; /** * @title TokenHandleRegistry * @author Lens Protocol * @notice This contract is used to link a token with a handle. * @custom:upgradeable Transparent upgradeable proxy without initializer. */ contract TokenHandleRegistry is ITokenHandleRegistry { string constant EIP712_DOMAIN_VERSION = '1'; bytes32 constant EIP712_DOMAIN_VERSION_HASH = keccak256(bytes(EIP712_DOMAIN_VERSION)); bytes4 internal constant EIP1271_MAGIC_VALUE = 0x1626ba7e; // First version of TokenHandleRegistry only works with Lens Profiles and .lens namespace. address immutable LENS_HUB; address immutable LENS_HANDLES; // Using _handleHash(Handle) and _tokenHash(Token) as keys given that structs cannot be used as them. mapping(bytes32 handle => RegistryTypes.Token token) handleToToken; mapping(bytes32 token => RegistryTypes.Handle handle) tokenToHandle; mapping(address signer => uint256 nonce) public nonces; constructor(address lensHub, address lensHandles) { LENS_HUB = lensHub; LENS_HANDLES = lensHandles; } // Lens V1 to Lens V2 migration function // WARNING: It is able to link the Token and Handle even if they're not in the same wallet. // But it is designed to be only called from LensHub migration function, which assures that they are. function migrationLink(uint256 handleId, uint256 profileId) external { if (msg.sender != LENS_HUB) { revert RegistryErrors.OnlyLensHub(); } _executeLinkage( RegistryTypes.Handle({collection: LENS_HANDLES, id: handleId}), RegistryTypes.Token({collection: LENS_HUB, id: profileId}), address(0) ); } /// @inheritdoc ITokenHandleRegistry function link(uint256 handleId, uint256 profileId) external { _link(handleId, profileId, msg.sender); } function linkWithSig(uint256 handleId, uint256 profileId, Types.EIP712Signature calldata signature) external { _validateLinkSignature(signature, handleId, profileId); _link(handleId, profileId, signature.signer); } function _link(uint256 handleId, uint256 profileId, address transactionExecutor) private { // Handle and profile must be owned by the same address. // Caller should be the owner of the profile or one of its approved delegated executors. address profileOwner = ILensHub(LENS_HUB).ownerOf(profileId); if (profileOwner != ILensHandles(LENS_HANDLES).ownerOf(handleId)) { revert RegistryErrors.HandleAndTokenNotInSameWallet(); } if ( transactionExecutor != profileOwner && !ILensHub(LENS_HUB).isDelegatedExecutorApproved(profileId, transactionExecutor) ) { revert RegistryErrors.DoesNotHavePermissions(); } _executeLinkage( RegistryTypes.Handle({collection: LENS_HANDLES, id: handleId}), RegistryTypes.Token({collection: LENS_HUB, id: profileId}), transactionExecutor ); } /// @notice This function is used to invalidate signatures by incrementing the nonce /// @param increment The amount to increment the nonce by function incrementNonce(uint8 increment) external { uint256 currentNonce = nonces[msg.sender]; nonces[msg.sender] = currentNonce + increment; emit RegistryEvents.NonceUpdated(msg.sender, currentNonce + increment, block.timestamp); } function _validateLinkSignature( Types.EIP712Signature calldata signature, uint256 handleId, uint256 profileId ) internal { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.LINK, handleId, profileId, _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } function _validateUnlinkSignature( Types.EIP712Signature calldata signature, uint256 handleId, uint256 profileId ) internal { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( Typehash.UNLINK, handleId, profileId, _getNonceIncrementAndEmitEvent(signature.signer), signature.deadline ) ) ), signature ); } /** * @dev Wrapper for ecrecover to reduce code size, used in meta-tx specific functions. */ function _validateRecoveredAddress(bytes32 digest, Types.EIP712Signature calldata signature) private view { if (block.timestamp > signature.deadline) revert Errors.SignatureExpired(); // If the expected address is a contract, check the signature there. if (signature.signer.code.length != 0) { bytes memory concatenatedSig = abi.encodePacked(signature.r, signature.s, signature.v); if (IERC1271(signature.signer).isValidSignature(digest, concatenatedSig) != EIP1271_MAGIC_VALUE) { revert Errors.SignatureInvalid(); } } else { address recoveredAddress = ecrecover(digest, signature.v, signature.r, signature.s); if (recoveredAddress == address(0) || recoveredAddress != signature.signer) { revert Errors.SignatureInvalid(); } } } /** * @dev Calculates EIP712 digest based on the current DOMAIN_SEPARATOR. * * @param hashedMessage The message hash from which the digest should be calculated. * * @return bytes32 A 32-byte output representing the EIP712 digest. */ function _calculateDigest(bytes32 hashedMessage) private view returns (bytes32) { return keccak256(abi.encodePacked('\x19\x01', calculateDomainSeparator(), hashedMessage)); } function calculateDomainSeparator() internal view returns (bytes32) { return keccak256( abi.encode( Typehash.EIP712_DOMAIN, keccak256('TokenHandleRegistry'), EIP712_DOMAIN_VERSION_HASH, block.chainid, address(this) ) ); } /// @inheritdoc ITokenHandleRegistry function unlink(uint256 handleId, uint256 profileId) external { _unlink(handleId, profileId, msg.sender); } function unlinkWithSig(uint256 handleId, uint256 profileId, Types.EIP712Signature calldata signature) external { _validateUnlinkSignature(signature, handleId, profileId); _unlink(handleId, profileId, signature.signer); } function _unlink(uint256 handleId, uint256 profileId, address transactionExecutor) private { if (handleId == 0 || profileId == 0) { revert RegistryErrors.DoesNotExist(); } if ( ILensHandles(LENS_HANDLES).exists(handleId) && ILensHandles(LENS_HANDLES).ownerOf(handleId) != transactionExecutor && ILensHub(LENS_HUB).exists(profileId) && (ILensHub(LENS_HUB).ownerOf(profileId) != transactionExecutor && !ILensHub(LENS_HUB).isDelegatedExecutorApproved(profileId, transactionExecutor)) ) { revert RegistryErrors.NotHandleNorTokenOwner(); } RegistryTypes.Handle memory handle = RegistryTypes.Handle({collection: LENS_HANDLES, id: handleId}); RegistryTypes.Token memory tokenPointedByHandle = handleToToken[_handleHash(handle)]; // We check if the tokens are (were) linked for the case if some of them doesn't exist if (tokenPointedByHandle.id != profileId) { revert RegistryErrors.NotLinked(); } _executeUnlinkage(handle, tokenPointedByHandle, transactionExecutor); } /// @inheritdoc ITokenHandleRegistry function resolve(uint256 handleId) external view returns (uint256) { if (!ILensHandles(LENS_HANDLES).exists(handleId)) { revert RegistryErrors.DoesNotExist(); } uint256 resolvedTokenId = _resolveHandleToToken(RegistryTypes.Handle({collection: LENS_HANDLES, id: handleId})) .id; if (resolvedTokenId == 0 || !ILensHub(LENS_HUB).exists(resolvedTokenId)) { return 0; } return resolvedTokenId; } /// @inheritdoc ITokenHandleRegistry function getDefaultHandle(uint256 profileId) external view returns (uint256) { if (!ILensHub(LENS_HUB).exists(profileId)) { revert RegistryErrors.DoesNotExist(); } uint256 defaultHandleId = _resolveTokenToHandle(RegistryTypes.Token({collection: LENS_HUB, id: profileId})).id; if (defaultHandleId == 0 || !ILensHandles(LENS_HANDLES).exists(defaultHandleId)) { return 0; } return defaultHandleId; } ////////////////////////////////////// /// INTERNAL FUNCTIONS /// ////////////////////////////////////// function _resolveHandleToToken( RegistryTypes.Handle memory handle ) internal view returns (RegistryTypes.Token storage) { return handleToToken[_handleHash(handle)]; } function _resolveTokenToHandle( RegistryTypes.Token memory token ) internal view returns (RegistryTypes.Handle storage) { return tokenToHandle[_tokenHash(token)]; } function _executeLinkage( RegistryTypes.Handle memory handle, RegistryTypes.Token memory token, address transactionExecutor ) internal { _deleteTokenToHandleLinkageIfAny(handle, transactionExecutor); handleToToken[_handleHash(handle)] = token; _deleteHandleToTokenLinkageIfAny(token, transactionExecutor); tokenToHandle[_tokenHash(token)] = handle; emit RegistryEvents.HandleLinked(handle, token, transactionExecutor, block.timestamp); } function _deleteTokenToHandleLinkageIfAny( RegistryTypes.Handle memory handle, address transactionExecutor ) internal { RegistryTypes.Token memory tokenPointedByHandle = handleToToken[_handleHash(handle)]; if (tokenPointedByHandle.collection != address(0) || tokenPointedByHandle.id != 0) { delete tokenToHandle[_tokenHash(tokenPointedByHandle)]; emit RegistryEvents.HandleUnlinked(handle, tokenPointedByHandle, transactionExecutor, block.timestamp); } } function _deleteHandleToTokenLinkageIfAny(RegistryTypes.Token memory token, address transactionExecutor) internal { RegistryTypes.Handle memory handlePointedByToken = tokenToHandle[_tokenHash(token)]; if (handlePointedByToken.collection != address(0) || handlePointedByToken.id != 0) { delete handleToToken[_handleHash(handlePointedByToken)]; emit RegistryEvents.HandleUnlinked(handlePointedByToken, token, transactionExecutor, block.timestamp); } } function _executeUnlinkage( RegistryTypes.Handle memory handle, RegistryTypes.Token memory token, address transactionExecutor ) internal { delete handleToToken[_handleHash(handle)]; // tokenToHandle is removed too, as the first version linkage is one-to-one. delete tokenToHandle[_tokenHash(token)]; emit RegistryEvents.HandleUnlinked(handle, token, transactionExecutor, block.timestamp); } function _handleHash(RegistryTypes.Handle memory handle) internal pure returns (bytes32) { return keccak256(abi.encode(handle.collection, handle.id)); } function _tokenHash(RegistryTypes.Token memory token) internal pure returns (bytes32) { return keccak256(abi.encode(token.collection, token.id)); } /** * @dev This fetches a signer's current nonce and increments it so it's ready for the next meta-tx. Also emits * the `NonceUpdated` event. * * @param signer The address to get and increment the nonce for. * * @return uint256 The current nonce for the given signer prior to being incremented. */ function _getNonceIncrementAndEmitEvent(address signer) private returns (uint256) { uint256 currentNonce; unchecked { currentNonce = nonces[signer]++; } emit RegistryEvents.NonceUpdated(signer, currentNonce + 1, block.timestamp); return currentNonce; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; library RegistryErrors { error NotHandleNorTokenOwner(); error OnlyLensHub(); error NotLinked(); error DoesNotExist(); error DoesNotHavePermissions(); error HandleAndTokenNotInSameWallet(); error SignatureInvalid(); } library HandlesErrors { error HandleLengthInvalid(); error HandleContainsInvalidCharacters(); error HandleFirstCharInvalid(); error NotOwnerNorWhitelisted(); error NotOwner(); error NotHub(); error DoesNotExist(); error NotEOA(); error DisablingAlreadyTriggered(); error GuardianEnabled(); error AlreadyEnabled(); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import {RegistryTypes} from 'contracts/namespaces/constants/Types.sol'; library HandlesEvents { event HandleMinted(string handle, string namespace, uint256 handleId, address to, uint256 timestamp); /** * @dev Emitted when an address' Token Guardian state change is triggered. * * @param wallet The address whose Token Guardian state change is being triggered. * @param enabled True if the Token Guardian is being enabled, false if it is being disabled. * @param tokenGuardianDisablingTimestamp The UNIX timestamp when disabling the Token Guardian will take effect, * if disabling it. Zero if the protection is being enabled. * @param timestamp The UNIX timestamp of the change being triggered. */ event TokenGuardianStateChanged( address indexed wallet, bool indexed enabled, uint256 tokenGuardianDisablingTimestamp, uint256 timestamp ); } library RegistryEvents { event HandleLinked( RegistryTypes.Handle handle, RegistryTypes.Token token, address transactionExecutor, uint256 timestamp ); /** * WARNING: If a linked handle or token is burnt, this event will not be emitted. * Indexers should also take into account token burns through ERC-721 Transfer events to track all unlink actions. * The `resolveHandle` and `resolveToken` functions will properly reflect the unlink in any case. */ event HandleUnlinked( RegistryTypes.Handle handle, RegistryTypes.Token token, address transactionExecutor, uint256 timestamp ); /** * @dev Emitted when a signer's nonce is used and, as a consequence, the next available nonce is updated. * * @param signer The signer whose next available nonce was updated. * @param nonce The next available nonce that can be used to execute a meta-tx successfully. * @param timestamp The UNIX timestamp of the nonce being used. */ event NonceUpdated(address indexed signer, uint256 nonce, uint256 timestamp); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; library Typehash { bytes32 constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 constant LINK = keccak256('Link(uint256 handleId,uint256 profileId,uint256 nonce,uint256 deadline)'); bytes32 constant UNLINK = keccak256('Unlink(uint256 handleId,uint256 profileId,uint256 nonce,uint256 deadline)'); }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title Namespaces Types * @author Lens Protocol */ library RegistryTypes { struct Token { uint256 id; // SLOT 0 address collection; // SLOT 1 - end // uint96 _gap; // SLOT 1 - start } struct Handle { uint256 id; // SLOT 0 address collection; // SLOT 1 - end // uint96 _gap; // SLOT 1 - start } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be paid in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: address zero is not a valid owner"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _ownerOf(tokenId); require(owner != address(0), "ERC721: invalid token ID"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { _requireMinted(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not token owner or approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { _requireMinted(tokenId); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved"); _safeTransfer(from, to, tokenId, data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist */ function _ownerOf(uint256 tokenId) internal view virtual returns (address) { return _owners[tokenId]; } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _ownerOf(tokenId) != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { address owner = ERC721.ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId, 1); // Check that tokenId was not minted by `_beforeTokenTransfer` hook require(!_exists(tokenId), "ERC721: token already minted"); unchecked { // Will not overflow unless all 2**256 token ids are minted to the same owner. // Given that tokens are minted one by one, it is impossible in practice that // this ever happens. Might change if we allow batch minting. // The ERC fails to describe this case. _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * This is an internal function that does not check if the sender is authorized to operate on the token. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, 1); // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook owner = ERC721.ownerOf(tokenId); // Clear approvals delete _tokenApprovals[tokenId]; unchecked { // Cannot overflow, as that would require more tokens to be burned/transferred // out than the owner initially received through minting and transferring in. _balances[owner] -= 1; } delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId, 1); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId, 1); // Check that tokenId was not transferred by `_beforeTokenTransfer` hook require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); // Clear approvals from the previous owner delete _tokenApprovals[tokenId]; unchecked { // `_balances[from]` cannot overflow for the same reason as described in `_burn`: // `from`'s balance is the number of token held, which is at least one before the current // transfer. // `_balances[to]` could overflow in the conditions described in `_mint`. That would require // all 2**256 token ids to be minted, which in practice is impossible. _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits an {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Reverts if the `tokenId` has not been minted yet. */ function _requireMinted(uint256 tokenId) internal view virtual { require(_exists(tokenId), "ERC721: invalid token ID"); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { /// @solidity memory-safe-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`. * - When `from` is zero, the tokens will be minted for `to`. * - When `to` is zero, ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * - `batchSize` is non-zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256, /* firstTokenId */ uint256 batchSize ) internal virtual { if (batchSize > 1) { if (from != address(0)) { _balances[from] -= batchSize; } if (to != address(0)) { _balances[to] += batchSize; } } } /** * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`. * - When `from` is zero, the tokens were minted for `to`. * - When `to` is zero, ``from``'s tokens were burned. * - `from` and `to` are never both zero. * - `batchSize` is non-zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 firstTokenId, uint256 batchSize ) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721 * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must * understand this adds an external call which potentially creates a reentrancy vulnerability. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol) pragma solidity ^0.8.0; /** * @dev Provides a set of functions to operate with Base64 strings. * * _Available since v4.5._ */ library Base64 { /** * @dev Base64 Encoding/Decoding Table */ string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * @dev Converts a `bytes` to its Bytes64 `string` representation. */ function encode(bytes memory data) internal pure returns (string memory) { /** * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol */ if (data.length == 0) return ""; // Loads the table into memory string memory table = _TABLE; // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter // and split into 4 numbers of 6 bits. // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up // - `data.length + 2` -> Round up // - `/ 3` -> Number of 3-bytes chunks // - `4 *` -> 4 characters for each chunk string memory result = new string(4 * ((data.length + 2) / 3)); /// @solidity memory-safe-assembly assembly { // Prepare the lookup table (skip the first "length" byte) let tablePtr := add(table, 1) // Prepare result pointer, jump over length let resultPtr := add(result, 32) // Run over the input, 3 bytes at a time for { let dataPtr := data let endPtr := add(data, mload(data)) } lt(dataPtr, endPtr) { } { // Advance 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // To write each character, shift the 3 bytes (18 bits) chunk // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) // and apply logical AND with 0x3F which is the number of // the previous character in the ASCII table prior to the Base64 Table // The result is then added to the table to get the character to write, // and finally write it in the result pointer but with a left shift // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) // Advance } // When data `bytes` is not exactly 3 bytes long // it is padded with `=` characters at the end switch mod(mload(data), 3) case 1 { mstore8(sub(resultPtr, 1), 0x3d) mstore8(sub(resultPtr, 2), 0x3d) } case 2 { mstore8(sub(resultPtr, 1), 0x3d) } } return result; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant _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) { 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), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @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) { 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] = _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); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @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 up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (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; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 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. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); 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 (rounding == Rounding.Up && 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 down. * * 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * 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 + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * 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 10, 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 + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } } }
{ "remappings": [ "@ensdomains/=node_modules/@ensdomains/", "@openzeppelin/=lib/openzeppelin-contracts/", "@seadrop/=lib/seadrop/src/", "ERC721A-Upgradeable/=lib/seadrop/lib/ERC721A-Upgradeable/contracts/", "ERC721A/=lib/seadrop/lib/ERC721A/contracts/", "create2-helpers/=lib/seadrop/lib/create2-helpers/", "create2-scripts/=lib/seadrop/lib/create2-helpers/script/", "ds-test/=lib/forge-std/lib/ds-test/src/", "erc4626-tests/=lib/seadrop/lib/operator-filter-registry/lib/openzeppelin-contracts/lib/erc4626-tests/", "eth-gas-reporter/=node_modules/eth-gas-reporter/", "forge-std/=lib/forge-std/src/", "hardhat/=node_modules/hardhat/", "murky/=lib/seadrop/lib/murky/src/", "openzeppelin-contracts-upgradeable/=lib/seadrop/lib/openzeppelin-contracts-upgradeable/contracts/", "openzeppelin-contracts/=lib/seadrop/lib/openzeppelin-contracts/contracts/", "operator-filter-registry/=lib/seadrop/lib/operator-filter-registry/src/", "seadrop/=lib/seadrop/", "solady/=lib/solady/src/", "solmate/=lib/seadrop/lib/solmate/src/", "utility-contracts/=lib/seadrop/lib/utility-contracts/src/" ], "optimizer": { "enabled": true, "runs": 10 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "paris", "viaIR": true, "libraries": { "contracts/libraries/ActionLib.sol": { "ActionLib": "0x7990dac84e3241fe314b980bba1466ac08715c4f" }, "contracts/libraries/FollowLib.sol": { "FollowLib": "0xe280cb21fb36b6b2d584428b809a6b822a5c2260" }, "contracts/libraries/GovernanceLib.sol": { "GovernanceLib": "0x5268512d20bf7653cf6d54b7c485ae3fbc658451" }, "contracts/libraries/LegacyCollectLib.sol": { "LegacyCollectLib": "0x5f0f24377c00f1517b4de496cf49eec8beb4ecb4" }, "contracts/libraries/MetaTxLib.sol": { "MetaTxLib": "0xf191c489e4ba0f448ea08a5fd27e9c928643f5c7" }, "contracts/libraries/MigrationLib.sol": { "MigrationLib": "0x0deced9ac3833b687d69d4eac6655f0f1279acee" }, "contracts/libraries/ProfileLib.sol": { "ProfileLib": "0x3fce2475a92c185f9634f5638f6b33306d77bb10" }, "contracts/libraries/PublicationLib.sol": { "PublicationLib": "0x90654f24a2c164a4da8f763ac8bc032d3d083a1b" }, "contracts/libraries/ValidationLib.sol": { "ValidationLib": "0x9cafd24d2851d9eb56e5a8fd394ab2ac0ef99849" }, "contracts/libraries/token-uris/FollowTokenURILib.sol": { "FollowTokenURILib": "0xc58f0e2a361e35c08619ef5f6122dc15180d783e" }, "contracts/libraries/token-uris/HandleTokenURILib.sol": { "HandleTokenURILib": "0x0e20f112689c7894ab8142108574e45d2650f529" }, "contracts/libraries/token-uris/ProfileTokenURILib.sol": { "ProfileTokenURILib": "0xf167835e74eecfe4bc571701d34fd38f4b61a830" } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"hub","type":"address"},{"internalType":"address","name":"lensHandles","type":"address"},{"internalType":"address","name":"tokenHandleRegistry","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"OnlyOwner","type":"error"},{"inputs":[],"name":"OnlyOwnerOrHub","type":"error"},{"inputs":[],"name":"ProfileAlreadyExists","type":"error"},{"inputs":[],"name":"LENS_HUB","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"OWNER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"string","name":"handle","type":"string"}],"name":"proxyCreateHandle","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"followModule","type":"address"},{"internalType":"bytes","name":"followModuleInitData","type":"bytes"}],"internalType":"struct Types.CreateProfileParams","name":"createProfileParams","type":"tuple"}],"name":"proxyCreateProfile","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"followModule","type":"address"},{"internalType":"bytes","name":"followModuleInitData","type":"bytes"}],"internalType":"struct Types.CreateProfileParams","name":"createProfileParams","type":"tuple"},{"internalType":"string","name":"handle","type":"string"}],"name":"proxyCreateProfileWithHandle","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
610100346100e357601f610a6b38819003918201601f19168301916001600160401b038311848410176100e8578084926080946040528339810103126100e357610048816100fe565b610054602083016100fe565b61006c6060610065604086016100fe565b94016100fe565b60809290925260a0526001600160a01b0391821660c0521660e05260405161095890816101138239608051818181609c015281816102230152818161042f01526107fe015260a05181818161014501528181610310015261048c015260c051818181610271015261055c015260e051816105ae0152f35b600080fd5b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b03821682036100e35756fe60806040908082526004918236101561001757600080fd5b600091823560e01c908163117803e3146107ea5750806350d425f91461033f5780637bb9c89b146102fc578063ac671158146101d95763fcaba76b1461005c57600080fd5b346101d5576020926003199084823601126101d1578035906001600160401b03908183116101ba576060833603948501126101ba576001600160a01b03927f0000000000000000000000000000000000000000000000000000000000000000841633036101c257855163560a4db160e01b815282810189905294846100e2838501610879565b166024870152846100f560248401610879565b166044870152604482013590602219018112156101be570160248101929101359081116101ba5780360382136101ba579183868161014181958b976060606485015260848401916108ba565b03927f0000000000000000000000000000000000000000000000000000000000000000165af19283156101af579261017b575b5051908152f35b9091508281813d83116101a8575b6101938183610856565b810103126101a357519038610174565b600080fd5b503d610189565b8251903d90823e3d90fd5b8580fd5b8780fd5b508451635fc483c560e01b8152fd5b8380fd5b5080fd5b5090346102f957816003193601126102f9576001600160a01b0391833583811681036101a3576024356001600160401b0381116101d15761021d903690870161088d565b949091817f00000000000000000000000000000000000000000000000000000000000000001633036102e957848495969761026d60209651998a968795869463784747af60e11b865285016108db565b03927f0000000000000000000000000000000000000000000000000000000000000000165af19182156102de57916102aa575b6020925051908152f35b90506020823d82116102d6575b816102c460209383610856565b810103126101a35760209151906102a0565b3d91506102b7565b9051903d90823e3d90fd5b8351635fc483c560e01b81528790fd5b80fd5b50346101d557816003193601126101d557517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346101d5576003199181833601126102f9576001600160401b03928435908482116107e65760609082360301126101d55782519160608301838110868211176107d3578452610390828701610879565b83526024946103a0868401610879565b9660209384860198895260448101359083821161069f570191366023840112156101d15781830135908082116107c157601f19918851946103e88885601f8501160187610856565b818652368b83830101116106d4578187928c8a93018389013786010152878701938452883590811161069f57610421903690840161088d565b9890916001600160a01b03907f0000000000000000000000000000000000000000000000000000000000000000821633036107b1578a8a516104856025828c642e6c656e7360d81b81830196808c8937830191820152036005810184520182610856565b51902095827f000000000000000000000000000000000000000000000000000000000000000016968b519063019e140760e41b825287820152898186818b5afa9081156107a7578991610776575b5061076657988899918b9c9d9284809d9a9b94818551169b308652519e8f9563560a4db160e01b8752878c8801525116888601525116604484015251606060648401528051908160848501528b5b82811061074c57505060a491601f828d85879586010152011681010301818a895af1988915610742578799610711575b5087610597999a9b827f000000000000000000000000000000000000000000000000000000000000000016948d519b8c92839263784747af60e11b8452308a85016108db565b03818a875af19889156107075787996106d8575b507f000000000000000000000000000000000000000000000000000000000000000016803b156106d457899160448a8980948f5196879586946386cf48e760e01b86528b8601528401525af180156106b7576106c1575b50803b1561069f5788516323b872dd60e01b808252918690829081838161062d8e8c308c8501610900565b03925af180156106b7579086916106a3575b5050823b1561069f57918793918580946106668c5197889687958694855230908501610900565b03925af1801561069557610681575b50508351928352820152f35b61068b829161082d565b6102f95780610675565b86513d84823e3d90fd5b8480fd5b6106ac9061082d565b61069f57843861063f565b8a513d88823e3d90fd5b6106cd9095919561082d565b9338610602565b8680fd5b9098508781813d8311610700575b6106f08183610856565b810103126106d4575197386105ab565b503d6106e6565b8b513d89823e3d90fd5b9a9850878b813d831161073b575b6107298183610856565b810103126106d4579951979987610551565b503d61071f565b8a513d89823e3d90fd5b81810186015194810160a401949094528c948e9401610521565b8a516337450d8560e11b81528690fd5b90508981813d83116107a0575b61078d8183610856565b8101031261079c5751386104d3565b8880fd5b503d610783565b8c513d8b823e3d90fd5b8951635fc483c560e01b81528590fd5b634e487b7160e01b8552604183528885fd5b634e487b7160e01b825260418752602482fd5b8280fd5b8390346101d557816003193601126101d5577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b6001600160401b03811161084057604052565b634e487b7160e01b600052604160045260246000fd5b601f909101601f19168101906001600160401b0382119082101761084057604052565b35906001600160a01b03821682036101a357565b9181601f840112156101a3578235916001600160401b0383116101a357602083818601950101116101a357565b908060209392818452848401376000828201840152601f01601f1916010190565b6001600160a01b0390911681526040602082018190526108fd939101916108ba565b90565b6001600160a01b0391821681529116602082015260408101919091526060019056fea264697066735822122007b23264f3b4f9a04e73f24a28ec77bac5d4315e7ee9742f844a68cc00c551ca64736f6c63430008150033000000000000000000000000e7af8325aa443f7678b651d4f0de23663e818691000000000000000000000000db46d1dc155634fbc732f92e853b10b288ad5a1d000000000000000000000000e7e7ead361f3aacd73a61a9bd6c10ca17f38e945000000000000000000000000d4f2f33680fccb36748fa9831851643781608844
Deployed Bytecode
0x60806040908082526004918236101561001757600080fd5b600091823560e01c908163117803e3146107ea5750806350d425f91461033f5780637bb9c89b146102fc578063ac671158146101d95763fcaba76b1461005c57600080fd5b346101d5576020926003199084823601126101d1578035906001600160401b03908183116101ba576060833603948501126101ba576001600160a01b03927f000000000000000000000000e7af8325aa443f7678b651d4f0de23663e818691841633036101c257855163560a4db160e01b815282810189905294846100e2838501610879565b166024870152846100f560248401610879565b166044870152604482013590602219018112156101be570160248101929101359081116101ba5780360382136101ba579183868161014181958b976060606485015260848401916108ba565b03927f000000000000000000000000db46d1dc155634fbc732f92e853b10b288ad5a1d165af19283156101af579261017b575b5051908152f35b9091508281813d83116101a8575b6101938183610856565b810103126101a357519038610174565b600080fd5b503d610189565b8251903d90823e3d90fd5b8580fd5b8780fd5b508451635fc483c560e01b8152fd5b8380fd5b5080fd5b5090346102f957816003193601126102f9576001600160a01b0391833583811681036101a3576024356001600160401b0381116101d15761021d903690870161088d565b949091817f000000000000000000000000e7af8325aa443f7678b651d4f0de23663e8186911633036102e957848495969761026d60209651998a968795869463784747af60e11b865285016108db565b03927f000000000000000000000000e7e7ead361f3aacd73a61a9bd6c10ca17f38e945165af19182156102de57916102aa575b6020925051908152f35b90506020823d82116102d6575b816102c460209383610856565b810103126101a35760209151906102a0565b3d91506102b7565b9051903d90823e3d90fd5b8351635fc483c560e01b81528790fd5b80fd5b50346101d557816003193601126101d557517f000000000000000000000000db46d1dc155634fbc732f92e853b10b288ad5a1d6001600160a01b03168152602090f35b50346101d5576003199181833601126102f9576001600160401b03928435908482116107e65760609082360301126101d55782519160608301838110868211176107d3578452610390828701610879565b83526024946103a0868401610879565b9660209384860198895260448101359083821161069f570191366023840112156101d15781830135908082116107c157601f19918851946103e88885601f8501160187610856565b818652368b83830101116106d4578187928c8a93018389013786010152878701938452883590811161069f57610421903690840161088d565b9890916001600160a01b03907f000000000000000000000000e7af8325aa443f7678b651d4f0de23663e818691821633036107b1578a8a516104856025828c642e6c656e7360d81b81830196808c8937830191820152036005810184520182610856565b51902095827f000000000000000000000000db46d1dc155634fbc732f92e853b10b288ad5a1d16968b519063019e140760e41b825287820152898186818b5afa9081156107a7578991610776575b5061076657988899918b9c9d9284809d9a9b94818551169b308652519e8f9563560a4db160e01b8752878c8801525116888601525116604484015251606060648401528051908160848501528b5b82811061074c57505060a491601f828d85879586010152011681010301818a895af1988915610742578799610711575b5087610597999a9b827f000000000000000000000000e7e7ead361f3aacd73a61a9bd6c10ca17f38e94516948d519b8c92839263784747af60e11b8452308a85016108db565b03818a875af19889156107075787996106d8575b507f000000000000000000000000d4f2f33680fccb36748fa983185164378160884416803b156106d457899160448a8980948f5196879586946386cf48e760e01b86528b8601528401525af180156106b7576106c1575b50803b1561069f5788516323b872dd60e01b808252918690829081838161062d8e8c308c8501610900565b03925af180156106b7579086916106a3575b5050823b1561069f57918793918580946106668c5197889687958694855230908501610900565b03925af1801561069557610681575b50508351928352820152f35b61068b829161082d565b6102f95780610675565b86513d84823e3d90fd5b8480fd5b6106ac9061082d565b61069f57843861063f565b8a513d88823e3d90fd5b6106cd9095919561082d565b9338610602565b8680fd5b9098508781813d8311610700575b6106f08183610856565b810103126106d4575197386105ab565b503d6106e6565b8b513d89823e3d90fd5b9a9850878b813d831161073b575b6107298183610856565b810103126106d4579951979987610551565b503d61071f565b8a513d89823e3d90fd5b81810186015194810160a401949094528c948e9401610521565b8a516337450d8560e11b81528690fd5b90508981813d83116107a0575b61078d8183610856565b8101031261079c5751386104d3565b8880fd5b503d610783565b8c513d8b823e3d90fd5b8951635fc483c560e01b81528590fd5b634e487b7160e01b8552604183528885fd5b634e487b7160e01b825260418752602482fd5b8280fd5b8390346101d557816003193601126101d5577f000000000000000000000000e7af8325aa443f7678b651d4f0de23663e8186916001600160a01b03168152602090f35b6001600160401b03811161084057604052565b634e487b7160e01b600052604160045260246000fd5b601f909101601f19168101906001600160401b0382119082101761084057604052565b35906001600160a01b03821682036101a357565b9181601f840112156101a3578235916001600160401b0383116101a357602083818601950101116101a357565b908060209392818452848401376000828201840152601f01601f1916010190565b6001600160a01b0390911681526040602082018190526108fd939101916108ba565b90565b6001600160a01b0391821681529116602082015260408101919091526060019056fea264697066735822122007b23264f3b4f9a04e73f24a28ec77bac5d4315e7ee9742f844a68cc00c551ca64736f6c63430008150033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000e7af8325aa443f7678b651d4f0de23663e818691000000000000000000000000db46d1dc155634fbc732f92e853b10b288ad5a1d000000000000000000000000e7e7ead361f3aacd73a61a9bd6c10ca17f38e945000000000000000000000000d4f2f33680fccb36748fa9831851643781608844
-----Decoded View---------------
Arg [0] : owner (address): 0xe7Af8325aA443F7678B651d4f0De23663E818691
Arg [1] : hub (address): 0xDb46d1Dc155634FbC732f92E853b10B288AD5a1d
Arg [2] : lensHandles (address): 0xe7E7EaD361f3AaCD73A61A9bD6C10cA17F38E945
Arg [3] : tokenHandleRegistry (address): 0xD4F2F33680FCCb36748FA9831851643781608844
-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 000000000000000000000000e7af8325aa443f7678b651d4f0de23663e818691
Arg [1] : 000000000000000000000000db46d1dc155634fbc732f92e853b10b288ad5a1d
Arg [2] : 000000000000000000000000e7e7ead361f3aacd73a61a9bd6c10ca17f38e945
Arg [3] : 000000000000000000000000d4f2f33680fccb36748fa9831851643781608844
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.