개발공부일지
BlockChain - token, transfer 본문
1. 세팅하기
npx create-react-app erc20
npm i web3
npm i @openzeppelin/contracts
remixd -s . --remix-ide "https://remix.ethereum.org/"
2. 토큰으로 랜덤 아이템 뽑기
- struct 객체 사용하기
- string[]에 임의의 이름과 각각의 url을 지정해주기
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "../node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyCoin is ERC20 {
constructor(string memory name, string memory symbol) ERC20(name, symbol) {
_mint(msg.sender, 100000 * (10 ** decimals()));
}
struct MyToken {
string url;
string name;
}
struct User {
address account;
}
uint256 private tokenPrice = 10 ether;
string[] tokenName = ["AAA", "BBB", "CCC"];
string[] tokenUrl = ["aaaa","bbbbb","ccccccc"]
mapping(address => MyToken[]) public myTokens;
User[] public users;
function getMyToken() public view returns (MyToken[] memory) {
return myTokens[msg.sender];
}
function getMyTokenUser() public view returns (User[] memory) {
return users;
}
function buyMyToken() public {
require(balanceOf(msg.sender) >= tokenPrice);
_update(msg.sender, address(0), tokenPrice);
uint random = uint(
keccak256(
abi.encodePacked(block.timestamp, block.coinbase, block.number)
)
);
random = uint(random % 3);
myTokens[msg.sender].push(
MyToken(myTokenUrl[random], myTokenName[random])
);
bool isUser = false;
for (uint256 i = 0; i < users.length; i++) {
if (users[i].account == msg.sender) {
isUser = true;
break;
}
}
if (!isUser) {
users.push(User(msg.sender));
}
}
}
- buyToken했을때 3개 중 랜덤의 아이템을 보내줌
3. 뽑은 토큰 다른계정에 보내기 (transfer)
function transferToken(uint index, address to, address from) public {
myTokens[to].push(myTokens[from][index]);
uint length = myTokens[from].length - 1;
myTokens[from][index] = myTokens[from][length];
myTokens[from].pop();
}
'BlockChain' 카테고리의 다른 글
BlockChain - factory contract, DAO, modifier, checks-effects-interactions pattern, mutex (0) | 2024.02.07 |
---|---|
BlockChain - ERC721, IPFS, pinata (0) | 2024.02.01 |
BlockChain - 메타마스크 네트워크 추가하기 (0) | 2024.01.31 |
BlockChain - react web3 hook, openzeppelin, ERC20, Token (0) | 2024.01.30 |
BlockChain - truffle, ERC20, remix (0) | 2024.01.29 |