Last active
October 24, 2021 13:03
-
-
Save carnoxen/0bf0b2d6c264a4064066f0d0792b969b to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: GPL-3.0 | |
pragma solidity ^0.8.4; | |
contract Gashapon { | |
// struct of rank. count is a maximum size of winners array. winners array stores users from user lists | |
struct Rank { | |
string name; | |
uint count; | |
string[] winners; | |
} | |
// user and rank lists | |
struct List { | |
Rank[] ranks; | |
bool created; | |
} | |
address private owner; | |
mapping(string => List) listmap; | |
constructor() { | |
owner = msg.sender; | |
} | |
function getList(string memory _name) external view returns (List memory){ | |
List storage list = listmap[_name]; | |
require(list.created); | |
return list; | |
} | |
function randMod(uint _count, uint _nonce) private view returns (uint) { | |
return uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, _nonce))) % _count; | |
} | |
function allocateUsers(string[] memory _users, Rank[] memory _ranks, string memory _name) external { | |
uint userCount = _users.length; | |
uint nonce = 0; | |
List storage list = listmap[_name]; | |
require(!list.created); | |
for (uint i = 0; i < _ranks.length && userCount > 0; ++i) { | |
Rank memory thisrank = _ranks[i]; | |
uint rankCount = thisrank.count < userCount ? thisrank.count : userCount; | |
thisrank.winners = new string[](rankCount); | |
for (uint j = 0; j < rankCount; ++j) { | |
uint rand = randMod(userCount, nonce++); | |
thisrank.winners[j] = _users[rand]; | |
_users[rand] = _users[userCount - 1]; | |
--userCount; | |
} | |
list.ranks.push(thisrank); | |
} | |
list.created = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment