Пост
Поделитесь своими знаниями.
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
Ответы
1«но есть ли способ создать случайное число?» - не совсем так, большинство блокчейнов и, в частности, EVM по своей сути детерминированы. Созданный вами код использует временную метку блока для случайности, но им можно манипулировать, приложив достаточно усилий.
Некоторые сервисы, такие как chainlink, публикуют случайные данные в блокчейне для использования в других контрактах. По сути, они действуют как третья сторона, предоставляя некоторые математические гарантии. Существуют альтернативы chainlink, но они используют очень похожие подходы и гораздо менее популярны. Итак, если вам нужен хороший источник случайности в блокчейне, то chainlink, вероятно, на данный момент является вашим лучшим выбором. Если вы только изучаете надежность, не беспокоясь о безопасности, вы можете попробовать подход с отметкой времени, как в сгенерированном фрагменте.
Знаете ответ?
Пожалуйста, войдите в систему и поделитесь им.
Solidity is an object-oriented, high-level language for implementing smart contracts. It is a curly-bracket language designed to target the Ethereum Virtual Machine (EVM).
Заработай свою долю из 1000 Sui
Зарабатывай очки репутации и получай награды за помощь в развитии сообщества Sui.
- My ERC721 contract successfully deploys, but I can't verify the contract's source code with hardhat21
- Solidity and ethers.js Compute Different Addresses from the Same Signature21
- can't understand what are the locations(uint256)22
- How to reverse keccak256 in solidity22
- Clarification on Gas Refunds and Comparison Between "require" and "revert" in Smart Contracts21