4. Soạn hợp đồng thông minh Klaystagram
Last updated
event PhotoUploaded (uint indexed tokenId, bytes photo, string title, string location, string description, uint256 timestamp);
ánh xạ (uint256 => PhotoData) private _photoList;
struct PhotoData {
uint256 tokenId; // id token không trùng lặp, bắt đầu từ 1 và tăng thêm 1
address[] ownerHistory; // Lịch sử tất cả những chủ sở hữu trước đây
bytes photo; // Nguồn ảnh
string title; // Tiêu đề ảnh
string location; // Nơi chụp ảnh
string description; // Mô tả ngắn về ảnh
uint256 timestamp; // Thời gian tải lên
}function uploadPhoto(bytes memory photo, string memory title, string memory location, string memory description) public {
uint256 tokenId = totalSupply() + 1;
_mint(msg.sender, tokenId);
address[] memory ownerHistory;
PhotoData memory newPhotoData = PhotoData({
tokenId : tokenId,
ownerHistory : ownerHistory,
photo : photo,
title: title,
location : location,
description : description,
timestamp : now
});
_photoList[tokenId] = newPhotoData;
_photoList[tokenId].ownerHistory.push(msg.sender);
emit PhotoUploaded(tokenId, photo, title, location, description, now);
}/**
* @ghi chú hàm safeTransferFrom kiểm tra xem người nhận có thể xử lý token ERC721 không,
* nhờ đó, ít có khả năng bị mất token. Sau khi kiểm tra xong, hàm transferFrom với định nghĩa bên dưới sẽ được gọi
*/
function transferOwnership(uint256 tokenId, address to) public returns(uint, address, address, address) {
safeTransferFrom(msg.sender, to, tokenId);
uint ownerHistoryLength = _photoList[tokenId].ownerHistory.length;
return (
_photoList[tokenId].tokenId,
//chủ sở hữu ban đầu _photoList[tokenId].ownerHistory[0],
//người sở hữu trước đây, độ dài không thể nhỏ hơn 2
_photoList[tokenId].ownerHistory[ownerHistoryLength-2],
//chủ sở hữu hiện tại
_photoList[tokenId].ownerHistory[ownerHistoryLength-1]);
}
/**
* @notice Khuyên dùng transferOwnership có sử dụng hàm safeTransferFrom
* @dev Viết đề lên hàm transferFrom để đảm bảo rằng mỗi lần chuyển quyền sở hữu
* địa chỉ của chủ sở hữu mới được đẩy vào mảng ownerHistory
*/
function transferFrom(address from, address to, uint256 tokenId) public {
super.transferFrom(from, to, tokenId);
_photoList[tokenId].ownerHistory.push(to);
}function getPhoto(uint tokenId) public view
returns(uint256, address[] memory, bytes memory, string memory, string memory, string memory, uint256) {
require(_photoList[tokenId].tokenId != 0, "Ảnh không tồn tại");
return (
_photoList[tokenId].tokenId,
_photoList[tokenId].ownerHistory,
_photoList[tokenId].photo,
_photoList[tokenId].title,
_photoList[tokenId].location,
_photoList[tokenId].description,
_photoList[tokenId].timestamp);
}