1

I am trying to implement a smart contract, that takes in a discreet distribution and returns a loaded random number. The higher the number higher the chance from 1-10000.

**anyone has any experience with this or ideas?

1 Answer 1

1

Here is an example from "Building Games with Ethereum Smart Contracts".

contract SatoshiDice {
    struct Bet {
    address user;
    uint block;
    uint cap;
    uint amount;
    }

    uint public constant FEE_NUMERATOR = 1;
    uint public constant FEE_DENOMINATOR = 100;
    uint public constant MAXIMUM_CAP = 100000;
    uint public constant MAXIMUM_BET_SIZE = 1e18;
    address owner;
    uint public counter = 0;
    mapping(uint => Bet) public bets;
    event BetPlaced(uint id, address user, uint cap, uint amount);
    event Roll(uint id, uint rolled);

function SatoshiDice () public {
    owner = msg.sender;
    }

function wager (uint cap) public payable {
    require(cap <= MAXIMUM_CAP);
    require(msg.value <= MAXIMUM_BET_SIZE);
    counter++;
    bets[counter] = Bet(msg.sender, block.number + 3, cap,
    msg.value);
    BetPlaced(counter, msg.sender, cap, msg.value);
}

function roll(uint id) public {
    Bet storage bet = bets[id];
    require(msg.sender == bet.user);
    require(block.number >= bet.block);
    require(block.number <= bet.block + 255);
    bytes32 random = keccak256(block.blockhash(bet.block), id);
    uint rolled = uint(random) % MAXIMUM_CAP;
    if (rolled < bet.cap) {
        uint payout = bet.amount * MAXIMUM_CAP / bet.cap;
        uint fee = payout * FEE_NUMERATOR / FEE_DENOMINATOR;
        payout -= fee;
        msg.sender.transfer(payout);
    }

    Roll(id, rolled);
    delete bets[id];
    }
    
    function fund () payable public {}
    function kill () public {
    require(msg.sender == owner);
    selfdestruct(owner);
 }
}

As the explanation for this kind of contracts is beyond a StackExchange answer, I'd recommend reading the book and/or more about random number generation on-chain.

2
  • Thank you for the answer, much appreciated.
    – chad3cpo
    Aug 11, 2021 at 10:46
  • 1
    @chad3cpo Cheers, could you validate the answer? I'm trying to build up rep.
    – Yakitori
    Aug 11, 2021 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.