Klaytn IDE 를 사용해서 예제 코드를 작성해보았다.
pragma solidity >=0.4.24 <=0.5.6;
contract Practice {
uint256 private totoalSupply = 10;
string public name = "ALVIN"
// python 의 dictionary와 비슷 uint256-> key, string-> value
mapping (uint256 => string) public tokenURIs;
address public owner; // contract deployer
constructor() public {
// msg.sender => transaction 실행한 주체
owner = msg.sender;
}
// view => read-only(값변경 x) -> 수수료 x 따로 transaction 생성 안하기 때문, returns (uint256) => 반환값을 uint256으로...
function getTotalSupply() public view returns (uint256) {
return totalSupply + 100000;
}
// 값을 변경하게 되면 transaction 생성을 하여 수수료 발생
function setTotalSupply(uint256 newSupply) public {
// contract를 만든 사람만 값을 바꾸게 하고싶을때... 실패하면 바로 끝내버림
require(owner == msg.sender, 'not owner');
totalSupply = newSupply;
}
function setTokenUri(uint256 id, string memory uri) public {
tokenURIs[id] = uri;
}
pragma solidity >=0.4.24 <=0.5.6;
contract NFTSimple {
string public name = "KlayLion";
string public symbol = "KL";
mapping (uint256 => address) public tokenOwner;
mapping (uint256 => string) public tokenURIs;
// token list
mapping (address => uint256[]) private _ownedTokens;
// mint (tokenId, uri, owner)
// transferForm(form, to, tokenId) -> owner가 바뀌는것(from -> to)
function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public returns (bool) {
// to에게 tokenId(일련번호)를 발행하겠다.
// 적힐 내용은 tokenURI
tokenOwner[tokenId] = to;
tokenURIs[tokenId] = tokenURI;
// add token to the list
_ownedTokens[to].push(tokenId);
}
function safeTransferForm(address from, address to, uint256 tokenId) public {
require(from == msg.sender, "from != msg.sender");
require(from == tokenOwner[tokenId], "you are not the owner of the token");
_removeTokenFromList(from, tokenId);
_ownedTokens[to].push(tokenId);
tokenOwner[tokenId] = to;
}
function _removeTokenFromList(address from, uint256 tokenId) private {
uint256 lastTokenIndex = _ownedTokens[from].length - 1;
for(uint256 i=0;i<_ownedTokens[from].length;i++) {
if (tokenId == _ownedTokens[from][i]) {
// Swap last token with deleting token
_ownedTokens[from][i] = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][lastTokenIndex] = tokenId;
break;
}
}
_ownedTokens[from].length--;
}
function ownedTokens(address owner) public view returns (uint256[] memory) {
return _ownedTokens[owner];
}
function setTokenUri(uint256 id, string memory uri) public {
tokenURIs[id] = uri;
}
}
contract NFTMarket {
function buyNFT(uint256 tokenId, address NFTAddress, address to) public returns (bool) {
NFTSimple(NFTAddress).safeTransferForm(address(this), to, tokenId);
return true;
}
}
contract 자체도 주소가 있기 때문에, 위 예시처럼 NFTMarket에도 토큰을 보낼 수 있고 NFTMarket도 토큰을 보낼 수 있다.