Допис
Діліться своїми знаннями.
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, розміщують випадкові речі на блокчейні для використання інших контрактів, в основному діючи як третя сторона з деякими математичними гарантіями. Існують альтернативи ланцюгових посилань, але вони використовують дуже схожі підходи і набагато менш популярні. Отже, якщо ви хочете хороше джерело випадковості в мережі, то ланцюгове посилання, ймовірно, є найкращим вибором на даний момент. Якщо ви просто вивчаєте солідність, не турбуючись про безпеку, ви можете спробувати підхід із часовою міткою, як у згенерованому фрагменті.
Ви знаєте відповідь?
Будь ласка, увійдіть та поділіться нею.
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).
- 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