Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

BlockChain - token, transfer 본문

BlockChain

BlockChain - token, transfer

보람- 2024. 1. 31. 17:47

 

 

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();
}