Solidity.

Главная

Добро пожаловать на форум сообщества Solidity

Посты

39
  • 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
    0
  • MetaInvestor.
    Mar 29, 2025
    Экспертные Вопросы и Ответы

    Как сгенерировать случайное число от 1 до 2 без VRF?

    Поэтому я создавал игру на коинфлипе, в которой «голова — 1» и «решка» — 2, а когда пользователь делает ставку на цепочку полигонов... смарт-контракт генерирует случайное число от 1 до 2, а в случае одинакового результата... пользователь получает двойное вознаграждение (5% в качестве вознаграждения владельцу контракта)! из пула, и если результат будет другим, пользователь теряет все, а проигранная сумма зачисляется в пул (3% в качестве вознаграждения владельцу) (для финансирования победителей)... но есть ли способ генерировать случайное число? У меня совсем нет средств, поэтому я не могу позволить себе генерировать Chainlink VRF. Итак, есть ли другой безопасный способ для этого? Кроме того, я новичок в solidity, поэтому я сделал этот код с помощью чата gpt, но у меня ничего не получается... может ли кто-нибудь помочь улучшить код? код- // 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
    0
  • 0xflavoredBy_God.
    Feb 27, 2025
    Обсуждение

    путь к аудиту смарт-контрактов

    какой совет вы дадите тому, кто только начинает аудит смарт-контрактов

    • Smart Contract
    • Solidity
    • Yul
    0
    1
  • Eyitayo Da Dev.
    Feb 24, 2025
    Обсуждение

    Привет, ребята, я здесь новичок. Я надеялся, что кто-нибудь даст мне ссылки для эффективного изучения надежности.

    //Идентификатор лицензии SDPX: MIT надежность прагмы 0.8.24; контракт «Привет, мир!» { строка общедоступная Hello World; } //Просто нужно было что-то добавить сюда

    • Smart Contract
    • Solidity
    0
    2
  • thegreatfeez.
    Dec 09, 2024
    Обсуждение

    Новичок в области солидности

    Пройдя курс для начинающих по использованию шифрина, я пытаюсь создать что-то, что могло бы закрепить свои знания, но мне кажется, что я ничего не знаю. Меня очень огорчает. Какой совет вы, ребята, дадите

    • Smart Contract
    • Solidity
    2
    3
    Лучший ответ
  • 0x1e3f...4698.
    Sep 13, 2024
    Обсуждение

    Seeking Freelance Opportunities for Beginner Solidity Developer"

    I have been studying Solidity for a couple of weeks and do not have any previous IT background. Are there any opportunities for me to get freelance work or earn money with my current skills?

    • Solidity
    • Use cases
    0
    0
  • 0xb5d6...1329.
    Jul 24, 2024
    Обсуждение

    Formatting/Hello

    I am new to Solidity! I wanted to say hello to this awesome community in hopes that it will get me out of my shell, and hopefully meet new people. I have zero programming experience, but love crypto. When posting questions in these forums is there a certain format I should post my question in, and/or any not so obvious rules I should follow in these forums? Thank you for taking the time to read, and leaving a reply!

    • Smart Contract
    • Solidity
    • Use cases
    0
    1
  • 0xe731...d226.
    Jul 13, 2024
    Обсуждение

    Career Path in WEB3 Auditing: Project Building or Learning Auditing First?

    Hi everyone, I've recently completed the Solidity and Foundry basic and advanced courses with Cyfrin Updraft. I'm contemplating my next steps and considering a career in Solidity. Should I start learning smart contract auditing at this stage, or would it be more beneficial to first create some projects to solidify my current knowledge? Looking forward to your advice!

    • Smart Contract
    • Solidity
    0
    1
  • 0xa0c8...4ff4.
    Jun 04, 2024
    Экспертные Вопросы и Ответы

    How often does the solidity syntax change

    I'd like to know how often the solidity syntax rules are changed and the best newsletter to follow up on the most recent updates

    • Smart Contract
    • Solidity
    • Language Grammar
    • Solidity Compiler
    1
    1
  • Serpent0x.
    May 31, 2024
    Обсуждение

    Reentrancy Vulnerability

    Hello everyone , I've noticed that the offer function uses the .call{value: amount}("") method to send Ether to the recipient's address. Could anyone provide insight into whether this function is indeed vulnerable to reentrancy and suggest any best practices or modifications to mitigate such risks? function _offer(address to, uint256 amount) internal { balance -= amount; (bool success, ) = to.call{value: amount}(""); if (!success) { revert TransferFailed(address(0), address(this), to, amount); } } `

    • Smart Contract
    • Solidity
    • Solidity Compiler
    0
    1
Sui.X.Peera.

Заработай свою долю из 1000 Sui

Зарабатывай очки репутации и получай награды за помощь в развитии сообщества Sui.

Популярные теги
  • Solidity
  • Smart Contract
  • Solidity Compiler
  • Use cases
  • Yul
  • Optimizer
  • Language Grammar
  • Internals
  • Private
Мы используем файлы cookie, чтобы гарантировать вам лучший опыт на нашем сайте.
Подробнее