Solidity.

帖子

分享您的知识。

MetaInvestor.
Mar 29, 2025
专家问答

How to generate random Number between 1&2 without VRF?

So I was making a coinflip game which assigns head- 1 and tails -2 and when user places bet on polygon chain.... smart contract generates a random number between 1 and 2 and if the outcome is same...user gets double - (5 % as fee to the owner of contract) ! from a pool and if outcome is different then user loses all and the lost amount is deposited in the pool - (3% as fee to the owner) (to fund winners)... but any way to make genrate a random number? I have no funds at all so I can't afford chainlink VRF to generate. So is there any other secure way for this? plus I am pritty new to solidity so I made this code with help of chat gpt but I don't it works....can anyone help to make the code better? code-

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract CoinFlip {
    address public owner;
    uint256 public contractBalance;
    
    event BetPlaced(address indexed player, uint256 amount, bool choice);
    event BetResult(address indexed player, uint256 amount, bool won);
    
    constructor() {
        owner = msg.sender;
    }
    
    function placeBet(bool choice) external payable {
        require(msg.value > 0, "Bet amount must be greater than 0");
        
        bool outcome = (block.timestamp % 2 == 0); // Simple pseudo-random outcome
        if (outcome == choice) {
            uint256 winAmount = (msg.value * 2 * 95) / 100;
            require(address(this).balance >= winAmount, "Insufficient contract balance");
            payable(msg.sender).transfer(winAmount);
            emit BetResult(msg.sender, winAmount, true);
        } else {
            uint256 lostAmount = (msg.value * 97) / 100;
            contractBalance += lostAmount;
            emit BetResult(msg.sender, msg.value, false);
        }
        emit BetPlaced(msg.sender, msg.value, choice);
    }
    
    function depositFunds() external payable {
        require(msg.sender == owner, "Only owner can deposit funds");
        contractBalance += msg.value;
    }
    
    function withdrawFunds(uint256 amount) external {
        require(msg.sender == owner, "Only owner can withdraw funds");
        require(amount <= address(this).balance, "Insufficient contract balance");
        payable(owner).transfer(amount);
        contractBalance -= amount;
    }
}
  • Smart Contract
  • Solidity
0
1
分享
评论
.

答案

1
0x67fc...27ac.
Mar 31 2025, 13:26

“但是有什么办法可以让生成一个随机数吗?”-不是真的,大多数区块链,尤其是EVM,在设计上都是确定性的. 你生成的代码使用区块的时间戳来实现随机性,但只要付出足够的努力就可以对其进行操作.

诸如chainlink之类的一些服务在区块链上随机发布内容供其他合约使用,基本上就像第三方一样,有一些数学保证. 有Chainlink的替代方案,但它们使用的方法非常相似,而且不那么受欢迎. 因此,如果你想要一个良好的链上随机性来源,那么chainlink可能是你目前最好的选择. 如果你只是在学习 solidity 而不担心安全性,你可以尝试使用时间戳的方法,就像生成的代码片段中一样.

0
评论
.

你知道答案吗?

请登录并分享。

我们使用 cookie 确保您在我们的网站上获得最佳体验。
更多信息