diff --git a/README.md b/README.md index 6b922f29..c1af5554 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,18 @@ -# 🚩 Challenge {challengeNum}: {challengeEmoji} {challengeTitle} +# 🚩 Challenge 3: 🎲 Dice Game -{challengeHeroImage} +![readme-3](./packages/nextjs/public/hero3.png) -A {challengeDescription}. +πŸ“š This tutorial is meant for developers that already understand the πŸ–οΈ basics: [Starklings](https://starklings.app/) or [Node Guardians](https://nodeguardians.io/campaigns?f=3%3D2) -🌟 The final deliverable is an app that {challengeDeliverable}. -Deploy your contracts to a testnet then build and upload your app to a public web server. Submit the url on [SpeedRunStark.com](https://speedrunstark.com/)! +> 🎰 Randomness is tricky on a public deterministic blockchain. The block hash is an easy to use, but very weak form of randomness. This challenge will give you an example of a contract using block hash to create random numbers. This randomness is exploitable. Other, stronger forms of randomness include commit/reveal schemes, oracles, or VRF from Chainlink. -πŸ’¬ Meet other builders working on this challenge and get help in the {challengeTelegramLink} +> πŸ’¬ Dice Game is a contract that allows users to roll the dice to try and win the prize. If players roll either a 0, 1, 2, 3, 4 or 5 they will win the current prize amount. The initial prize is 10% of the contract's balance, which starts out at .05 Eth. + +> 🧀 Every time a player rolls the dice, they are required to send .002 Eth. 40 percent of this value is added to the current prize amount while the other 60 percent stays in the contract to fund future prizes. Once a prize is won, the new prize amount is set to 10% of the total balance of the DiceGame contract. + +> 🧨 Your job is to attack the Dice Game contract! You will create a new contract that will predict the randomness ahead of time and only roll the dice when you're guaranteed to be a winner! + +> πŸ’¬ Submit this challenge, meet other builders working on this challenge or get help in the [Builders telegram chat](https://t.me/+wO3PtlRAreo4MDI9)! --- @@ -15,14 +20,14 @@ Deploy your contracts to a testnet then build and upload your app to a public we Before you begin, you need to install the following tools: -- [Node (>= v18.17)](https://nodejs.org/en/download/) +- [Node (v18 LTS)](https://nodejs.org/en/download/) - Yarn ([v1](https://classic.yarnpkg.com/en/docs/install/) or [v2+](https://yarnpkg.com/getting-started/install)) - [Git](https://git-scm.com/downloads) ### Compatible versions - Scarb - v2.6.5 -- Snforge - v0.27.0 +- Snforge - v0.27 - Cairo - v2.6.4 Make sure you have the compatible versions otherwise refer to [Scaffold-Stark Requirements](https://github.com/Quantum3-Labs/scaffold-stark-2?.tab=readme-ov-file#requirements) @@ -30,44 +35,153 @@ Make sure you have the compatible versions otherwise refer to [Scaffold-Stark Re Then download the challenge to your computer and install dependencies by running: ```sh -git clone https://github.com/Quantum3-Labs/speedrunstark.git {challengeName} -cd {challengeName} -git checkout {challengeName} + +git clone https://github.com/Quantum3-Labs/speedrunstark.git dice-game +cd dice-game +git checkout dice-game + yarn install ``` > in the same terminal, start your local network (a local instance of a blockchain): -```sh +```bash yarn chain ``` > in a second terminal window, πŸ›° deploy your contract (locally): ```sh -cd +cd dice-game yarn deploy ``` > in a third terminal window, start your πŸ“± frontend: ```sh -cd +cd dice-game yarn start ``` -πŸ“± Open to see the app. +πŸ“± Open [http://localhost:3000](http://localhost:3000) to see the app. + +> πŸ‘©β€πŸ’» Rerun `yarn deploy` whenever you want to deploy new contracts to the frontend. + +--- + +## Checkpoint 1: 🎲 Dice Game + +πŸ” Inspect the code in the `DiceGame.cairo` contract in `packages/snfoundry/contracts` + +πŸ”’ You will not be changing any code in the `DiceGame.cairo` contract in this challenge. You will write your own contract to predict the outcome, then only roll the dice when it is favourable. -> πŸ‘©β€πŸ’» Rerun `yarn deploy --reset` whenever you want to deploy new contracts to the frontend, update your current contracts with changes, or re-deploy it to get a fresh contract address. +### πŸ₯… Goals -πŸ” Now you are ready to edit your smart contract `{YourCollectible.cairo}` in `packages/snfoundry/contracts` +- [ ] Track the cairo code to find out how the DiceGame contract is generating random numbers. +- [ ] Is it possible to predict the random number for any given roll? --- -### βš”οΈ Side Quests +## Checkpoint 2: πŸ”‘ Rigged Contract + +Start by adding the ETh token address in the `RiggedRoll.cairo` contract to allow it to receive Eth. This will allow us to fund the RiggedRoll contract from the faucet which is required for our contract to call the `rollTheDice()` function. + +Next add a `riggedRoll()` function. This function should predict the randomness of a roll, and if the outcome will be a winner, call `rollTheDice()` on the DiceGame contract. + +πŸƒ Predict the outcome by generating your random numbers in the exact same way as the DiceGame contract. + +> πŸ“£ Reminder! Calling `rollTheDice()` will fail unless you transfer a value of at least .002 Eth!. + +πŸš€ To deploy your RiggedRoll contract, uncomment the appropriate lines in the `deploy.ts` file in `packages/snfoundry/script-ts/deploy.ts` + +πŸ’Έ You will need to send some funds to your RiggedRoll contract before doing your first roll, you can use the Faucet button at the bottom left of the page. + +❓ If you're struggling to get the exact same random number as the DiceGame contract, try adding some `console.log()` statements in both contracts to help you track the values. These messages will appear in the Hardhat node terminal. + +### βš”οΈ Side Quest + +- [ ] Add a statement to require `assert(contract_balance >= 2000000000000000,` in your riggedRoll function. This will help prevent calling the `rollTheDice()` function without enough value. +- [ ] Uncomment the code in `packages/nextjs/app/dice/page.tsx` to show a riggedRoll button and contract balance on the main UI tab. Now you can test your function without switching tabs. +- [ ] Does your riggedRoll function only call `rollTheDice()` when it's going to be a winning roll? What happens when it does call `rollTheDice()`? + +![RiggedLosingRoll](./packages/nextjs/public/ch3-roll.png) + +--- + +## Checkpoint 3: πŸ’΅ Where's my money?!? + +You have beaten the game, but where is your money? Since the RiggedRoll contract is the one calling `rollTheDice()`, that is where the prize money is being sent. + +![RiggedRollAddress](./packages/nextjs/public/ch3-events.png) + +πŸ“₯ Create a `fn withdraw(ref self: ContractState, to: ContractAddress, amount: u256)` function to allow you to send Eth from RiggedRoll to another address. + +### πŸ₯… Goals + +- [ ] Can you send value from the RiggedRoll contract to your front end address? +- [ ] Is anyone able to call the withdraw function? What would be the downside to that? + +### βš”οΈ Side Quest -_To finish your README, can add these links_ +- [ ] Lock the withdraw function so it can only be called by the owner. + +![WithdrawOnlyOwner](./packages/nextjs/public/ch3-debug.png) + +> ⚠️ But wait, I am not the owner! You will want to set your front end address as the owner in `deploy.ts`. This will allow your front end address to call the withdraw function. + +## Checkpoint 4: πŸ’Ύ Deploy your contracts! πŸ›° + +πŸ“‘ Edit the `defaultNetwork` to your choice of public Starknet networks in `packages/nextjs/scaffold.config.ts` to `sepolia`. + +![network](./packages/nextjs/public/ch0-scaffold-config.png) + +> Prepare your environment variables. + +```shell +cp packages/snfoundry/.env.example packages/snfoundry/.env +``` + +πŸ” You will need to generate a *deployer address* using Argent or Braavos, get your private key and put in `packages/snfoundry/.env` + +⛽️ You will need to send ETH or STRK to your deployer Contract Addres with your wallet, or get it from a public faucet of your chosen network. + +> Some popular faucets are [Starknet Faucet](https://starknet-faucet.vercel.app/) and [Blastapi Starknet Sepolia Eth](https://blastapi.io/faucets/starknet-sepolia-eth) + +πŸš€ Run `yarn deploy --{DESIRED NETWORK}` , we support sepolia, mainnet and devnet + +> πŸ’¬ Hint: you can `yarn deploy --network sepolia`. + +--- + +## Checkpoint 5: 🚒 Ship your frontend! 🚁 + +✏️ Edit your frontend config in `packages/nextjs/scaffold.config.ts` to change the `targetNetwork` to `chains.sepolia` or any other public network. + +πŸ’» View your frontend at and verify you see the correct network. + +πŸ“‘ When you are ready to ship the frontend app... + +πŸ“¦ Run `yarn vercel` to package up your frontend and deploy. + +> Follow the steps to deploy to Vercel. Once you log in (email, github, etc), the default options should work. It'll give you a public URL. + +> If you want to redeploy to the same production URL you can run `yarn vercel --prod`. If you omit the `--prod` flag it will deploy it to a preview/test URL. + +> 🦊 Since we have deployed to a public testnet, you will now need to connect using a wallet you own or use a burner wallet. By default πŸ”₯ `burner wallets` are only available on `devnet` . You can enable them on every chain by setting `onlyLocalBurnerWallet: false` in your frontend config (`scaffold.config.ts` in `packages/nextjs/`) + +#### Configuration of Third-Party Services for Production-Grade Apps + +By default, πŸ— Scaffold-Stark provides predefined API keys for some services such as Infura. This allows you to begin developing and testing your applications more easily, avoiding the need to register for these services. +This is great to complete your SpeedRunStark. + +For production-grade applications, it's recommended to obtain your own API keys (to prevent rate limiting issues). You can configure these at: + +πŸ”· `RPC_URL_SEPOLIA` variable in `packages/snfoundry/.env` and `packages/nextjs/.env.local`. You can create API keys from the [Infura dashboard](https://www.infura.io/). + +> πŸ’¬ Hint: It's recommended to store env's for nextjs in Vercel/system env config for live apps and use .env.local for local testing. + +--- > πŸƒ Head to your next challenge [here](https://speedrunstark.com/). -> πŸ’¬ Problems, questions, comments on the stack? Post them to the [πŸ— Scaffold-Stark developers chat](https://t.me/+wO3PtlRAreo4MDI9) +> πŸ’¬ Problems, questions, comments on the stack? Post them to the [πŸ— scaffold-stark developers chat](https://t.me/+wO3PtlRAreo4MDI9) \ No newline at end of file diff --git a/packages/nextjs/app/dice/page.tsx b/packages/nextjs/app/dice/page.tsx new file mode 100644 index 00000000..6514769c --- /dev/null +++ b/packages/nextjs/app/dice/page.tsx @@ -0,0 +1,268 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import type { NextPage } from "next"; +import { useBalance } from "@starknet-react/core"; +import { Roll, RollEvents } from "~~/components/RollEvents"; +import { Winner, WinnerEvents } from "~~/components/WinnerEvents"; +import { useScaffoldContract } from "~~/hooks/scaffold-stark/useScaffoldContract"; +import { useScaffoldReadContract } from "~~/hooks/scaffold-stark/useScaffoldReadContract"; +import { Amount } from "~~/components/diceComponents/Amount"; +import { formatEther, parseEther } from "ethers"; +import { + createContractCall, + useScaffoldMultiWriteContract, +} from "~~/hooks/scaffold-stark/useScaffoldMultiWriteContract"; +import { Address } from "~~/components/scaffold-stark"; +import { Address as AddressType } from "@starknet-react/chains"; +import { useScaffoldEventHistory } from "~~/hooks/scaffold-stark/useScaffoldEventHistory"; +import { BlockNumber } from "starknet"; +import useScaffoldEthBalance from "~~/hooks/scaffold-stark/useScaffoldEthBalance"; + +const ROLL_ETH_VALUE = "0.002"; +const MAX_TABLE_ROWS = 10; + +const DiceGame: NextPage = () => { + const [rolls, setRolls] = useState([]); + const [winners, setWinners] = useState([]); + + const videoRef = useRef(null); + + const [rolled, setRolled] = useState(false); + const [isRolling, setIsRolling] = useState(false); + const { data: accountDice } = useScaffoldContract({ + contractName: "DiceGame", + }); + + const { data: riggedRollContract } = useScaffoldContract({ + contractName: "RiggedRoll", + }); + const { value: riggedRollBalance } = useScaffoldEthBalance({ + address: riggedRollContract?.address, + // watch: true, + // blockIdentifier: "pending" as BlockNumber, + }); + + const { data: prize } = useScaffoldReadContract({ + contractName: "DiceGame", + functionName: "prize", + }); + const { writeAsync: multiContractWriteDice, isError: rollTheDiceError } = + useScaffoldMultiWriteContract({ + calls: [ + createContractCall("Eth", "approve", [ + accountDice?.address, + parseEther(ROLL_ETH_VALUE), + ]), + createContractCall("DiceGame", "roll_dice", [ + parseEther(ROLL_ETH_VALUE), + ]), + ], + }); + + const { writeAsync: multiContractWriteRigged, isError: riggedRollError } = + useScaffoldMultiWriteContract({ + calls: [ + createContractCall("Eth", "approve", [ + riggedRollContract?.address, + parseEther(ROLL_ETH_VALUE), + ]), + createContractCall("RiggedRoll", "rigged_roll", [ + parseEther(ROLL_ETH_VALUE), + ]), + ], + }); + const { data: rollsHistoryData, isLoading: rollsHistoryLoading } = + useScaffoldEventHistory({ + contractName: "DiceGame", + eventName: "contracts::DiceGame::DiceGame::Roll", + fromBlock: BigInt(0n), + watch: true, + }); + const { data: winnerHistoryData, isLoading: winnerHistoryLoading } = + useScaffoldEventHistory({ + contractName: "DiceGame", + eventName: "contracts::DiceGame::DiceGame::Winner", + fromBlock: BigInt(0n), + watch: true, + }); + + useEffect(() => { + if (rollsHistoryData?.length) { + const newRolls = ( + rollsHistoryData?.map(({ args }) => { + return { + address: args.player, + amount: Number(args.amount), + roll: args.roll.toString(16).toUpperCase(), + }; + }) || [] + ).slice(0, MAX_TABLE_ROWS); + setRolls(newRolls); + } + }, [rollsHistoryData]); + + useEffect(() => { + if (winnerHistoryData?.length) { + const newWinners = ( + winnerHistoryData?.map(({ args }) => { + return { + address: args.winner, + amount: args.amount, + }; + }) || [] + ).slice(0, MAX_TABLE_ROWS); + + setWinners(newWinners); + } + }, [winnerHistoryData]); + + const handleDice = async () => { + try { + await multiContractWriteDice(); + //refetchRiggedBalance(); + setIsRolling(false); + setRolled(true); + } catch (error) { + console.error("Error", error); + } + }; + + const handleRigged = async () => { + try { + await multiContractWriteRigged(); + //refetchRiggedBalance(); + setIsRolling(false); + setRolled(true); + } catch (error) { + console.error("Error", error); + } + }; + + useEffect(() => { + if (rollTheDiceError || riggedRollError) { + setIsRolling(false); + setRolled(false); + } + }, [riggedRollError, rollTheDiceError]); + + useEffect(() => { + if (videoRef.current && !isRolling) { + videoRef.current.currentTime = 9999; + } + }, [isRolling]); + + return ( +
+
+
+ +
+ +
+
+ + Roll a 0, 1, 2, 3, 4 or 5 to win the prize!{" "} + +
+ +
+ Prize: + +
+ + +
+ Rigged Roll +
+ Address: +
+
+
+ Balance: + +
+
+ {/* + */} + +
+ {rolled ? ( + isRolling ? ( +
+
+ +
+ +
+
+
+ ); +}; + +export default DiceGame; diff --git a/packages/nextjs/app/exampleView1/page.tsx b/packages/nextjs/app/exampleView1/page.tsx deleted file mode 100644 index 349cd12a..00000000 --- a/packages/nextjs/app/exampleView1/page.tsx +++ /dev/null @@ -1,15 +0,0 @@ -"use client"; - -import type { NextPage } from "next"; - -const ExampleView1: NextPage = () => { - return ( - <> -
-
-
- - ); -}; - -export default ExampleView1; diff --git a/packages/nextjs/app/page.tsx b/packages/nextjs/app/page.tsx index 14a6f002..ecfce706 100644 --- a/packages/nextjs/app/page.tsx +++ b/packages/nextjs/app/page.tsx @@ -1,17 +1,78 @@ "use client"; - +import Image from "next/image"; import type { NextPage } from "next"; import { useAccount } from "@starknet-react/core"; const Home: NextPage = () => { const connectedAddress = useAccount(); - return ( - <> -
-
+
+
+

+ SpeedRunStarknet + + Challenge #3: 🎲 Dice Game + +

+
+ challenge banner +
+

+ 🎰 Randomness is tricky on a public deterministic blockchain. The + block hash is an easy to use, but very weak form of randomness. + This challenge will give you an example of a contract using block + hash to create random numbers. This randomness is exploitable. + Other, stronger forms of randomness include commit/reveal schemes, + oracles, or VRF from Chainlink. +

+

+ πŸ‘ One day soon, randomness will be built into the Starknet! +

+

+ 🧀 Every time a player rolls the dice, they are required to send + .002 Eth. 40 percent of this value is added to the current prize + amount while the other 60 percent stays in the contract to fund + future prizes. Once a prize is won, the new prize amount is set to + 10% of the total balance of the DiceGame contract. +

+

+ 🧨 Your job is to attack the Dice Game contract! You will create a + new contract that will predict the randomness ahead of time and + only roll the dice when youβ€²re guaranteed to be a winner! +

+

+ πŸ’¬ Meet other builders working on this challenge and get help in + the{" "} + + Telegram Group + +

+

+ + SpeedrunStark.com + + ! +

+
+
- +
); }; diff --git a/packages/nextjs/components/Header.tsx b/packages/nextjs/components/Header.tsx index 4683518f..bab6dbee 100644 --- a/packages/nextjs/components/Header.tsx +++ b/packages/nextjs/components/Header.tsx @@ -4,7 +4,12 @@ import React, { useCallback, useRef, useState, useEffect } from "react"; import Image from "next/image"; import Link from "next/link"; import { usePathname } from "next/navigation"; -import { Bars3Icon, BugAntIcon, PhotoIcon } from "@heroicons/react/24/outline"; +import { + Bars3Icon, + BugAntIcon, + CubeIcon, + PhotoIcon, +} from "@heroicons/react/24/outline"; import { useOutsideClick } from "~~/hooks/scaffold-stark"; import { CustomConnectButton } from "~~/components/scaffold-stark/CustomConnectButton"; import { useTheme } from "next-themes"; @@ -21,9 +26,13 @@ type HeaderMenuLink = { export const menuLinks: HeaderMenuLink[] = [ { - label: "Example View 1", - href: "/exampleView1", - icon: , + label: "Home", + href: "/", + }, + { + label: "Dice Game", + href: "/dice", + icon: , }, { label: "Debug Contracts", diff --git a/packages/nextjs/components/RollEvents.tsx b/packages/nextjs/components/RollEvents.tsx new file mode 100644 index 00000000..572bcc63 --- /dev/null +++ b/packages/nextjs/components/RollEvents.tsx @@ -0,0 +1,50 @@ +import React from "react"; +import { Address } from "./scaffold-stark/Address"; +import { Address as AddressType } from "@starknet-react/chains"; + +export type Roll = { + address: AddressType; + amount: number; + roll: string; +}; + +export type RollEventsProps = { + rolls: Roll[]; +}; + +export const RollEvents = ({ rolls }: RollEventsProps) => { + return ( +
+
+

Roll Events

+
+ + + + + + + + + + {rolls.map(({ address, roll }, i) => { + return ( + + + + + ); + })} + +
+ Address + + Roll +
+
+
+ {roll} +
+
+ ); +}; diff --git a/packages/nextjs/components/WinnerEvents.tsx b/packages/nextjs/components/WinnerEvents.tsx new file mode 100644 index 00000000..b09e5982 --- /dev/null +++ b/packages/nextjs/components/WinnerEvents.tsx @@ -0,0 +1,68 @@ +import React, { useState } from "react"; +import { Amount } from "~~/components/diceComponents/Amount"; +import { Address as AddressType } from "@starknet-react/chains"; +import { Address } from "~~/components/scaffold-stark"; +import { formatEther } from "ethers"; + +export type Winner = { + address: AddressType; + amount: bigint | number; +}; + +export type WinnerEventsProps = { + winners: Winner[]; +}; + +export const WinnerEvents = ({ winners }: WinnerEventsProps) => { + const [showUsdPrice, setShowUsdPrice] = useState(true); + return ( +
+
+

Winner Events

+
+ + + + + + + + + + {winners.map(({ address, amount }, i) => { + return ( + + + + + ); + })} + +
+ Address + { + setShowUsdPrice(!showUsdPrice); + }} + > + Won +
+
+
{ + setShowUsdPrice(!showUsdPrice); + }} + > + +
+
+ ); +}; diff --git a/packages/nextjs/components/diceComponents/Amount.tsx b/packages/nextjs/components/diceComponents/Amount.tsx new file mode 100644 index 00000000..90003fe6 --- /dev/null +++ b/packages/nextjs/components/diceComponents/Amount.tsx @@ -0,0 +1,70 @@ +import { useEffect, useState } from "react"; +import { useGlobalState } from "~~/services/store/store"; +import { useTargetNetwork } from "~~/hooks/scaffold-stark/useTargetNetwork"; + +type TAmountProps = { + amount?: number; + className?: string; + isLoading?: boolean; + showUsdPrice?: boolean; + disableToggle?: boolean; +}; + +/** + * Display (ETH & USD) balance of an ETH address. + */ +export const Amount = ({ + isLoading, + showUsdPrice = false, + amount = 0, + className = "", + disableToggle = false, +}: TAmountProps) => { + const { targetNetwork: configuredNetwork } = useTargetNetwork(); + const price = useGlobalState((state) => state.nativeCurrencyPrice); + const [isEthBalance, setEthBalance] = useState(!showUsdPrice); + + useEffect(() => { + setEthBalance(!showUsdPrice); + }, [showUsdPrice]); + + if (isLoading) { + return ( +
+
+
+
+
+
+ ); + } + + const onToggleBalance = () => { + if (!disableToggle) { + setEthBalance(!isEthBalance); + } + }; + + return ( + + ); +}; diff --git a/packages/nextjs/components/diceComponents/RollEvents.tsx b/packages/nextjs/components/diceComponents/RollEvents.tsx new file mode 100644 index 00000000..87968d0e --- /dev/null +++ b/packages/nextjs/components/diceComponents/RollEvents.tsx @@ -0,0 +1,48 @@ +import React from "react"; +import { Address } from "~~/components/scaffold-stark"; +import { Address as AddressType } from "@starknet-react/chains"; + +export type Roll = { + address: AddressType; + amount: number; + roll: string; +}; + +export type RollEventsProps = { + rolls: Roll[]; +}; + +export const RollEvents = ({ rolls }: RollEventsProps) => { + return ( +
+
+

Roll Events

+
+ + + + + + + + + + {rolls.map(({ address, roll }, i) => ( + + + + + ))} + +
+ Address + + Roll +
+
+
+ {roll} +
+
+ ); +}; diff --git a/packages/nextjs/contracts/deployedContracts.ts b/packages/nextjs/contracts/deployedContracts.ts index 25751cee..8151fd30 100644 --- a/packages/nextjs/contracts/deployedContracts.ts +++ b/packages/nextjs/contracts/deployedContracts.ts @@ -3,6 +3,396 @@ * You should not edit it manually or your changes might be overwritten. */ -const deployedContracts = {} as const; +const deployedContracts = { + devnet: { + DiceGame: { + address: + "0x5566fd3a15aa0ab2e3d489f151d0094cbeebef35b3b216a20d0ed17aa0bb21", + abi: [ + { + type: "impl", + name: "DiceGameImpl", + interface_name: "contracts::DiceGame::IDiceGame", + }, + { + type: "struct", + name: "core::integer::u256", + members: [ + { + name: "low", + type: "core::integer::u128", + }, + { + name: "high", + type: "core::integer::u128", + }, + ], + }, + { + type: "struct", + name: "openzeppelin::token::erc20::interface::IERC20CamelDispatcher", + members: [ + { + name: "contract_address", + type: "core::starknet::contract_address::ContractAddress", + }, + ], + }, + { + type: "interface", + name: "contracts::DiceGame::IDiceGame", + items: [ + { + type: "function", + name: "roll_dice", + inputs: [ + { + name: "amount", + type: "core::integer::u256", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "function", + name: "last_dice_value", + inputs: [], + outputs: [ + { + type: "core::integer::u256", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "nonce", + inputs: [], + outputs: [ + { + type: "core::integer::u256", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "prize", + inputs: [], + outputs: [ + { + type: "core::integer::u256", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "eth_token_dispatcher", + inputs: [], + outputs: [ + { + type: "openzeppelin::token::erc20::interface::IERC20CamelDispatcher", + }, + ], + state_mutability: "view", + }, + ], + }, + { + type: "constructor", + name: "constructor", + inputs: [ + { + name: "eth_token_address", + type: "core::starknet::contract_address::ContractAddress", + }, + ], + }, + { + type: "event", + name: "contracts::DiceGame::DiceGame::Roll", + kind: "struct", + members: [ + { + name: "player", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + { + name: "amount", + type: "core::integer::u256", + kind: "data", + }, + { + name: "roll", + type: "core::integer::u256", + kind: "data", + }, + ], + }, + { + type: "event", + name: "contracts::DiceGame::DiceGame::Winner", + kind: "struct", + members: [ + { + name: "winner", + type: "core::starknet::contract_address::ContractAddress", + kind: "data", + }, + { + name: "amount", + type: "core::integer::u256", + kind: "data", + }, + ], + }, + { + type: "event", + name: "contracts::DiceGame::DiceGame::Event", + kind: "enum", + variants: [ + { + name: "Roll", + type: "contracts::DiceGame::DiceGame::Roll", + kind: "nested", + }, + { + name: "Winner", + type: "contracts::DiceGame::DiceGame::Winner", + kind: "nested", + }, + ], + }, + ], + classHash: + "0x14225211cee35d5f61e9896569f5b731f306e4ab280cf55fcfba0ac11356849", + }, + RiggedRoll: { + address: + "0x149557df374fe92a908816ba2381a75e232f5853446dc7be6a293279b0f187b", + abi: [ + { + type: "impl", + name: "RiggedRollImpl", + interface_name: "contracts::RiggedRoll::IRiggedRoll", + }, + { + type: "struct", + name: "core::integer::u256", + members: [ + { + name: "low", + type: "core::integer::u128", + }, + { + name: "high", + type: "core::integer::u128", + }, + ], + }, + { + type: "struct", + name: "contracts::DiceGame::IDiceGameDispatcher", + members: [ + { + name: "contract_address", + type: "core::starknet::contract_address::ContractAddress", + }, + ], + }, + { + type: "interface", + name: "contracts::RiggedRoll::IRiggedRoll", + items: [ + { + type: "function", + name: "rigged_roll", + inputs: [ + { + name: "amount", + type: "core::integer::u256", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "function", + name: "withdraw", + inputs: [ + { + name: "to", + type: "core::starknet::contract_address::ContractAddress", + }, + { + name: "amount", + type: "core::integer::u256", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "function", + name: "last_dice_value", + inputs: [], + outputs: [ + { + type: "core::integer::u256", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "predicted_roll", + inputs: [], + outputs: [ + { + type: "core::integer::u256", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "dice_game_dispatcher", + inputs: [], + outputs: [ + { + type: "contracts::DiceGame::IDiceGameDispatcher", + }, + ], + state_mutability: "view", + }, + ], + }, + { + type: "impl", + name: "OwnableImpl", + interface_name: "openzeppelin::access::ownable::interface::IOwnable", + }, + { + type: "interface", + name: "openzeppelin::access::ownable::interface::IOwnable", + items: [ + { + type: "function", + name: "owner", + inputs: [], + outputs: [ + { + type: "core::starknet::contract_address::ContractAddress", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "transfer_ownership", + inputs: [ + { + name: "new_owner", + type: "core::starknet::contract_address::ContractAddress", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "function", + name: "renounce_ownership", + inputs: [], + outputs: [], + state_mutability: "external", + }, + ], + }, + { + type: "constructor", + name: "constructor", + inputs: [ + { + name: "dice_game_address", + type: "core::starknet::contract_address::ContractAddress", + }, + { + name: "owner", + type: "core::starknet::contract_address::ContractAddress", + }, + ], + }, + { + type: "event", + name: "openzeppelin::access::ownable::ownable::OwnableComponent::OwnershipTransferred", + kind: "struct", + members: [ + { + name: "previous_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + { + name: "new_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + ], + }, + { + type: "event", + name: "openzeppelin::access::ownable::ownable::OwnableComponent::OwnershipTransferStarted", + kind: "struct", + members: [ + { + name: "previous_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + { + name: "new_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + ], + }, + { + type: "event", + name: "openzeppelin::access::ownable::ownable::OwnableComponent::Event", + kind: "enum", + variants: [ + { + name: "OwnershipTransferred", + type: "openzeppelin::access::ownable::ownable::OwnableComponent::OwnershipTransferred", + kind: "nested", + }, + { + name: "OwnershipTransferStarted", + type: "openzeppelin::access::ownable::ownable::OwnableComponent::OwnershipTransferStarted", + kind: "nested", + }, + ], + }, + { + type: "event", + name: "contracts::RiggedRoll::RiggedRoll::Event", + kind: "enum", + variants: [ + { + name: "OwnableEvent", + type: "openzeppelin::access::ownable::ownable::OwnableComponent::Event", + kind: "flat", + }, + ], + }, + ], + classHash: + "0x48a5dcd9cf8dd96574a47a92bf7ad369796cfc88dc2a7dd95b588c19d3f2056", + }, + }, +} as const; export default deployedContracts; diff --git a/packages/nextjs/public/ch0-scaffold-config.png b/packages/nextjs/public/ch0-scaffold-config.png new file mode 100644 index 00000000..e043b787 Binary files /dev/null and b/packages/nextjs/public/ch0-scaffold-config.png differ diff --git a/packages/nextjs/public/ch3-debug.png b/packages/nextjs/public/ch3-debug.png new file mode 100644 index 00000000..bde42f6e Binary files /dev/null and b/packages/nextjs/public/ch3-debug.png differ diff --git a/packages/nextjs/public/ch3-events.png b/packages/nextjs/public/ch3-events.png new file mode 100644 index 00000000..633b4018 Binary files /dev/null and b/packages/nextjs/public/ch3-events.png differ diff --git a/packages/nextjs/public/ch3-roll.png b/packages/nextjs/public/ch3-roll.png new file mode 100644 index 00000000..d8a6c657 Binary files /dev/null and b/packages/nextjs/public/ch3-roll.png differ diff --git a/packages/nextjs/public/hero3.png b/packages/nextjs/public/hero3.png new file mode 100644 index 00000000..4dcb6a06 Binary files /dev/null and b/packages/nextjs/public/hero3.png differ diff --git a/packages/nextjs/public/riggedroll.png b/packages/nextjs/public/riggedroll.png new file mode 100644 index 00000000..6d07fdd0 Binary files /dev/null and b/packages/nextjs/public/riggedroll.png differ diff --git a/packages/nextjs/public/rolldice.png b/packages/nextjs/public/rolldice.png new file mode 100644 index 00000000..94c89b93 Binary files /dev/null and b/packages/nextjs/public/rolldice.png differ diff --git a/packages/nextjs/public/rolls/0.webm b/packages/nextjs/public/rolls/0.webm new file mode 100644 index 00000000..4e02e16e Binary files /dev/null and b/packages/nextjs/public/rolls/0.webm differ diff --git a/packages/nextjs/public/rolls/1.webm b/packages/nextjs/public/rolls/1.webm new file mode 100644 index 00000000..c8cc1def Binary files /dev/null and b/packages/nextjs/public/rolls/1.webm differ diff --git a/packages/nextjs/public/rolls/2.webm b/packages/nextjs/public/rolls/2.webm new file mode 100644 index 00000000..31d55bcc Binary files /dev/null and b/packages/nextjs/public/rolls/2.webm differ diff --git a/packages/nextjs/public/rolls/3.webm b/packages/nextjs/public/rolls/3.webm new file mode 100644 index 00000000..d7fc2c79 Binary files /dev/null and b/packages/nextjs/public/rolls/3.webm differ diff --git a/packages/nextjs/public/rolls/4.webm b/packages/nextjs/public/rolls/4.webm new file mode 100644 index 00000000..f0993c9f Binary files /dev/null and b/packages/nextjs/public/rolls/4.webm differ diff --git a/packages/nextjs/public/rolls/5.webm b/packages/nextjs/public/rolls/5.webm new file mode 100644 index 00000000..665cdb36 Binary files /dev/null and b/packages/nextjs/public/rolls/5.webm differ diff --git a/packages/nextjs/public/rolls/6.webm b/packages/nextjs/public/rolls/6.webm new file mode 100644 index 00000000..a15953c1 Binary files /dev/null and b/packages/nextjs/public/rolls/6.webm differ diff --git a/packages/nextjs/public/rolls/7.webm b/packages/nextjs/public/rolls/7.webm new file mode 100644 index 00000000..8bf623e2 Binary files /dev/null and b/packages/nextjs/public/rolls/7.webm differ diff --git a/packages/nextjs/public/rolls/8.webm b/packages/nextjs/public/rolls/8.webm new file mode 100644 index 00000000..f1828297 Binary files /dev/null and b/packages/nextjs/public/rolls/8.webm differ diff --git a/packages/nextjs/public/rolls/9.webm b/packages/nextjs/public/rolls/9.webm new file mode 100644 index 00000000..3dd1985e Binary files /dev/null and b/packages/nextjs/public/rolls/9.webm differ diff --git a/packages/nextjs/public/rolls/A.webm b/packages/nextjs/public/rolls/A.webm new file mode 100644 index 00000000..452b4fdf Binary files /dev/null and b/packages/nextjs/public/rolls/A.webm differ diff --git a/packages/nextjs/public/rolls/B.webm b/packages/nextjs/public/rolls/B.webm new file mode 100644 index 00000000..6022114a Binary files /dev/null and b/packages/nextjs/public/rolls/B.webm differ diff --git a/packages/nextjs/public/rolls/C.webm b/packages/nextjs/public/rolls/C.webm new file mode 100644 index 00000000..91fb9f06 Binary files /dev/null and b/packages/nextjs/public/rolls/C.webm differ diff --git a/packages/nextjs/public/rolls/D.webm b/packages/nextjs/public/rolls/D.webm new file mode 100644 index 00000000..f2d6b4fd Binary files /dev/null and b/packages/nextjs/public/rolls/D.webm differ diff --git a/packages/nextjs/public/rolls/E.webm b/packages/nextjs/public/rolls/E.webm new file mode 100644 index 00000000..1f36bb83 Binary files /dev/null and b/packages/nextjs/public/rolls/E.webm differ diff --git a/packages/nextjs/public/rolls/F.webm b/packages/nextjs/public/rolls/F.webm new file mode 100644 index 00000000..4dbaf8d7 Binary files /dev/null and b/packages/nextjs/public/rolls/F.webm differ diff --git a/packages/nextjs/public/rolls/Spin.webm b/packages/nextjs/public/rolls/Spin.webm new file mode 100644 index 00000000..71ecf07d Binary files /dev/null and b/packages/nextjs/public/rolls/Spin.webm differ diff --git a/packages/nextjs/public/withdraw.png b/packages/nextjs/public/withdraw.png new file mode 100644 index 00000000..3c8a7035 Binary files /dev/null and b/packages/nextjs/public/withdraw.png differ diff --git a/packages/snfoundry/contracts/src/DiceGame.cairo b/packages/snfoundry/contracts/src/DiceGame.cairo new file mode 100644 index 00000000..000c9645 --- /dev/null +++ b/packages/snfoundry/contracts/src/DiceGame.cairo @@ -0,0 +1,108 @@ +use openzeppelin::token::erc20::interface::{IERC20CamelDispatcher, IERC20CamelDispatcherTrait}; + +#[starknet::interface] +pub trait IDiceGame { + fn roll_dice(ref self: T, amount: u256); + fn last_dice_value(self: @T) -> u256; + fn nonce(self: @T) -> u256; + fn prize(self: @T) -> u256; + fn eth_token_dispatcher(self: @T) -> IERC20CamelDispatcher; +} + +#[starknet::contract] +pub mod DiceGame { + use keccak::keccak_u256s_le_inputs; + use starknet::{ContractAddress, get_contract_address, get_block_number, get_caller_address}; + use super::{IERC20CamelDispatcher, IERC20CamelDispatcherTrait, IDiceGame}; + + #[event] + #[derive(Drop, starknet::Event)] + pub enum Event { + Roll: Roll, + Winner: Winner, + } + + #[derive(Drop, starknet::Event)] + pub struct Roll { + #[key] + pub player: ContractAddress, + pub amount: u256, + pub roll: u256, + } + + #[derive(Drop, starknet::Event)] + pub struct Winner { + pub winner: ContractAddress, + pub amount: u256, + } + + #[storage] + struct Storage { + eth_token: IERC20CamelDispatcher, + nonce: u256, + prize: u256, + last_dice_value: u256 + } + + #[constructor] + fn constructor(ref self: ContractState, eth_token_address: ContractAddress) { + self.eth_token.write(IERC20CamelDispatcher { contract_address: eth_token_address }); + self._reset_prize(); + } + + + #[abi(embed_v0)] + impl DiceGameImpl of super::IDiceGame { + fn roll_dice(ref self: ContractState, amount: u256) { + // >= 0.002 ETH + assert(amount >= 2000000000000000, 'Not enough ETH'); + let caller = get_caller_address(); + let this_contract = get_contract_address(); + // call approve on UI + self.eth_token.read().transferFrom(caller, this_contract, amount); + + let prev_block: u256 = get_block_number().into() - 1; + let array = array![prev_block, self.nonce.read()]; + let roll = keccak_u256s_le_inputs(array.span()) % 16; + self.last_dice_value.write(roll); + self.nonce.write(self.nonce.read() + 1); + let new_prize = self.prize.read() + amount * 4 / 10; + self.prize.write(new_prize); + + self.emit(Roll { player: caller, amount, roll }); + + if (roll > 5) { + return; + } + + let contract_balance = self.eth_token.read().balanceOf(this_contract); + let prize = self.prize.read(); + assert(contract_balance >= prize, 'Not enough balance'); + self.eth_token.read().transfer(caller, prize); + + self._reset_prize(); + self.emit(Winner { winner: caller, amount: prize }); + } + fn last_dice_value(self: @ContractState) -> u256 { + self.last_dice_value.read() + } + fn nonce(self: @ContractState) -> u256 { + self.nonce.read() + } + + fn prize(self: @ContractState) -> u256 { + self.prize.read() + } + fn eth_token_dispatcher(self: @ContractState) -> IERC20CamelDispatcher { + self.eth_token.read() + } + } + + #[generate_trait] + pub impl InternalImpl of InternalTrait { + fn _reset_prize(ref self: ContractState) { + let contract_balance = self.eth_token.read().balanceOf(get_contract_address()); + self.prize.write(contract_balance / 10); + } + } +} diff --git a/packages/snfoundry/contracts/src/RiggedRoll.cairo b/packages/snfoundry/contracts/src/RiggedRoll.cairo new file mode 100644 index 00000000..c34a43e2 --- /dev/null +++ b/packages/snfoundry/contracts/src/RiggedRoll.cairo @@ -0,0 +1,72 @@ +use contracts::DiceGame::{IDiceGameDispatcher, IDiceGameDispatcherTrait}; +use starknet::ContractAddress; + +#[starknet::interface] +pub trait IRiggedRoll { + fn rigged_roll(ref self: T, amount: u256); + fn withdraw(ref self: T, to: ContractAddress, amount: u256); + fn last_dice_value(self: @T) -> u256; + fn predicted_roll(self: @T) -> u256; + fn dice_game_dispatcher(self: @T) -> IDiceGameDispatcher; +} + +#[starknet::contract] +mod RiggedRoll { + use keccak::keccak_u256s_le_inputs; + use openzeppelin::access::ownable::OwnableComponent; + use openzeppelin::token::erc20::interface::IERC20CamelDispatcherTrait; + use starknet::{ContractAddress, get_contract_address, get_block_number, get_caller_address}; + use super::{IRiggedRoll, IDiceGameDispatcher, IDiceGameDispatcherTrait}; + + component!(path: OwnableComponent, storage: ownable, event: OwnableEvent); + + #[abi(embed_v0)] + impl OwnableImpl = OwnableComponent::OwnableImpl; + + impl OwnableInternalImpl = OwnableComponent::InternalImpl; + + #[storage] + struct Storage { + dice_game: IDiceGameDispatcher, + #[substorage(v0)] + ownable: OwnableComponent::Storage, + predicted_roll: u256 + } + + #[event] + #[derive(Drop, starknet::Event)] + enum Event { + #[flat] + OwnableEvent: OwnableComponent::Event + } + + #[constructor] + fn constructor( + ref self: ContractState, dice_game_address: ContractAddress, owner: ContractAddress + ) { + self.dice_game.write(IDiceGameDispatcher { contract_address: dice_game_address }); + self.ownable.initializer(owner); + } + + #[abi(embed_v0)] + impl RiggedRollImpl of super::IRiggedRoll { + fn rigged_roll( + ref self: ContractState, amount: u256 + ) { // Create the `rigged_roll()` function to predict the randomness in the DiceGame contract and only initiate a roll when it guarantees a win. + } + fn withdraw( + ref self: ContractState, to: ContractAddress, amount: u256 + ) { // Implement the `withdraw` function to transfer Ether from the rigged contract to a specified address. + } + + fn last_dice_value(self: @ContractState) -> u256 { + self.dice_game.read().last_dice_value() + } + fn predicted_roll(self: @ContractState) -> u256 { + self.predicted_roll.read() + } + fn dice_game_dispatcher(self: @ContractState) -> IDiceGameDispatcher { + self.dice_game.read() + } + } +} diff --git a/packages/snfoundry/contracts/src/YourContract.cairo b/packages/snfoundry/contracts/src/YourContract.cairo deleted file mode 100644 index 21e18509..00000000 --- a/packages/snfoundry/contracts/src/YourContract.cairo +++ /dev/null @@ -1,103 +0,0 @@ -#[starknet::interface] -pub trait IYourContract { - fn gretting(self: @TContractState) -> ByteArray; - fn set_gretting(ref self: TContractState, new_greeting: ByteArray, amount_eth: u256); - fn withdraw(ref self: TContractState); - fn premium(self: @TContractState) -> bool; -} - -#[starknet::contract] -mod YourContract { - use openzeppelin::access::ownable::OwnableComponent; - use openzeppelin::token::erc20::interface::{IERC20CamelDispatcher, IERC20CamelDispatcherTrait}; - use starknet::{ContractAddress, contract_address_const}; - use starknet::{get_caller_address, get_contract_address}; - use super::{IYourContract}; - - component!(path: OwnableComponent, storage: ownable, event: OwnableEvent); - - #[abi(embed_v0)] - impl OwnableImpl = OwnableComponent::OwnableImpl; - impl OwnableInternalImpl = OwnableComponent::InternalImpl; - - const ETH_CONTRACT_ADDRESS: felt252 = - 0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7; - - #[event] - #[derive(Drop, starknet::Event)] - enum Event { - #[flat] - OwnableEvent: OwnableComponent::Event, - GreetingChanged: GreetingChanged - } - - #[derive(Drop, starknet::Event)] - struct GreetingChanged { - #[key] - greeting_setter: ContractAddress, - #[key] - new_greeting: ByteArray, - premium: bool, - value: u256, - } - - #[storage] - struct Storage { - eth_token: IERC20CamelDispatcher, - greeting: ByteArray, - premium: bool, - total_counter: u256, - user_gretting_counter: LegacyMap, - #[substorage(v0)] - ownable: OwnableComponent::Storage, - } - - #[constructor] - fn constructor(ref self: ContractState, owner: ContractAddress) { - let eth_contract_address = contract_address_const::(); - self.eth_token.write(IERC20CamelDispatcher { contract_address: eth_contract_address }); - self.greeting.write("Building Unstoppable Apps!!!"); - self.ownable.initializer(owner); - } - - #[abi(embed_v0)] - impl YourContractImpl of IYourContract { - fn gretting(self: @ContractState) -> ByteArray { - self.greeting.read() - } - fn set_gretting(ref self: ContractState, new_greeting: ByteArray, amount_eth: u256) { - self.greeting.write(new_greeting); - self.total_counter.write(self.total_counter.read() + 1); - let user_counter = self.user_gretting_counter.read(get_caller_address()); - self.user_gretting_counter.write(get_caller_address(), user_counter + 1); - - if amount_eth > 0 { - // In `Debug Contract` or UI implementation call `approve` on ETH contract before invoke fn set_gretting() - self - .eth_token - .read() - .transferFrom(get_caller_address(), get_contract_address(), amount_eth); - self.premium.write(true); - } else { - self.premium.write(false); - } - self - .emit( - GreetingChanged { - greeting_setter: get_caller_address(), - new_greeting: self.greeting.read(), - premium: true, - value: 100 - } - ); - } - fn withdraw(ref self: ContractState) { - self.ownable.assert_only_owner(); - let balance = self.eth_token.read().balanceOf(get_contract_address()); - self.eth_token.read().transfer(self.ownable.owner(), balance); - } - fn premium(self: @ContractState) -> bool { - self.premium.read() - } - } -} diff --git a/packages/snfoundry/contracts/src/lib.cairo b/packages/snfoundry/contracts/src/lib.cairo index 568f9f72..760de311 100644 --- a/packages/snfoundry/contracts/src/lib.cairo +++ b/packages/snfoundry/contracts/src/lib.cairo @@ -1,5 +1,10 @@ -mod YourContract; +mod DiceGame; +mod RiggedRoll; +mod mock_contracts { + pub mod MockETHToken; +} #[cfg(test)] mod test { mod TestContract; } + diff --git a/packages/snfoundry/contracts/src/mock_contracts/MockETHToken.cairo b/packages/snfoundry/contracts/src/mock_contracts/MockETHToken.cairo new file mode 100644 index 00000000..07064311 --- /dev/null +++ b/packages/snfoundry/contracts/src/mock_contracts/MockETHToken.cairo @@ -0,0 +1,34 @@ +#[starknet::contract] +pub mod MockETHToken { + use openzeppelin::token::erc20::{ERC20Component, ERC20HooksEmptyImpl}; + use starknet::ContractAddress; + + component!(path: ERC20Component, storage: erc20, event: ERC20Event); + + #[abi(embed_v0)] + impl ERC20Impl = ERC20Component::ERC20MixinImpl; + impl ERC20InternalImpl = ERC20Component::InternalImpl; + + #[storage] + struct Storage { + #[substorage(v0)] + erc20: ERC20Component::Storage + } + + #[event] + #[derive(Drop, starknet::Event)] + enum Event { + #[flat] + ERC20Event: ERC20Component::Event + } + + #[constructor] + fn constructor(ref self: ContractState, initial_supply: u256, recipient: ContractAddress) { + let name = "MockETH"; + let symbol = "ETH"; + + self.erc20.initializer(name, symbol); + let amount_to_mint = initial_supply / 10; + self.erc20.mint(recipient, amount_to_mint); + } +} diff --git a/packages/snfoundry/contracts/src/test/TestContract.cairo b/packages/snfoundry/contracts/src/test/TestContract.cairo index 8b137891..b10f0977 100644 --- a/packages/snfoundry/contracts/src/test/TestContract.cairo +++ b/packages/snfoundry/contracts/src/test/TestContract.cairo @@ -1 +1,216 @@ +use contracts::DiceGame::{IDiceGameDispatcher, IDiceGameDispatcherTrait, DiceGame}; +use contracts::RiggedRoll::{IRiggedRollDispatcher, IRiggedRollDispatcherTrait}; +use contracts::mock_contracts::MockETHToken; +use keccak::keccak_u256s_le_inputs; +use openzeppelin::token::erc20::interface::{IERC20CamelDispatcher, IERC20CamelDispatcherTrait}; +use openzeppelin::utils::serde::SerializedAppend; +use snforge_std::cheatcodes::events::EventsFilterTrait; +use snforge_std::{ + declare, ContractClassTrait, spy_events, EventSpyAssertionsTrait, EventSpyTrait, Event, + cheat_caller_address, cheat_block_timestamp, CheatSpan +}; +use starknet::{ContractAddress, get_contract_address, get_block_number, get_caller_address}; +use starknet::{contract_address_const, get_block_timestamp}; + +fn OWNER() -> ContractAddress { + contract_address_const::<'OWNER'>() +} + +const ROLL_DICE_AMOUNT: u256 = 2000000000000000; // 0.002_ETH_IN_WEI +// Should deploy the MockETHToken contract +fn deploy_mock_eth_token() -> ContractAddress { + let erc20_class_hash = declare("MockETHToken").unwrap(); + let INITIAL_SUPPLY: u256 = 100000000000000000000; // 100_ETH_IN_WEI + let reciever = OWNER(); + let mut calldata = array![]; + calldata.append_serde(INITIAL_SUPPLY); + calldata.append_serde(reciever); + let (eth_token_address, _) = erc20_class_hash.deploy(@calldata).unwrap(); + eth_token_address +} + +// Should deploy the DiceGame contract +fn deploy_dice_game_contract() -> ContractAddress { + let eth_token_address = deploy_mock_eth_token(); + let dice_game_class_hash = declare("DiceGame").unwrap(); + let mut calldata = array![]; + calldata.append_serde(eth_token_address); + let (dice_game_contract_address, _) = dice_game_class_hash.deploy(@calldata).unwrap(); + println!("-- Dice Game contract deployed on: {:?}", dice_game_contract_address); + dice_game_contract_address +} + +fn deploy_rigged_roll_contract() -> ContractAddress { + let dice_game_contract_address = deploy_dice_game_contract(); + let rigged_roll_class_hash = declare("RiggedRoll").unwrap(); + let mut calldata = array![]; + calldata.append_serde(dice_game_contract_address); + calldata.append_serde(OWNER()); + let (rigged_roll_contract_address, _) = rigged_roll_class_hash.deploy(@calldata).unwrap(); + println!("-- Rigged Roll contract deployed on: {:?}", rigged_roll_contract_address); + rigged_roll_contract_address +} + +fn get_roll(get_roll_less_than_5: bool, rigged_roll_dispatcher: IRiggedRollDispatcher) -> u256 { + let mut expected_roll = 0; + let dice_game_dispatcher = rigged_roll_dispatcher.dice_game_dispatcher(); + let dice_game_contract_address = dice_game_dispatcher.contract_address; + let tester_address = OWNER(); + while true { + let prev_block: u256 = get_block_number().into() - 1; + let array = array![prev_block, dice_game_dispatcher.nonce()]; + expected_roll = keccak_u256s_le_inputs(array.span()) % 16; + println!("-- Produced roll: {:?}", expected_roll); + if expected_roll <= 5 == get_roll_less_than_5 { + break; + } + let eth_token_dispatcher = dice_game_dispatcher.eth_token_dispatcher(); + cheat_caller_address( + eth_token_dispatcher.contract_address, tester_address, CheatSpan::TargetCalls(1) + ); + eth_token_dispatcher.approve(dice_game_contract_address, ROLL_DICE_AMOUNT); + cheat_caller_address(dice_game_contract_address, tester_address, CheatSpan::TargetCalls(1)); + dice_game_dispatcher.roll_dice(ROLL_DICE_AMOUNT); + }; + expected_roll +} +#[test] +fn test_deploy_dice_game() { + deploy_dice_game_contract(); +} + +#[test] +fn test_deploy_rigged_roll() { + deploy_rigged_roll_contract(); +} + +#[test] +#[should_panic(expected: ('Not enough ETH',))] +fn test_rigged_roll_fails() { + let rigged_roll_contract_address = deploy_rigged_roll_contract(); + let rigged_roll_dispatcher = IRiggedRollDispatcher { + contract_address: rigged_roll_contract_address + }; + let eth_amount_wei: u256 = 1000000000000000; // 0.001_ETH_IN_WEI + + let tester_address = OWNER(); + let eth_token_dispatcher = rigged_roll_dispatcher.dice_game_dispatcher().eth_token_dispatcher(); + cheat_caller_address( + eth_token_dispatcher.contract_address, tester_address, CheatSpan::TargetCalls(1) + ); + eth_token_dispatcher.approve(rigged_roll_contract_address, eth_amount_wei); + cheat_caller_address(rigged_roll_contract_address, tester_address, CheatSpan::TargetCalls(1)); + rigged_roll_dispatcher.rigged_roll(eth_amount_wei); +} + +#[test] +fn test_rigged_roll_call_dice_game() { + let rigged_roll_contract_address = deploy_rigged_roll_contract(); + let rigged_roll_dispatcher = IRiggedRollDispatcher { + contract_address: rigged_roll_contract_address + }; + let dice_game_dispatcher = rigged_roll_dispatcher.dice_game_dispatcher(); + + let get_roll_less_than_5 = true; + let expected_roll = get_roll(get_roll_less_than_5, rigged_roll_dispatcher); + println!("-- Expect roll to be less than or equal to 5. DiceGame Roll:: {:?}", expected_roll); + let tester_address = OWNER(); + let eth_token_dispatcher = dice_game_dispatcher.eth_token_dispatcher(); + cheat_caller_address( + eth_token_dispatcher.contract_address, tester_address, CheatSpan::TargetCalls(1) + ); + eth_token_dispatcher.approve(rigged_roll_contract_address, ROLL_DICE_AMOUNT); + + cheat_caller_address(rigged_roll_contract_address, tester_address, CheatSpan::TargetCalls(1)); + + let mut spy = spy_events(); + rigged_roll_dispatcher.rigged_roll(ROLL_DICE_AMOUNT); + + let dice_game_contract = dice_game_dispatcher.contract_address; + let events = spy.get_events().emitted_by(dice_game_contract); + + assert_eq!(events.events.len(), 2, "There should be two events emitted by DiceGame contract"); + spy + .assert_emitted( + @array![ + ( + dice_game_contract, + DiceGame::Event::Roll( + DiceGame::Roll { + player: rigged_roll_contract_address, + amount: ROLL_DICE_AMOUNT, + roll: expected_roll + } + ) + ) + ] + ); + let (_, event) = events.events.at(1); + assert(event.keys.at(0) == @selector!("Winner"), 'Expected Winner event'); +} + +#[test] +fn test_rigged_roll_should_not_call_dice_game() { + let rigged_roll_contract_address = deploy_rigged_roll_contract(); + let rigged_roll_dispatcher = IRiggedRollDispatcher { + contract_address: rigged_roll_contract_address + }; + let dice_game_dispatcher = rigged_roll_dispatcher.dice_game_dispatcher(); + + let get_roll_less_than_5 = false; + let expected_roll = get_roll(get_roll_less_than_5, rigged_roll_dispatcher); + println!("-- Expect roll to be greater than 5. DiceGame Roll:: {:?}", expected_roll); + let tester_address = OWNER(); + let eth_token_dispatcher = dice_game_dispatcher.eth_token_dispatcher(); + cheat_caller_address( + eth_token_dispatcher.contract_address, tester_address, CheatSpan::TargetCalls(1) + ); + eth_token_dispatcher.approve(rigged_roll_contract_address, ROLL_DICE_AMOUNT); + + cheat_caller_address(rigged_roll_contract_address, tester_address, CheatSpan::TargetCalls(1)); + + let mut spy = spy_events(); + + rigged_roll_dispatcher.rigged_roll(ROLL_DICE_AMOUNT); + + let dice_game_contract = dice_game_dispatcher.contract_address; + let events = spy.get_events().emitted_by(dice_game_contract); + + assert_eq!(events.events.len(), 0, "There should be no events emitted by DiceGame contract"); +} + +#[test] +fn test_withdraw() { + let rigged_roll_contract_address = deploy_rigged_roll_contract(); + let rigged_roll_dispatcher = IRiggedRollDispatcher { + contract_address: rigged_roll_contract_address + }; + + let get_roll_less_than_5 = true; + let expected_roll = get_roll(get_roll_less_than_5, rigged_roll_dispatcher); + println!("-- Expect roll to be less than or equal to 5. DiceGame Roll:: {:?}", expected_roll); + let tester_address = OWNER(); + let eth_token_dispatcher = rigged_roll_dispatcher.dice_game_dispatcher().eth_token_dispatcher(); + cheat_caller_address( + eth_token_dispatcher.contract_address, tester_address, CheatSpan::TargetCalls(1) + ); + eth_token_dispatcher.approve(rigged_roll_contract_address, ROLL_DICE_AMOUNT); + + cheat_caller_address(rigged_roll_contract_address, tester_address, CheatSpan::TargetCalls(1)); + + rigged_roll_dispatcher.rigged_roll(ROLL_DICE_AMOUNT); + + let tester_address_prev_balance = eth_token_dispatcher.balanceOf(tester_address); + cheat_caller_address(rigged_roll_contract_address, tester_address, CheatSpan::TargetCalls(1)); + let rigged_roll_balance = eth_token_dispatcher.balanceOf(rigged_roll_contract_address); + + cheat_caller_address(rigged_roll_contract_address, tester_address, CheatSpan::TargetCalls(1)); + rigged_roll_dispatcher.withdraw(tester_address, rigged_roll_balance); + let tester_address_new_balance = eth_token_dispatcher.balanceOf(tester_address); + assert_eq!( + tester_address_new_balance, + tester_address_prev_balance + rigged_roll_balance, + "Tester address should have the balance of the rigged_roll_contract_address" + ); +} diff --git a/packages/snfoundry/scripts-ts/deploy.ts b/packages/snfoundry/scripts-ts/deploy.ts index 101aa7cf..88fb370e 100644 --- a/packages/snfoundry/scripts-ts/deploy.ts +++ b/packages/snfoundry/scripts-ts/deploy.ts @@ -1,3 +1,4 @@ +import { Abi, Contract } from "starknet"; import { deployContract, executeDeployCalls, @@ -6,45 +7,31 @@ import { } from "./deploy-contract"; import { green } from "./helpers/colorize-log"; -/** - * Deploy a contract using the specified parameters. - * - * @example (deploy contract with contructorArgs) - * const deployScript = async (): Promise => { - * await deployContract( - * { - * contract: "YourContract", - * contractName: "YourContractExportName", - * constructorArgs: { - * owner: deployer.address, - * }, - * options: { - * maxFee: BigInt(1000000000000) - * } - * } - * ); - * }; - * - * @example (deploy contract without contructorArgs) - * const deployScript = async (): Promise => { - * await deployContract( - * { - * contract: "YourContract", - * contractName: "YourContractExportName", - * options: { - * maxFee: BigInt(1000000000000) - * } - * } - * ); - * }; - * - * - * @returns {Promise} - */ +import preDeployedContracts from "../../nextjs/contracts/predeployedContracts"; + const deployScript = async (): Promise => { + const { address: diceGameAddr } = await deployContract({ + contract: "DiceGame", + constructorArgs: { + eth_token_address: + "0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7", + }, + }); + const ethAbi = preDeployedContracts.devnet.Eth.abi as Abi; + const ethAddress = preDeployedContracts.devnet.Eth.address as `0x${string}`; + + const ethContract = new Contract(ethAbi, ethAddress, deployer); + + const tx = await ethContract.invoke("transfer", [ + diceGameAddr, + 1000000000000000000n, + ]); + // const receipt = await provider.waitForTransaction(tx.transaction_hash); + await deployContract({ - contract: "YourContract", + contract: "RiggedRoll", constructorArgs: { + dice_game_address: diceGameAddr, owner: deployer.address, }, });