element in src/app.html
9 | target: '#svelte'
10 | }
11 | };
12 |
13 | export default config;
14 |
--------------------------------------------------------------------------------
/dynamic-nft/README.md:
--------------------------------------------------------------------------------
1 | # Dynamic NFTs
2 | This repo will support the [Creating Dynamic NFTs](https://www.youtube.com/watch?v=E7Rm1LUKhj4) tutorial.
3 |
4 | ## How to Use The Repo
5 |
6 | This repo consists of two files:
7 | - **1_starter.sol**: This is the starter file with the basic OpenZeppelin contract plus helper functions
8 | - **2_complete.sol**: the final contract for use with keepers
9 |
10 | Both versions of the contracts can be deployed as is via a tool like [Remix](https://remix.ethereum.org/).
11 |
--------------------------------------------------------------------------------
/functions-examples/README.md:
--------------------------------------------------------------------------------
1 | # Chainlink Functions Examples
2 |
3 | This project is an example of a command-line interface (CLI) that uses the [functions-toolkit](https://github.com/smartcontractkit/functions-toolkit) to interact with Chainlink Functions.
4 |
5 | ## Installation
6 |
7 | To set up the project, follow these steps:
8 |
9 | 1. Clone the repository.
10 | ```bash
11 | git clone https://github.com/smartcontractkit/functions-example
12 | ```
13 | 1. Clone the repository.
14 | ```bash
15 | cd functions-example
16 | ```
17 | 1. Install the required dependencies.
18 |
19 | ```bash
20 | npm install
21 | ```
22 |
23 | 1. We use [@chainlink/env-enc](https://www.npmjs.com/package/@chainlink/env-enc) package to encrypt environment variables at rest. Set the password to encrypt and decrypt the environment varilable file `.env.enc`:
24 |
25 | ```bash
26 | npx env-enc set-pw
27 | ```
28 |
29 | 1. Set the following variables:
30 |
31 | - PRIVATE_KEY
32 | - ETHEREUM_SEPOLIA_RPC_URL
33 |
--------------------------------------------------------------------------------
/functions-examples/examples/1-simple-computation/source.js:
--------------------------------------------------------------------------------
1 | // calculate geometric mean off-chain by a DON then return the result
2 | // valures provided in args array
3 |
4 | console.log(`calculate geometric mean of ${args}`);
5 |
6 | // make sure arguments are provided
7 | if (!args || args.length === 0) throw new Error("input not provided");
8 |
9 | const product = args.reduce((accumulator, currentValue) => {
10 | const numValue = parseInt(currentValue);
11 | if (isNaN(numValue)) throw Error(`${currentValue} is not a number`);
12 | return accumulator * numValue;
13 | }, 1); // calculate the product of numbers provided in args array
14 |
15 | const geometricMean = Math.pow(product, 1 / args.length); // geometric mean = length-root of (product)
16 | console.log(`geometric mean is: ${geometricMean.toFixed(2)}`);
17 |
18 | // Decimals are not handled in Solidity so multiply by 100 (for 2 decimals) and round to the nearest integer
19 | // Functions.encodeUint256: Return a buffer from uint256
20 | return Functions.encodeUint256(Math.round(geometricMean * 100));
21 |
--------------------------------------------------------------------------------
/functions-examples/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "functions-examples",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "@chainlink/env-enc": "^1.0.5",
13 | "@chainlink/functions-toolkit": "^0.2.7",
14 | "ethers": "^5.7.2"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/lottery/.env.example:
--------------------------------------------------------------------------------
1 | KOVAN_RPC_URL='https://kovan.infura.io/v3/1234567890'
2 | RINKEBY_RPC_URL='https://alchemy.infura.io/v3/1234567890'
3 | POLYGON_MAINNET_RPC_URL='https://rpc-mainnet.maticvigil.com'
4 | PRIVATE_KEY='abcdefg'
5 | ALCHEMY_MAINNET_RPC_URL="https://eth-mainnet.alchemyapi.io/v2/your-api-key"
6 | REPORT_GAS=true
7 | COINMARKETCAP_API_KEY="YOUR_KEY"
8 | AUTO_FUND=true
9 |
--------------------------------------------------------------------------------
/lottery/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/lottery/.npmignore:
--------------------------------------------------------------------------------
1 | hardhat.config.js
2 | scripts
3 | test
4 |
--------------------------------------------------------------------------------
/lottery/.prettierignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | artifacts
3 | cache
4 | coverage*
5 | gasReporterOutput.json
6 | package.json
7 | img
8 | .env
9 | .*
10 | README.md
11 | coverage.json
12 | deployments
--------------------------------------------------------------------------------
/lottery/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "tabWidth": 4,
3 | "useTabs": false,
4 | "semi": false,
5 | "singleQuote": false,
6 | "printWidth": 100
7 | }
8 |
--------------------------------------------------------------------------------
/lottery/.solhint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "solhint:recommended",
3 | "rules": {
4 | "compiler-version": ["error", "^0.8.0"],
5 | "func-visibility": ["warn", { "ignoreConstructors": true }]
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/lottery/.solhintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | contracts/test
--------------------------------------------------------------------------------
/lottery/contracts/test/VRFCoordinatorV2Mock.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol";
--------------------------------------------------------------------------------
/lottery/deploy/00-deploy-mocks.ts:
--------------------------------------------------------------------------------
1 | import { DeployFunction } from "hardhat-deploy/types"
2 | import { HardhatRuntimeEnvironment } from "hardhat/types"
3 |
4 | const BASE_FEE = "250000000000000000" // 0.25 is this the premium in LINK?
5 | const GAS_PRICE_LINK = 1e9 // link per gas, is this the gas lane? // 0.000000001 LINK per gas
6 |
7 | const deployMocks: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
8 | const { deployments, getNamedAccounts, network } = hre
9 | const { deploy, log } = deployments
10 | const { deployer } = await getNamedAccounts()
11 | const chainId = network.config.chainId
12 | // If we are on a local development network, we need to deploy mocks!
13 | if (chainId == 31337) {
14 | log("Local network detected! Deploying mocks...")
15 | await deploy("VRFCoordinatorV2Mock", {
16 | from: deployer,
17 | log: true,
18 | args: [BASE_FEE, GAS_PRICE_LINK],
19 | })
20 |
21 | log("Mocks Deployed!")
22 | log("----------------------------------")
23 |
24 | log("You are deploying to a local network, you'll need a local network running to interact")
25 | log(
26 | "Please run `yarn hardhat console --network localhost` to interact with the deployed smart contracts!"
27 | )
28 | log("----------------------------------")
29 | }
30 | }
31 | export default deployMocks
32 | deployMocks.tags = ["all", "mocks"]
33 |
--------------------------------------------------------------------------------
/lottery/deploy/02-update-front-end.ts:
--------------------------------------------------------------------------------
1 | import { frontEndContractsFile } from "../helper-hardhat-config"
2 | import fs from "fs"
3 | import { DeployFunction } from "hardhat-deploy/types"
4 | import { HardhatRuntimeEnvironment } from "hardhat/types"
5 |
6 | const updateUI: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
7 | const { network, ethers } = hre
8 | const chainId = "31337"
9 |
10 | if (process.env.UPDATE_FRONT_END) {
11 | console.log("Writing to front end...")
12 | const fundMe = await ethers.getContract("Raffle")
13 | const contractAddresses = JSON.parse(fs.readFileSync(frontEndContractsFile, "utf8"))
14 | if (chainId in contractAddresses) {
15 | if (!contractAddresses[network.config.chainId!].includes(fundMe.address)) {
16 | contractAddresses[network.config.chainId!].push(fundMe.address)
17 | }
18 | } else {
19 | contractAddresses[network.config.chainId!] = [fundMe.address]
20 | }
21 | fs.writeFileSync(frontEndContractsFile, JSON.stringify(contractAddresses))
22 | console.log("Front end written!")
23 | }
24 | }
25 | export default updateUI
26 | updateUI.tags = ["all", "frontend"]
27 |
--------------------------------------------------------------------------------
/lottery/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "hardhat-smartcontract-lottery-fcc",
3 | "version": "1.0.0",
4 | "description": "",
5 | "scripts": {
6 | "test": "yarn hardhat test",
7 | "test-staging": "yarn hardhat test --network rinkeby",
8 | "lint": "yarn solhint 'contracts/*.sol'",
9 | "lint:fix": "yarn solhint 'contracts/**/*.sol' --fix",
10 | "format": "yarn prettier --write .",
11 | "coverage": "yarn hardhat coverage",
12 | "typechain": "yarn hardhat typechain"
13 | },
14 | "license": "MIT",
15 | "devDependencies": {
16 | "@chainlink/contracts": "^0.4.0",
17 | "@nomiclabs/hardhat-ethers": "npm:hardhat-deploy-ethers@^0.3.0-beta.13",
18 | "@nomiclabs/hardhat-etherscan": "^3.0.0",
19 | "@nomiclabs/hardhat-waffle": "^2.0.1",
20 | "@openzeppelin/contracts": "^4.5.0",
21 | "@types/chai": "^4.3.0",
22 | "@types/mocha": "^9.1.0",
23 | "@types/node": "^17.0.13",
24 | "babel-eslint": "^10.1.0",
25 | "chai": "^4.3.4",
26 | "dotenv": "^14.2.0",
27 | "ethereum-waffle": "^3.4.0",
28 | "ethers": "^5.5.1",
29 | "hardhat": "^2.6.7",
30 | "hardhat-contract-sizer": "^2.4.0",
31 | "hardhat-deploy": "^0.9.29",
32 | "hardhat-deploy-ethers": "^0.3.0-beta.13",
33 | "hardhat-gas-reporter": "^1.0.7",
34 | "prettier": "^2.4.1",
35 | "prettier-plugin-solidity": "^1.0.0-beta.19",
36 | "solhint": "^3.3.6",
37 | "solidity-coverage": "^0.7.13",
38 | "ts-node": "^10.4.0",
39 | "typechain": "^8.0.0",
40 | "typescript": "^4.5.5",
41 | "@typechain/ethers-v5": "^10.0.0",
42 | "@typechain/hardhat": "^6.0.0"
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/lottery/scripts/charity-raffle-scripts/enterCharityRaffle.ts:
--------------------------------------------------------------------------------
1 | // @ts-ignore
2 | import { ethers } from "hardhat"
3 | import { CharityRaffle } from "../../typechain-types"
4 |
5 | async function enterCharityRaffle(): Promise
{
6 | const charityRaffle: CharityRaffle = await ethers.getContract("CharityRaffle")
7 | const entranceFee: number = (await charityRaffle.getEntranceFee()).toNumber()
8 | await charityRaffle.enterRaffle(0, { value: entranceFee + 1 })
9 | console.log("Entered Charity Raffle!")
10 | }
11 |
12 | enterCharityRaffle()
13 | .then(() => process.exit(0))
14 | .catch((error) => {
15 | console.error(error)
16 | process.exit(1)
17 | })
18 |
--------------------------------------------------------------------------------
/lottery/scripts/enterRaffle.ts:
--------------------------------------------------------------------------------
1 | // @ts-ignore
2 | import { ethers } from "hardhat"
3 | import { Raffle } from '../typechain-types'
4 |
5 | async function enterRaffle():Promise {
6 | const raffle: Raffle = await ethers.getContract("Raffle")
7 | const entranceFee: number = (await raffle.getEntranceFee()).toNumber()
8 | await raffle.enterRaffle({ value: entranceFee + 1 })
9 | console.log("Entered!")
10 | }
11 |
12 | enterRaffle()
13 | .then(() => process.exit(0))
14 | .catch((error) => {
15 | console.error(error)
16 | process.exit(1)
17 | })
18 |
--------------------------------------------------------------------------------
/lottery/scripts/mockOffchain.ts:
--------------------------------------------------------------------------------
1 | // @ts-ignore
2 | import { ethers, network } from "hardhat"
3 | import { Raffle } from "../typechain-types"
4 | import { BigNumber } from "ethers"
5 |
6 | async function mockKeepers() {
7 | const raffle: Raffle = await ethers.getContract("Raffle")
8 | const checkData = ethers.utils.keccak256(ethers.utils.toUtf8Bytes(""))
9 | const { upkeepNeeded } = await raffle.callStatic.checkUpkeep(checkData)
10 | if (upkeepNeeded) {
11 | const tx = await raffle.performUpkeep(checkData)
12 | const txReceipt = await tx.wait(1)
13 | const requestId: BigNumber = txReceipt.events[1].args.requestId
14 | console.log(`Performed upkeep with RequestId: ${requestId}`)
15 | if (network.config.chainId == 31337) {
16 | await mockVrf(requestId, raffle)
17 | }
18 | } else {
19 | console.log("No upkeep needed!")
20 | }
21 | }
22 |
23 | async function mockVrf(requestId: BigNumber, raffle: Raffle) {
24 | console.log("We on a local network? Ok let's pretend...")
25 | const vrfCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock")
26 | await vrfCoordinatorV2Mock.fulfillRandomWords(requestId, raffle.address)
27 | console.log("Responded!")
28 | const recentWinner = await raffle.getRecentWinner()
29 | console.log(`The winner is: ${recentWinner}`)
30 | }
31 |
32 | mockKeepers()
33 | .then(() => process.exit(0))
34 | .catch((error) => {
35 | console.error(error)
36 | process.exit(1)
37 | })
38 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as src from "./src";
5 | export type { src };
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as src from "./src";
5 | export type { src };
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as v08 from "./v0.8";
5 | export type { v08 };
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as v08 from "./v0.8";
5 | export type { v08 };
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/v0.8/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as interfaces from "./interfaces";
5 | export type { interfaces };
6 | import type * as mocks from "./mocks";
7 | export type { mocks };
8 | export type { VRFConsumerBaseV2 } from "./VRFConsumerBaseV2";
9 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/v0.8/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as interfaces from "./interfaces";
5 | export type { interfaces };
6 | import type * as mocks from "./mocks";
7 | export type { mocks };
8 | export type { VRFConsumerBaseV2 } from "./VRFConsumerBaseV2";
9 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/v0.8/interfaces/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export type { KeeperCompatibleInterface } from "./KeeperCompatibleInterface";
5 | export type { LinkTokenInterface } from "./LinkTokenInterface";
6 | export type { VRFCoordinatorV2Interface } from "./VRFCoordinatorV2Interface";
7 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/v0.8/interfaces/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export type { KeeperCompatibleInterface } from "./KeeperCompatibleInterface";
5 | export type { LinkTokenInterface } from "./LinkTokenInterface";
6 | export type { VRFCoordinatorV2Interface } from "./VRFCoordinatorV2Interface";
7 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/v0.8/mocks/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export type { VRFCoordinatorV2Mock } from "./VRFCoordinatorV2Mock";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/contracts/src/v0.8/mocks/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export type { VRFCoordinatorV2Mock } from "./VRFCoordinatorV2Mock";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as contracts from "./contracts";
5 | export type { contracts };
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/@chainlink/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type * as contracts from "./contracts";
5 | export type { contracts };
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/common 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type { Listener } from "@ethersproject/providers";
5 | import type { Event, EventFilter } from "ethers";
6 |
7 | export interface TypedEvent<
8 | TArgsArray extends Array = any,
9 | TArgsObject = any
10 | > extends Event {
11 | args: TArgsArray & TArgsObject;
12 | }
13 |
14 | export interface TypedEventFilter<_TEvent extends TypedEvent>
15 | extends EventFilter {}
16 |
17 | export interface TypedListener {
18 | (...listenerArg: [...__TypechainArgsArray, TEvent]): void;
19 | }
20 |
21 | type __TypechainArgsArray = T extends TypedEvent ? U : never;
22 |
23 | export interface OnEvent {
24 | (
25 | eventFilter: TypedEventFilter,
26 | listener: TypedListener
27 | ): TRes;
28 | (eventName: string, listener: Listener): TRes;
29 | }
30 |
31 | export type MinEthersFactory = {
32 | deploy(...a: ARGS[]): Promise;
33 | };
34 |
35 | export type GetContractTypeFromFactory = F extends MinEthersFactory<
36 | infer C,
37 | any
38 | >
39 | ? C
40 | : never;
41 |
42 | export type GetARGsTypeFromFactory = F extends MinEthersFactory
43 | ? Parameters
44 | : never;
45 |
--------------------------------------------------------------------------------
/lottery/typechain-types/common.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | import type { Listener } from "@ethersproject/providers";
5 | import type { Event, EventFilter } from "ethers";
6 |
7 | export interface TypedEvent<
8 | TArgsArray extends Array = any,
9 | TArgsObject = any
10 | > extends Event {
11 | args: TArgsArray & TArgsObject;
12 | }
13 |
14 | export interface TypedEventFilter<_TEvent extends TypedEvent>
15 | extends EventFilter {}
16 |
17 | export interface TypedListener {
18 | (...listenerArg: [...__TypechainArgsArray, TEvent]): void;
19 | }
20 |
21 | type __TypechainArgsArray = T extends TypedEvent ? U : never;
22 |
23 | export interface OnEvent {
24 | (
25 | eventFilter: TypedEventFilter,
26 | listener: TypedListener
27 | ): TRes;
28 | (eventName: string, listener: Listener): TRes;
29 | }
30 |
31 | export type MinEthersFactory = {
32 | deploy(...a: ARGS[]): Promise;
33 | };
34 |
35 | export type GetContractTypeFromFactory = F extends MinEthersFactory<
36 | infer C,
37 | any
38 | >
39 | ? C
40 | : never;
41 |
42 | export type GetARGsTypeFromFactory = F extends MinEthersFactory
43 | ? Parameters
44 | : never;
45 |
--------------------------------------------------------------------------------
/lottery/typechain-types/contracts/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export type { CharityRaffle } from "./CharityRaffle";
5 | export type { Raffle } from "./Raffle";
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/contracts/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export type { CharityRaffle } from "./CharityRaffle";
5 | export type { Raffle } from "./Raffle";
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as src from "./src";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as src from "./src";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as v08 from "./v0.8";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as v08 from "./v0.8";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/v0.8/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as interfaces from "./interfaces";
5 | export * as mocks from "./mocks";
6 | export { VRFConsumerBaseV2__factory } from "./VRFConsumerBaseV2__factory";
7 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/v0.8/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as interfaces from "./interfaces";
5 | export * as mocks from "./mocks";
6 | export { VRFConsumerBaseV2__factory } from "./VRFConsumerBaseV2__factory";
7 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/v0.8/interfaces/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export { KeeperCompatibleInterface__factory } from "./KeeperCompatibleInterface__factory";
5 | export { LinkTokenInterface__factory } from "./LinkTokenInterface__factory";
6 | export { VRFCoordinatorV2Interface__factory } from "./VRFCoordinatorV2Interface__factory";
7 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/v0.8/interfaces/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export { KeeperCompatibleInterface__factory } from "./KeeperCompatibleInterface__factory";
5 | export { LinkTokenInterface__factory } from "./LinkTokenInterface__factory";
6 | export { VRFCoordinatorV2Interface__factory } from "./VRFCoordinatorV2Interface__factory";
7 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/v0.8/mocks/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export { VRFCoordinatorV2Mock__factory } from "./VRFCoordinatorV2Mock__factory";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/contracts/src/v0.8/mocks/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export { VRFCoordinatorV2Mock__factory } from "./VRFCoordinatorV2Mock__factory";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as contracts from "./contracts";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/@chainlink/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as contracts from "./contracts";
5 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/contracts/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export { CharityRaffle__factory } from "./CharityRaffle__factory";
5 | export { Raffle__factory } from "./Raffle__factory";
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/contracts/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export { CharityRaffle__factory } from "./CharityRaffle__factory";
5 | export { Raffle__factory } from "./Raffle__factory";
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/index 2.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as chainlink from "./@chainlink";
5 | export * as contracts from "./contracts";
6 |
--------------------------------------------------------------------------------
/lottery/typechain-types/factories/index.ts:
--------------------------------------------------------------------------------
1 | /* Autogenerated file. Do not edit manually. */
2 | /* tslint:disable */
3 | /* eslint-disable */
4 | export * as chainlink from "./@chainlink";
5 | export * as contracts from "./contracts";
6 |
--------------------------------------------------------------------------------
/lottery/utils/verify.ts:
--------------------------------------------------------------------------------
1 | import { run } from "hardhat"
2 |
3 | const verify = async (contractAddress: string, args: any[]) => {
4 | console.log("Verifying contract...")
5 | try {
6 | await run("verify:verify", {
7 | address: contractAddress,
8 | constructorArguments: args,
9 | })
10 | } catch (e: any) {
11 | if (e.message.toLowerCase().includes("already verified")) {
12 | console.log("Already verified!")
13 | } else {
14 | console.log(e)
15 | }
16 | }
17 | }
18 |
19 | export default verify
20 |
--------------------------------------------------------------------------------
/my-crypto-coin/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .vscode
--------------------------------------------------------------------------------
/my-crypto-coin/cli/mcc/balances.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/spf13/cobra"
5 | "my-crypto-coin/ledger"
6 | "fmt"
7 | "os"
8 | )
9 |
10 | func balancesCmd() *cobra.Command {
11 | var balancesCmd = &cobra.Command{
12 | Use: "balances",
13 | Short: "Interact with balances (list...).",
14 | Run: func(cmd *cobra.Command, args []string) {
15 | },
16 | }
17 |
18 | balancesCmd.AddCommand(balancesListCmd)
19 |
20 | return balancesCmd
21 | }
22 |
23 | var balancesListCmd = &cobra.Command{
24 | Use: "list",
25 | Short: "Lists all balances.",
26 | Run: func(cmd *cobra.Command, args []string) {
27 | state, err := ledger.SyncState()
28 | if err != nil {
29 | fmt.Fprintln(os.Stderr, err)
30 | os.Exit(1)
31 | }
32 | defer state.Close()
33 |
34 | fmt.Println("Accounts balances:")
35 | fmt.Println("__________________")
36 | fmt.Println("")
37 | for account, balance := range state.Balances {
38 | fmt.Println(fmt.Sprintf("%s: %d", account, balance))
39 | }
40 | },
41 | }
--------------------------------------------------------------------------------
/my-crypto-coin/cli/mcc/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/spf13/cobra"
5 | "os"
6 | "fmt"
7 | )
8 |
9 | func main() {
10 | var mccCmd = &cobra.Command{
11 | Use: "mcc",
12 | Short: "My Crypto Coin CLI",
13 | Run: func(cmd *cobra.Command, args []string) {
14 | },
15 | }
16 |
17 | mccCmd.AddCommand(versionCmd)
18 | mccCmd.AddCommand(balancesCmd())
19 | mccCmd.AddCommand(txCmd())
20 |
21 | err := mccCmd.Execute()
22 | if err != nil {
23 | fmt.Fprintln(os.Stderr, err)
24 | os.Exit(1)
25 | }
26 | }
--------------------------------------------------------------------------------
/my-crypto-coin/cli/mcc/tx.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/spf13/cobra"
5 | "my-crypto-coin/ledger"
6 | "fmt"
7 | "os"
8 | )
9 |
10 | func txCmd() *cobra.Command {
11 | var txsCmd = &cobra.Command{
12 | Use: "tx",
13 | Short: "Interact with transactions (new...).",
14 | Run: func(cmd *cobra.Command, args []string) {
15 | },
16 | }
17 |
18 | txsCmd.AddCommand(newTxCmd())
19 |
20 | return txsCmd
21 | }
22 |
23 |
24 | func newTxCmd() *cobra.Command {
25 | var cmd = &cobra.Command{
26 | Use: "new",
27 | Short: "Adds new TX to the ledger.",
28 | Run: func(cmd *cobra.Command, args []string) {
29 | from, _ := cmd.Flags().GetString("from")
30 | to, _ := cmd.Flags().GetString("to")
31 | value, _ := cmd.Flags().GetUint("value")
32 |
33 | tx := ledger.NewTx(ledger.NewAccount(from), ledger.NewAccount(to), value)
34 |
35 | state, err := ledger.SyncState()
36 | if err != nil {
37 | fmt.Fprintln(os.Stderr, err)
38 | os.Exit(1)
39 | }
40 | defer state.Close()
41 |
42 | err = state.WriteToLedger(tx)
43 | if err != nil {
44 | fmt.Fprintln(os.Stderr, err)
45 | os.Exit(1)
46 | }
47 |
48 | fmt.Println("TX successfully added to the ledger.")
49 | },
50 | }
51 |
52 | cmd.Flags().String("from", "", "From what account to send coins")
53 | cmd.MarkFlagRequired("from")
54 |
55 | cmd.Flags().String("to", "", "To what account to send coins")
56 | cmd.MarkFlagRequired("to")
57 |
58 | cmd.Flags().Uint("value", 0, "How many coins to send")
59 | cmd.MarkFlagRequired("value")
60 |
61 | return cmd
62 | }
--------------------------------------------------------------------------------
/my-crypto-coin/cli/mcc/version.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "github.com/spf13/cobra"
6 | )
7 |
8 | const Major = "0"
9 | const Minor = "1"
10 | const Fix = "0"
11 | const Verbal = "Genesis"
12 |
13 | var versionCmd = &cobra.Command{
14 | Use: "version",
15 | Short: "Describes version.",
16 | Run: func(cmd *cobra.Command, args []string) {
17 | fmt.Println(fmt.Sprintf("Version: %s.%s.%s-beta %s", Major, Minor, Fix, Verbal))
18 | },
19 | }
--------------------------------------------------------------------------------
/my-crypto-coin/go.mod:
--------------------------------------------------------------------------------
1 | module my-crypto-coin
2 |
3 | go 1.16
4 |
5 | require github.com/spf13/cobra v1.4.0 // indirect
6 |
--------------------------------------------------------------------------------
/my-crypto-coin/go.sum:
--------------------------------------------------------------------------------
1 | github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
2 | github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
3 | github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
4 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
5 | github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q=
6 | github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
7 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
8 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
9 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
10 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
11 |
--------------------------------------------------------------------------------
/my-crypto-coin/ledger/genesis.go:
--------------------------------------------------------------------------------
1 | package ledger
2 |
3 | import (
4 | "io/ioutil"
5 | "encoding/json"
6 | )
7 |
8 | type Genesis struct {
9 | Balances map[Account]uint `json:"balances"`
10 | }
11 |
12 | func loadGenesis(path string) (Genesis, error) {
13 | genesisFileContent, err := ioutil.ReadFile(path)
14 | if err != nil {
15 | return Genesis{}, err
16 | }
17 |
18 | var loadedGenesis Genesis
19 |
20 | err = json.Unmarshal(genesisFileContent, &loadedGenesis)
21 | if err != nil {
22 | return Genesis{}, err
23 | }
24 |
25 | return loadedGenesis, nil
26 | }
--------------------------------------------------------------------------------
/my-crypto-coin/ledger/genesis.json:
--------------------------------------------------------------------------------
1 | {
2 | "genesis_time": "2022-04-12T00:00:00.000000000Z",
3 | "chain_id": "our-blockchain",
4 | "balances": {
5 | "alice": 1000000
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/my-crypto-coin/ledger/ledger.db:
--------------------------------------------------------------------------------
1 | {"from":"alice","to":"bob","value":10}
2 | {"from":"alice","to":"alice","value":3}
3 | {"from":"alice","to":"alice","value":500}
4 | {"from":"alice","to":"bob","value":100}
5 | {"from":"bob","to":"alice","value":5}
6 | {"from":"bob","to":"carol","value":10}
7 | {"from":"alice","to":"carol","value":10}
8 |
--------------------------------------------------------------------------------
/my-crypto-coin/ledger/tx.go:
--------------------------------------------------------------------------------
1 | package ledger
2 |
3 | type Account string
4 |
5 | type Tx struct {
6 | From Account `json:"from"`
7 | To Account `json:"to"`
8 | Value uint `json:"value"`
9 | }
10 |
11 | func NewAccount(value string) Account {
12 | return Account(value)
13 | }
14 |
15 | func NewTx(from Account, to Account, value uint) Tx {
16 | return Tx{from, to, value}
17 | }
18 |
--------------------------------------------------------------------------------
/my-crypto-wallet/02_restoreWallet.js:
--------------------------------------------------------------------------------
1 | const { mnemonicToEntropy } = require("ethereum-cryptography/bip39");
2 | const { wordlist } = require("ethereum-cryptography/bip39/wordlists/english");
3 | const { HDKey } = require("ethereum-cryptography/hdkey");
4 | const { getPublicKey } = require("ethereum-cryptography/secp256k1");
5 | const { keccak256 } = require("ethereum-cryptography/keccak");
6 | const { bytesToHex } = require("ethereum-cryptography/utils");
7 | const { writeFileSync } = require("fs");
8 |
9 | async function main(_mnemonic) {
10 | const entropy = mnemonicToEntropy(_mnemonic, wordlist);
11 | const hdRootKey = HDKey.fromMasterSeed(entropy);
12 | const privateKey = hdRootKey.deriveChild(0).privateKey;
13 | const publicKey = getPublicKey(privateKey);
14 | const address = keccak256(publicKey).slice(-20);
15 | console.log(`Account One Wallet Address: 0x${bytesToHex(address)}`);
16 |
17 | const accountOne = {
18 | privateKey: privateKey,
19 | publicKey: publicKey,
20 | address: address,
21 | };
22 | const accountOneData = JSON.stringify(accountOne);
23 | writeFileSync("account 1.json", accountOneData);
24 | }
25 |
26 | main(process.argv[2])
27 | .then(() => process.exit(0))
28 | .catch((error) => {
29 | console.error(error);
30 | process.exit(1);
31 | });
32 |
--------------------------------------------------------------------------------
/my-crypto-wallet/03_send.js:
--------------------------------------------------------------------------------
1 | const { getDefaultProvider, Wallet, utils } = require("ethers");
2 | const { readFileSync } = require("fs");
3 |
4 | async function main(_receiverAddress, _ethAmount) {
5 | const network = "goerli";
6 | const provider = getDefaultProvider(network);
7 |
8 | const accountRawData = readFileSync("account 1.json", "utf8");
9 | const accountData = JSON.parse(accountRawData);
10 |
11 | const privateKey = Object.values(accountData.privateKey);
12 |
13 | const signer = new Wallet(privateKey, provider);
14 |
15 | const transaction = await signer.sendTransaction({
16 | to: _receiverAddress,
17 | value: utils.parseEther(_ethAmount),
18 | });
19 |
20 | console.log(transaction);
21 | }
22 |
23 | main(process.argv[2], process.argv[3])
24 | .then(() => process.exit(0))
25 | .catch((error) => {
26 | console.error(error);
27 | process.exit(1);
28 | });
29 |
--------------------------------------------------------------------------------
/my-crypto-wallet/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "my-crypto-wallet",
3 | "version": "1.0.0",
4 | "main": "index.js",
5 | "license": "MIT",
6 | "dependencies": {
7 | "ethereum-cryptography": "^1.0.3",
8 | "ethers": "^5.6.8"
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/pricefeed-golang/.env.example:
--------------------------------------------------------------------------------
1 | RPC_URL=REPLACE_BY_YOUR_RPC_URL
2 | DEFAULT_FEED_ADDR=REPLACE_BY_PRICE_FEED_PROXY_ADDR
--------------------------------------------------------------------------------
/pricefeed-golang/.gitignore:
--------------------------------------------------------------------------------
1 | .env
--------------------------------------------------------------------------------
/pricefeed-golang/aggregatorv3/AggregatorV3Interface.abi:
--------------------------------------------------------------------------------
1 | [{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint80","name":"_roundId","type":"uint80"}],"name":"getRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]
--------------------------------------------------------------------------------
/pricefeed-golang/aggregatorv3/AggregatorV3Interface.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | interface AggregatorV3Interface {
5 | function decimals() external view returns (uint8);
6 |
7 | function description() external view returns (string memory);
8 |
9 | function version() external view returns (uint256);
10 |
11 | // getRoundData and latestRoundData should both raise "No data present"
12 | // if they do not have data to report, instead of returning unset values
13 | // which could be misinterpreted as actual reported values.
14 | function getRoundData(uint80 _roundId)
15 | external
16 | view
17 | returns (
18 | uint80 roundId,
19 | int256 answer,
20 | uint256 startedAt,
21 | uint256 updatedAt,
22 | uint80 answeredInRound
23 | );
24 |
25 | function latestRoundData()
26 | external
27 | view
28 | returns (
29 | uint80 roundId,
30 | int256 answer,
31 | uint256 startedAt,
32 | uint256 updatedAt,
33 | uint80 answeredInRound
34 | );
35 | }
36 |
--------------------------------------------------------------------------------
/pricefeed-golang/go.mod:
--------------------------------------------------------------------------------
1 | module chainlink-price-feed
2 |
3 | go 1.18
4 |
5 | require (
6 | github.com/ethereum/go-ethereum v1.10.17
7 | github.com/joho/godotenv v1.4.0
8 | )
9 |
10 | require (
11 | github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 // indirect
12 | github.com/btcsuite/btcd/btcec/v2 v2.1.2 // indirect
13 | github.com/deckarep/golang-set v1.8.0 // indirect
14 | github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
15 | github.com/go-ole/go-ole v1.2.1 // indirect
16 | github.com/go-stack/stack v1.8.0 // indirect
17 | github.com/google/uuid v1.2.0 // indirect
18 | github.com/gorilla/websocket v1.4.2 // indirect
19 | github.com/rjeczalik/notify v0.9.1 // indirect
20 | github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
21 | github.com/tklauser/go-sysconf v0.3.5 // indirect
22 | github.com/tklauser/numcpus v0.2.2 // indirect
23 | golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect
24 | golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912 // indirect
25 | gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
26 | )
27 |
--------------------------------------------------------------------------------
/quiz-game/.gitignore:
--------------------------------------------------------------------------------
1 | cache/
2 | out/
3 | .DS_Store
4 | node_modules
5 | /build
6 | /.svelte-kit
7 | /package
8 | .env
9 | .env.*
10 | !.env.example
11 |
--------------------------------------------------------------------------------
/quiz-game/foundry/.gitignore:
--------------------------------------------------------------------------------
1 | cache/
2 | out/
3 |
--------------------------------------------------------------------------------
/quiz-game/foundry/deploy.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Read the RPC URL
4 | echo Enter Your RPC URL:
5 | echo Example: "https://eth-goerli.alchemyapi.io/v2//XXXXXXXXXX"
6 | read -s rpc
7 |
8 | # Read the contract name
9 | echo Which contract do you want to deploy \(eg Greeter\)?
10 | read contract
11 |
12 | forge create ./src/${contract}.sol:${contract} -i --rpc-url $rpc
--------------------------------------------------------------------------------
/quiz-game/foundry/foundry.toml:
--------------------------------------------------------------------------------
1 | [profile.default]
2 | src = 'src'
3 | out = 'out'
4 | libs = ['lib']
5 |
6 | # See more config options https://github.com/gakonst/foundry/tree/master/config
--------------------------------------------------------------------------------
/quiz-game/foundry/src/QuizFactory.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: UNLICENSED
2 | pragma solidity ^0.8.13;
3 |
4 | import "./QuizGame.sol";
5 |
6 | contract QuizFactory {
7 | QuizGame[] public quizzes;
8 | event QuizCreated(QuizGame indexed quiz);
9 |
10 | constructor() {}
11 |
12 | function createQuiz(string memory question, bytes32 answer) public {
13 | QuizGame quiz = new QuizGame(question, answer);
14 | quizzes.push(quiz);
15 | emit QuizCreated(quiz);
16 | }
17 |
18 | function getQuizzes() public view returns (QuizGame[] memory) {
19 | return quizzes;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/quiz-game/foundry/src/QuizGame.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: UNLICENSED
2 | pragma solidity ^0.8.13;
3 |
4 | contract QuizGame {
5 | bytes32 public salt = bytes32("123123123");
6 | bytes32 public hashedAnswer;
7 | string public question;
8 | event QuizFunded(uint256 amount);
9 | event AnswerGuessed();
10 |
11 | constructor(string memory _question, bytes32 _hashedAnswer) {
12 | question = _question;
13 | hashedAnswer = _hashedAnswer;
14 | }
15 |
16 | function guess(string calldata answer) public {
17 | require(keccak256(abi.encodePacked(salt, answer)) == hashedAnswer);
18 | if (address(this).balance > 0) {
19 | emit AnswerGuessed();
20 | (bool sent, bytes memory data) = payable(msg.sender).call{value: address(this).balance}("");
21 | require(sent, "Failed to send");
22 | }
23 | }
24 |
25 | fallback() external payable {
26 | emit QuizFunded(address(this).balance);
27 | }
28 |
29 | receive() external payable {
30 | emit QuizFunded(address(this).balance);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/quiz-game/foundry/src/test/QuizFactory.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: UNLICENSED
2 | pragma solidity ^0.8.13;
3 |
4 | import "ds-test/test.sol";
5 |
6 | import "../QuizFactory.sol";
7 |
8 | contract QuizFactoryTest is DSTest {
9 | QuizFactory public factory;
10 |
11 | function setUp() public {
12 | factory = new QuizFactory();
13 | }
14 |
15 | function testCreateQuiz() public {
16 | string
17 | memory question = "What is the answer to life, the universe, and everything?";
18 | string memory answer = "42";
19 | bytes32 salt = bytes32("123123123");
20 | bytes32 hashedAnswer = keccak256(abi.encodePacked(salt, answer));
21 | factory.createQuiz(question, hashedAnswer);
22 | QuizGame quiz = factory.quizzes(0);
23 | assertEq(
24 | keccak256(abi.encodePacked(quiz.question())),
25 | keccak256(abi.encodePacked(question))
26 | );
27 | }
28 |
29 | function testCountQuizzes() public {
30 | string
31 | memory question = "What is the answer to life, the universe, and everything?";
32 | string memory answer = "42";
33 | bytes32 salt = bytes32("123123123");
34 | bytes32 hashedAnswer = keccak256(abi.encodePacked(salt, answer));
35 | factory.createQuiz(question, hashedAnswer);
36 | factory.createQuiz(question, hashedAnswer);
37 | QuizGame[] memory quizzes = factory.getQuizzes();
38 | assertEq(quizzes.length, 2);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/quiz-game/foundry/src/test/QuizGame.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: UNLICENSED
2 | pragma solidity ^0.8.13;
3 |
4 | import "ds-test/test.sol";
5 |
6 | import "../QuizGame.sol";
7 |
8 | interface CheatCodes {
9 | function deal(address, uint256) external;
10 | }
11 |
12 | contract QuizGameTest is DSTest {
13 | QuizGame public game;
14 | CheatCodes constant cheats = CheatCodes(HEVM_ADDRESS);
15 |
16 | function setUp() public {
17 | // Create a question
18 | string
19 | memory question = "What is the answer to life, the universe, and everything?";
20 | string memory answer = "42";
21 | bytes32 salt = bytes32("123123123");
22 | bytes32 hashedAnswer = keccak256(abi.encodePacked(salt, answer));
23 | emit log_bytes32(hashedAnswer);
24 | game = new QuizGame(question, hashedAnswer);
25 | emit log(game.question());
26 | }
27 |
28 | function testQuizFail() public {
29 | try game.guess("1") {
30 | assertTrue(false);
31 | } catch {
32 | assertTrue(true);
33 | }
34 | }
35 |
36 | function testQuizPass() public {
37 | uint256 beginBalance = address(this).balance;
38 | cheats.deal(address(game), 10000);
39 | game.guess("42");
40 | assertEq(address(this).balance, beginBalance + 10000);
41 | }
42 |
43 | fallback() external payable {}
44 |
45 | receive() external payable {}
46 | }
47 |
--------------------------------------------------------------------------------
/quiz-game/svelte/.eslintignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | /build
4 | /.svelte-kit
5 | /package
6 | .env
7 | .env.*
8 | !.env.example
9 |
10 | # Ignore files for PNPM, NPM and YARN
11 | pnpm-lock.yaml
12 | package-lock.json
13 | yarn.lock
14 |
--------------------------------------------------------------------------------
/quiz-game/svelte/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | extends: ['eslint:recommended', 'prettier'],
4 | plugins: ['svelte3'],
5 | overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
6 | parserOptions: {
7 | sourceType: 'module',
8 | ecmaVersion: 2020
9 | },
10 | env: {
11 | browser: true,
12 | es2017: true,
13 | node: true
14 | }
15 | };
16 |
--------------------------------------------------------------------------------
/quiz-game/svelte/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | /build
4 | /.svelte-kit
5 | /package
6 | .env
7 | .env.*
8 | !.env.example
9 |
--------------------------------------------------------------------------------
/quiz-game/svelte/.npmrc:
--------------------------------------------------------------------------------
1 | engine-strict=true
2 |
--------------------------------------------------------------------------------
/quiz-game/svelte/.prettierignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | /build
4 | /.svelte-kit
5 | /package
6 | .env
7 | .env.*
8 | !.env.example
9 |
10 | # Ignore files for PNPM, NPM and YARN
11 | pnpm-lock.yaml
12 | package-lock.json
13 | yarn.lock
14 |
--------------------------------------------------------------------------------
/quiz-game/svelte/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "useTabs": true,
3 | "singleQuote": true,
4 | "trailingComma": "none",
5 | "printWidth": 100
6 | }
7 |
--------------------------------------------------------------------------------
/quiz-game/svelte/README.md:
--------------------------------------------------------------------------------
1 | # create-svelte
2 |
3 | Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
4 |
5 | ## Creating a project
6 |
7 | If you're seeing this, you've probably already done this step. Congrats!
8 |
9 | ```bash
10 | # create a new project in the current directory
11 | npm init svelte
12 |
13 | # create a new project in my-app
14 | npm init svelte my-app
15 | ```
16 |
17 | ## Developing
18 |
19 | Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
20 |
21 | ```bash
22 | npm run dev
23 |
24 | # or start the server and open the app in a new browser tab
25 | npm run dev -- --open
26 | ```
27 |
28 | ## Building
29 |
30 | To create a production version of your app:
31 |
32 | ```bash
33 | npm run build
34 | ```
35 |
36 | You can preview the production build with `npm run preview`.
37 |
38 | > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
39 |
--------------------------------------------------------------------------------
/quiz-game/svelte/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "svelte",
3 | "version": "0.0.1",
4 | "scripts": {
5 | "dev": "svelte-kit dev",
6 | "build": "svelte-kit build",
7 | "package": "svelte-kit package",
8 | "preview": "svelte-kit preview",
9 | "prepare": "svelte-kit sync",
10 | "lint": "prettier --check --plugin-search-dir=. . && eslint .",
11 | "format": "prettier --write --plugin-search-dir=. ."
12 | },
13 | "devDependencies": {
14 | "@sveltejs/adapter-auto": "next",
15 | "@sveltejs/kit": "next",
16 | "eslint": "^8.12.0",
17 | "eslint-config-prettier": "^8.3.0",
18 | "eslint-plugin-svelte3": "^4.0.0",
19 | "prettier": "^2.5.1",
20 | "prettier-plugin-svelte": "^2.5.0",
21 | "svelte": "^3.44.0"
22 | },
23 | "type": "module",
24 | "dependencies": {
25 | "ethers": "^5.6.8"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/quiz-game/svelte/src/app.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | %sveltekit.head%
8 |
9 |
10 | %sveltekit.body%
11 |
12 |
13 |
--------------------------------------------------------------------------------
/quiz-game/svelte/src/routes/index.svelte:
--------------------------------------------------------------------------------
1 |
14 |
15 | Welcome to My Quiz
16 | {#if !web3Props.account}
17 |
18 | {:else}
19 |
20 |
21 | {/if}
22 |
--------------------------------------------------------------------------------
/quiz-game/svelte/static/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smartcontractkit/smart-contract-examples/32bb95e558bdd6a4ebab4b6c1eadbfc83668c539/quiz-game/svelte/static/favicon.png
--------------------------------------------------------------------------------
/quiz-game/svelte/svelte.config.js:
--------------------------------------------------------------------------------
1 | import adapter from '@sveltejs/adapter-auto';
2 |
3 | /** @type {import('@sveltejs/kit').Config} */
4 | const config = {
5 | kit: {
6 | adapter: adapter()
7 | }
8 | };
9 |
10 | export default config;
11 |
--------------------------------------------------------------------------------
/random-svg-nft/.env.example:
--------------------------------------------------------------------------------
1 | ETHERSCAN_API_KEY=
2 | SEPOLIA_URL=https://eth-rinkeby.alchemyapi.io/v2/
3 | PRIVATE_KEY=
4 | SUBSCRIPTION_ID=
5 |
--------------------------------------------------------------------------------
/random-svg-nft/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | artifacts
3 | cache
4 | coverage
5 |
--------------------------------------------------------------------------------
/random-svg-nft/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | env: {
3 | browser: false,
4 | es2021: true,
5 | mocha: true,
6 | node: true,
7 | },
8 | plugins: ["@typescript-eslint"],
9 | extends: [
10 | "standard",
11 | "plugin:prettier/recommended",
12 | "plugin:node/recommended",
13 | ],
14 | parser: "@typescript-eslint/parser",
15 | parserOptions: {
16 | ecmaVersion: 12,
17 | },
18 | rules: {
19 | "node/no-unsupported-features/es-syntax": [
20 | "error",
21 | { ignores: ["modules"] },
22 | ],
23 | },
24 | };
25 |
--------------------------------------------------------------------------------
/random-svg-nft/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .env
3 | coverage
4 | coverage.json
5 | typechain
6 |
7 | #Hardhat files
8 | cache
9 | artifacts
10 |
11 | yarn.lock
12 | package-lock.json
--------------------------------------------------------------------------------
/random-svg-nft/.npmignore:
--------------------------------------------------------------------------------
1 | hardhat.config.ts
2 | scripts
3 | test
4 |
--------------------------------------------------------------------------------
/random-svg-nft/.prettierignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | artifacts
3 | cache
4 | coverage*
5 | gasReporterOutput.json
6 |
--------------------------------------------------------------------------------
/random-svg-nft/.solhint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "solhint:recommended",
3 | "rules": {
4 | "compiler-version": ["error", "^0.8.0"],
5 | "func-visibility": ["warn", { "ignoreConstructors": true }]
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/random-svg-nft/.solhintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
--------------------------------------------------------------------------------
/random-svg-nft/contracts/test/LinkToken.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.4.24;
3 |
4 | import "@chainlink/contracts/src/v0.4/LinkToken.sol";
5 |
--------------------------------------------------------------------------------
/random-svg-nft/contracts/test/VRFCoordinatorV2Mock.sol:
--------------------------------------------------------------------------------
1 | //SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol";
5 |
--------------------------------------------------------------------------------
/random-svg-nft/demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smartcontractkit/smart-contract-examples/32bb95e558bdd6a4ebab4b6c1eadbfc83668c539/random-svg-nft/demo.png
--------------------------------------------------------------------------------
/random-svg-nft/hardhat.config.ts:
--------------------------------------------------------------------------------
1 | import * as dotenv from "dotenv";
2 |
3 | import { HardhatUserConfig } from "hardhat/config";
4 | import "@nomiclabs/hardhat-etherscan";
5 | import "@nomiclabs/hardhat-waffle";
6 | import "@typechain/hardhat";
7 | import "hardhat-gas-reporter";
8 | import "solidity-coverage";
9 |
10 | dotenv.config();
11 |
12 | const config: HardhatUserConfig = {
13 | solidity: {
14 | compilers: [
15 | {
16 | version: "0.8.7",
17 | },
18 | {
19 | version: "0.4.24",
20 | },
21 | ],
22 | },
23 | networks: {
24 | rinkeby: {
25 | url: process.env.SEPOLIA_URL || "",
26 | accounts:
27 | process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],
28 | },
29 | },
30 | gasReporter: {
31 | enabled: process.env.REPORT_GAS !== undefined,
32 | currency: "USD",
33 | },
34 | etherscan: {
35 | apiKey: {
36 | rinkeby: process.env.ETHERSCAN_API_KEY,
37 | },
38 | },
39 | };
40 |
41 | export default config;
42 |
--------------------------------------------------------------------------------
/random-svg-nft/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "emoji-nft",
3 | "license": "MIT",
4 | "scripts": {
5 | "compile": "hardhat compile",
6 | "test": "hardhat test",
7 | "coverage": "hardhat coverage",
8 | "deploy": "hardhat run --network rinkeby scripts/deploy.ts"
9 | },
10 | "devDependencies": {
11 | "@chainlink/contracts": "^0.4.0",
12 | "@nomiclabs/hardhat-ethers": "^2.0.4",
13 | "@nomiclabs/hardhat-etherscan": "^3.0.1",
14 | "@nomiclabs/hardhat-waffle": "^2.0.2",
15 | "@openzeppelin/contracts": "^4.5.0",
16 | "@typechain/ethers-v5": "^7.2.0",
17 | "@typechain/hardhat": "^2.3.1",
18 | "@types/chai": "^4.3.0",
19 | "@types/mocha": "^9.1.0",
20 | "@types/node": "^12.20.42",
21 | "@typescript-eslint/eslint-plugin": "^4.33.0",
22 | "@typescript-eslint/parser": "^4.33.0",
23 | "chai": "^4.3.6",
24 | "dotenv": "^10.0.0",
25 | "eslint": "^7.32.0",
26 | "eslint-config-prettier": "^8.3.0",
27 | "eslint-config-standard": "^16.0.3",
28 | "eslint-plugin-import": "^2.25.4",
29 | "eslint-plugin-node": "^11.1.0",
30 | "eslint-plugin-prettier": "^3.4.1",
31 | "eslint-plugin-promise": "^5.2.0",
32 | "ethereum-waffle": "^3.4.0",
33 | "ethers": "^5.5.3",
34 | "hardhat": "^2.8.3",
35 | "hardhat-gas-reporter": "^1.0.7",
36 | "prettier": "^2.5.1",
37 | "prettier-plugin-solidity": "^1.0.0-beta.13",
38 | "solhint": "^3.3.6",
39 | "solidity-coverage": "^0.7.18",
40 | "ts-node": "^10.4.0",
41 | "typechain": "^5.2.0",
42 | "typescript": "^4.5.5"
43 | },
44 | "dependencies": {}
45 | }
46 |
--------------------------------------------------------------------------------
/random-svg-nft/test/shared/helpers.ts:
--------------------------------------------------------------------------------
1 | import { BigNumber, Wallet } from "ethers";
2 | import { parseEther } from "ethers/lib/utils";
3 | import { VRFCoordinatorV2Mock } from "../../typechain";
4 |
5 | export const createAndFundMockSubscription = async (
6 | vrfCoordinatorMock: VRFCoordinatorV2Mock,
7 | deployer: Wallet
8 | ): Promise => {
9 | const tx = await vrfCoordinatorMock.connect(deployer).createSubscription();
10 | const txReceipt = await tx.wait();
11 | const subscriptionId = BigNumber.from(txReceipt.logs[0].topics[1]);
12 | await vrfCoordinatorMock.fundSubscription(subscriptionId, parseEther(`1`));
13 |
14 | return subscriptionId;
15 | };
16 |
--------------------------------------------------------------------------------
/random-svg-nft/test/shared/types.ts:
--------------------------------------------------------------------------------
1 | import { Fixture } from "ethereum-waffle";
2 | import { Wallet } from "@ethersproject/wallet";
3 | import { EmojiNFT, VRFCoordinatorV2Mock } from "../../typechain";
4 |
5 | declare module "mocha" {
6 | export interface Context {
7 | loadFixture: (fixture: Fixture) => Promise;
8 | signers: Signers;
9 | emojiNft: EmojiNFT;
10 | vrfCoordinatorMock: VRFCoordinatorV2Mock;
11 | }
12 | }
13 |
14 | export interface Signers {
15 | deployer: Wallet;
16 | alice: Wallet;
17 | bob: Wallet;
18 | }
19 |
--------------------------------------------------------------------------------
/random-svg-nft/test/unit/EmojiNFT/EmojiNFTShouldMint.spec.ts:
--------------------------------------------------------------------------------
1 | import { expect, assert } from "chai";
2 | import { BigNumber } from "ethers";
3 | import { ethers } from "hardhat";
4 |
5 | export const shouldMint = (): void => {
6 | // to silent warning for duplicate definition of Transfer event
7 | ethers.utils.Logger.setLogLevel(ethers.utils.Logger.levels.OFF);
8 |
9 | context(`#mint`, async function () {
10 | it(`should mint new NFT`, async function () {
11 | const requestId: BigNumber = await this.emojiNft.callStatic.mint();
12 |
13 | await expect(this.emojiNft.connect(this.signers.alice).mint())
14 | .to.emit(this.emojiNft, `RandomnessRequested`)
15 | .withArgs(requestId);
16 |
17 | await this.vrfCoordinatorMock.fulfillRandomWords(
18 | requestId,
19 | this.emojiNft.address
20 | );
21 |
22 | const aliceBalance: BigNumber = await this.emojiNft.balanceOf(
23 | this.signers.alice.address
24 | );
25 |
26 | assert(aliceBalance.eq(ethers.constants.One));
27 | });
28 | });
29 | };
30 |
--------------------------------------------------------------------------------
/random-svg-nft/test/unit/index.ts:
--------------------------------------------------------------------------------
1 | import { waffle } from "hardhat";
2 | import { unitEmojiNftFixture } from "../shared/fixtures";
3 | import { Signers } from "../shared/types";
4 | import { shouldMint } from "./EmojiNFT/EmojiNFTShouldMint.spec";
5 |
6 | describe(`Unit tests`, async () => {
7 | before(async function () {
8 | const wallets = waffle.provider.getWallets();
9 |
10 | this.signers = {} as Signers;
11 | this.signers.deployer = wallets[0];
12 | this.signers.alice = wallets[1];
13 | this.signers.bob = wallets[2];
14 |
15 | this.loadFixture = waffle.createFixtureLoader(wallets);
16 | });
17 |
18 | describe(`EmojiNFT`, async () => {
19 | beforeEach(async function () {
20 | const { emojiNft, vrfCoordinatorMock } = await this.loadFixture(
21 | unitEmojiNftFixture
22 | );
23 |
24 | this.emojiNft = emojiNft;
25 | this.vrfCoordinatorMock = vrfCoordinatorMock;
26 | });
27 |
28 | shouldMint();
29 | });
30 | });
31 |
--------------------------------------------------------------------------------
/random-svg-nft/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es2018",
4 | "module": "commonjs",
5 | "strict": true,
6 | "esModuleInterop": true,
7 | "outDir": "dist",
8 | "declaration": true
9 | },
10 | "include": ["./scripts", "./test", "./typechain"],
11 | "files": ["./hardhat.config.ts"]
12 | }
13 |
--------------------------------------------------------------------------------
/timelocked-contracts/.gitignore:
--------------------------------------------------------------------------------
1 | cache/
2 | out/
3 |
--------------------------------------------------------------------------------
/timelocked-contracts/README.md:
--------------------------------------------------------------------------------
1 | # Timelocked Contracts
2 | This repo supports the blog post [posthere](https://blog.chain.link)
3 |
4 | ## How to Use The Repo
5 |
6 | This repo was developed using [Foundry](https://github.com/foundry-rs/foundry)
7 |
8 | Use `forge test` to run the test suite.
--------------------------------------------------------------------------------
/timelocked-contracts/foundry.toml:
--------------------------------------------------------------------------------
1 | [profile.default]
2 | src = 'src'
3 | out = 'out'
4 | libs = ['lib']
5 |
6 | # See more config options https://github.com/gakonst/foundry/tree/master/config
--------------------------------------------------------------------------------
/timelocked-contracts/remappings.txt:
--------------------------------------------------------------------------------
1 | @openzeppelin/=lib/openzeppelin-contracts/
2 | ds-test/=lib/ds-test/src/
--------------------------------------------------------------------------------
/ultimate-nft-repo/.env.example:
--------------------------------------------------------------------------------
1 | NFT_STORAGE_KEY='asdfasdfasdf'
2 | PINATA_API_KEY='asdfasdfasdf'
3 | PINATA_API_SECRET='asdfasdfasdf'
4 | UPLOAD_TO_PINATA=true
5 | ETHERSCAN_API_KEY='asdfasdfasdf'
6 | COINMARKETCAP_API_KEY='asdfasdfasdf'
7 | SEPOLIA_RPC_URL='asdfasdfasdf'
--------------------------------------------------------------------------------
/ultimate-nft-repo/.npmignore:
--------------------------------------------------------------------------------
1 | hardhat.config.js
2 | scripts
3 | test
4 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/.prettierignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | artifacts
3 | cache
4 | coverage*
5 | gasReporterOutput.json
6 | package.json
7 | img
8 | .env
9 | .*
10 | README.md
11 | coverage.json
12 | deployments
--------------------------------------------------------------------------------
/ultimate-nft-repo/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "tabWidth": 4,
3 | "useTabs": false,
4 | "semi": false,
5 | "singleQuote": false,
6 | "printWidth": 100
7 | }
8 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/contracts/BasicNft.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.8;
3 |
4 | import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
5 |
6 | contract BasicNft is ERC721 {
7 | string public constant TOKEN_URI =
8 | "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json";
9 | uint256 private s_tokenCounter;
10 |
11 | constructor() ERC721("Dogie", "DOG") {
12 | s_tokenCounter = 0;
13 | }
14 |
15 | function mintNft() public returns (uint256) {
16 | _safeMint(msg.sender, s_tokenCounter);
17 | s_tokenCounter = s_tokenCounter + 1;
18 | return s_tokenCounter;
19 | }
20 |
21 | function tokenURI(uint256 tokenId) public view override returns (string memory) {
22 | // require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
23 | return TOKEN_URI;
24 | }
25 |
26 | function getTokenCounter() public view returns (uint256) {
27 | return s_tokenCounter;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/contracts/test/MockV3Aggregator.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.6.0;
3 |
4 | import "@chainlink/contracts/src/v0.6/tests/MockV3Aggregator.sol";
5 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/contracts/test/VRFCoordinatorV2Mock.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol";
5 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/deploy/00-deploy-mocks.js:
--------------------------------------------------------------------------------
1 | const { network } = require("hardhat")
2 | const { DECIMALS, INITIAL_PRICE } = require("../helper-hardhat-config")
3 |
4 | const BASE_FEE = "250000000000000000" // 0.25 is this the premium in LINK?
5 | const GAS_PRICE_LINK = 1e9 // link per gas, is this the gas lane? // 0.000000001 LINK per gas
6 |
7 | module.exports = async ({ getNamedAccounts, deployments }) => {
8 | const { deploy, log } = deployments
9 | const { deployer } = await getNamedAccounts()
10 | const chainId = network.config.chainId
11 | // If we are on a local development network, we need to deploy mocks!
12 | if (chainId == 31337) {
13 | log("Local network detected! Deploying mocks...")
14 | await deploy("VRFCoordinatorV2Mock", {
15 | from: deployer,
16 | log: true,
17 | args: [BASE_FEE, GAS_PRICE_LINK],
18 | })
19 | await deploy("MockV3Aggregator", {
20 | from: deployer,
21 | log: true,
22 | args: [DECIMALS, INITIAL_PRICE],
23 | })
24 |
25 | log("Mocks Deployed!")
26 | log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
27 | log("You are deploying to a local network, you'll need a local network running to interact")
28 | log(
29 | "Please run `yarn hardhat console --network localhost` to interact with the deployed smart contracts!"
30 | )
31 | log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
32 | }
33 | }
34 | module.exports.tags = ["all", "mocks", "main"]
35 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/deploy/01-deploy-basic-nft.js:
--------------------------------------------------------------------------------
1 | const { network } = require("hardhat")
2 | const { developmentChains } = require("../helper-hardhat-config")
3 | const { verify } = require("../utils/verify")
4 |
5 | module.exports = async ({ getNamedAccounts, deployments }) => {
6 | const { deploy, log } = deployments
7 | const { deployer } = await getNamedAccounts()
8 |
9 | log("----------------------------------------------------")
10 | arguments = []
11 | const basicNft = await deploy("BasicNft", {
12 | from: deployer,
13 | args: arguments,
14 | log: true,
15 | waitConfirmations: network.config.blockConfirmations || 1,
16 | })
17 |
18 | // Verify the deployment
19 | if (!developmentChains.includes(network.name) && process.env.ETHERSCAN_API_KEY) {
20 | log("Verifying...")
21 | await verify(basicNft.address, arguments)
22 | }
23 | }
24 |
25 | module.exports.tags = ["all", "basicnft", "main"]
26 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/helper-hardhat-config.js:
--------------------------------------------------------------------------------
1 | const networkConfig = {
2 | 31337: {
3 | name: "localhost",
4 | ethUsdPriceFeed: "0x9326BFA02ADD2366b30bacB125260Af641031331",
5 | gasLane: "0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc", // 30 gwei
6 | mintFee: "10000000000000000", // 0.01 ETH
7 | callbackGasLimit: "500000", // 500,000 gas
8 | },
9 | // Price Feed Address, values can be obtained at https://docs.chain.link/docs/reference-contracts
10 | // Default one is ETH/USD contract on Kovan
11 | 11155111: {
12 | name: "sepolia",
13 | ethUsdPriceFeed: "0x694AA1769357215DE4FAC081bf1f309aDC325306",
14 | vrfCoordinatorV2: "0x8103B0A8A00be2DDC778e6e7eaa21791Cd364625",
15 | gasLane: "0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c",
16 | callbackGasLimit: "500000", // 500,000 gas
17 | mintFee: "10000000000000000", // 0.01 ETH
18 | subscriptionId: "", // add your ID here!
19 | },
20 | }
21 |
22 | const DECIMALS = "18"
23 | const INITIAL_PRICE = "200000000000000000000"
24 | const developmentChains = ["hardhat", "localhost"]
25 |
26 | module.exports = {
27 | networkConfig,
28 | developmentChains,
29 | DECIMALS,
30 | INITIAL_PRICE,
31 | }
32 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/images/dynamicNft/frown.svg:
--------------------------------------------------------------------------------
1 |
2 |
7 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/images/dynamicNft/happy.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/images/randomNft/pug.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smartcontractkit/smart-contract-examples/32bb95e558bdd6a4ebab4b6c1eadbfc83668c539/ultimate-nft-repo/images/randomNft/pug.png
--------------------------------------------------------------------------------
/ultimate-nft-repo/images/randomNft/shiba-inu.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smartcontractkit/smart-contract-examples/32bb95e558bdd6a4ebab4b6c1eadbfc83668c539/ultimate-nft-repo/images/randomNft/shiba-inu.png
--------------------------------------------------------------------------------
/ultimate-nft-repo/images/randomNft/st-bernard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smartcontractkit/smart-contract-examples/32bb95e558bdd6a4ebab4b6c1eadbfc83668c539/ultimate-nft-repo/images/randomNft/st-bernard.png
--------------------------------------------------------------------------------
/ultimate-nft-repo/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "hardhat-project",
3 | "devDependencies": {
4 | "@nomiclabs/hardhat-ethers": "npm:hardhat-deploy-ethers",
5 | "@nomiclabs/hardhat-etherscan": "^3.0.3",
6 | "@nomiclabs/hardhat-waffle": "^2.0.3",
7 | "chai": "^4.3.4",
8 | "ethereum-waffle": "^3.4.0",
9 | "ethers": "^5.5.4",
10 | "hardhat": "^2.9.0",
11 | "hardhat-deploy": "^0.10.5",
12 | "hardhat-gas-reporter": "^1.0.7",
13 | "prettier": "^2.5.1",
14 | "solidity-coverage": "^0.7.18"
15 | },
16 | "dependencies": {
17 | "@aave/protocol-v2": "^1.0.1",
18 | "@chainlink/contracts": "^0.4.0",
19 | "@ethersproject/bignumber": "^5.5.0",
20 | "@openzeppelin/contracts": "^4.5.0",
21 | "@pinata/sdk": "^1.1.23",
22 | "base64-sol": "^1.1.0",
23 | "dotenv": "^16.0.0",
24 | "fs": "^0.0.1-security",
25 | "mime": "^3.0.0",
26 | "nft.storage": "^6.0.1",
27 | "path": "^0.12.7",
28 | "prettier-plugin-solidity": "^1.0.0-beta.19",
29 | "solhint": "^3.3.7"
30 | },
31 | "scripts": {
32 | "lint": "solhint 'contracts/*.sol'",
33 | "lint:fix": "solhint 'contracts/**/*.sol' --fix",
34 | "format": "prettier --write ."
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/test/unit/basicNft.test.js:
--------------------------------------------------------------------------------
1 | // We are going to skimp a bit on these tests...
2 |
3 | const { assert } = require("chai")
4 | const { network, deployments, ethers } = require("hardhat")
5 | const { developmentChains } = require("../../helper-hardhat-config")
6 |
7 | !developmentChains.includes(network.name)
8 | ? describe.skip
9 | : describe("Basic NFT Unit Tests", async function () {
10 | let basicNft, deployer
11 |
12 | beforeEach(async () => {
13 | accounts = await ethers.getSigners()
14 | deployer = accounts[0]
15 | await deployments.fixture(["mocks", "basicnft"])
16 | basicNft = await ethers.getContract("BasicNft")
17 | })
18 |
19 | it("Allows users to mint an NFT, and updates appropriately", async function () {
20 | const txResponse = await basicNft.mintNft()
21 | await txResponse.wait(1)
22 | const tokenURI = await basicNft.tokenURI(0)
23 | const tokenCounter = await basicNft.getTokenCounter()
24 |
25 | assert.equal(tokenCounter.toString(), "1")
26 | assert.equal(tokenURI, await basicNft.TOKEN_URI())
27 | })
28 | })
29 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/utils/uploadToPinata.js:
--------------------------------------------------------------------------------
1 | const pinataSDK = require("@pinata/sdk")
2 | const fs = require("fs")
3 | const path = require("path")
4 |
5 | const pinataApiKey = process.env.PINATA_API_KEY || ""
6 | const pinataApiSecret = process.env.PINATA_API_SECRET || ""
7 | const pinata = pinataSDK(pinataApiKey, pinataApiSecret)
8 |
9 | async function storeImages(imagesFilePath) {
10 | const fullImagesPath = path.resolve(imagesFilePath)
11 | const files = fs.readdirSync(fullImagesPath)
12 | let responses = []
13 | for (fileIndex in files) {
14 | const readableStreamForFile = fs.createReadStream(`${fullImagesPath}/${files[fileIndex]}`)
15 | try {
16 | const response = await pinata.pinFileToIPFS(readableStreamForFile)
17 | responses.push(response)
18 | } catch (error) {
19 | console.log(error)
20 | }
21 | }
22 | return { responses, files }
23 | }
24 |
25 | async function storeTokeUriMetadata(metadata) {
26 | try {
27 | const response = await pinata.pinJSONToIPFS(metadata)
28 | return response
29 | } catch (error) {
30 | console.log(error)
31 | }
32 | return null
33 | }
34 |
35 | module.exports = { storeImages, storeTokeUriMetadata }
36 |
--------------------------------------------------------------------------------
/ultimate-nft-repo/utils/verify.js:
--------------------------------------------------------------------------------
1 | // we can't have these functions in our `helper-hardhat-config`
2 | // since these use the hardhat library
3 | // and it would be a circular dependency
4 | const { run, network } = require("hardhat")
5 | const { networkConfig } = require("../helper-hardhat-config")
6 |
7 | const verify = async (contractAddress, args) => {
8 | console.log("Verifying contract...")
9 | try {
10 | await run("verify:verify", {
11 | address: contractAddress,
12 | constructorArguments: args,
13 | })
14 | } catch (e) {
15 | if (e.message.toLowerCase().includes("already verified")) {
16 | console.log("Already verified!")
17 | } else {
18 | console.log(e)
19 | }
20 | }
21 | }
22 |
23 | module.exports = {
24 | verify,
25 | }
26 |
--------------------------------------------------------------------------------
/upkeep-interactions/custom-logic-upkeep/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | package-lock.json
3 | .env.enc
4 | .env
--------------------------------------------------------------------------------
/upkeep-interactions/custom-logic-upkeep/README.md:
--------------------------------------------------------------------------------
1 | # Custom Logic Upkeep Interactions
2 |
3 | ### UpkeepInteractions.sol
4 |
5 | A solidity contract showcasing the interaction with `AutomationRegistrar` and `KeeperRegistry` contracts, for **registration** of **Custom Logic Upkeep** and performing other operations like **pause upkeep**, **unpause upkeep**, **cancel upkeep**, **add funds to upkeep**, **withdraw funds from upkeep**, and **edit gas limit of upkeep**.
6 |
7 | **Note:** The upkeep that will be registered using the contract won't be visible in the [Automation UI](https://automation.chain.link/) because the `adminAddress` is being set to the address of the contract (not to any wallet).
8 |
9 | ### upkeepInteractions.js
10 |
11 | A script in JS containing the functions to interact with the registered **Custom Logic Upkeep**.
12 |
13 | Run the script using this command:
14 |
15 | ```js
16 | node upkeepInteractions.js ${KEEPER_REGISTRY_ADDRESS} ${LINK_TOKEN_ADDRESS}
17 | ```
--------------------------------------------------------------------------------
/upkeep-interactions/custom-logic-upkeep/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "@chainlink/env-enc": "^1.0.5",
4 | "ethers": "^6.13.2"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/vrf-arbitrum-gas-estimation/.env-sample:
--------------------------------------------------------------------------------
1 | # Hosted Aggregator Node (JSON-RPC Endpoint). This is Arbitrum Goerli Testnet, can use any Arbitrum chain
2 | L2RPC="https://goerli-rollup.arbitrum.io/rpc"
--------------------------------------------------------------------------------
/vrf-arbitrum-gas-estimation/README.md:
--------------------------------------------------------------------------------
1 | # VRF / Arbitrum gas estimation tutorial
2 |
3 | This extends the [**original Arbitrum gas estimation tutorial**](https://github.com/OffchainLabs/arbitrum-tutorials/tree/master/packages/gas-estimation) to add [gas estimate calculations for Chainlink VRF](https://docs.chain.link/vrf/v2/estimating-costs#arbitrum).
4 |
5 | ---
6 |
7 | # Gas estimation tutorial
8 |
9 | `gas-estimation` is a simple demo of how a developer can estimate transaction fees on Arbitrum.
10 |
11 | It uses the formula described in this Medium article to estimate the fees to be paid on a transaction, also estimating each component of the formula separately: [Understanding Arbitrum: 2-Dimensional Fees](https://medium.com/offchainlabs/understanding-arbitrum-2-dimensional-fees-fd1d582596c9).
12 |
13 | See [./exec.ts](./scripts/exec.ts) for inline explanations.
14 |
15 | Inside the script, you can edit `txData` constant to suit your needs.
16 |
17 | To run:
18 |
19 | ```
20 | yarn run exec
21 | ```
22 |
23 | ## Config Environment Variables
24 |
25 | Set the values shown in `.env-sample` as environmental variables. To copy it into a `.env` file:
26 |
27 | ```bash
28 | cp .env-sample .env
29 | ```
30 |
31 | (you'll still need to edit some variables, i.e., `L2RPC`)
32 |
--------------------------------------------------------------------------------
/vrf-arbitrum-gas-estimation/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "gas-estimation",
3 | "version": "1.0.0",
4 | "description": "",
5 | "scripts": {
6 | "exec": "ts-node scripts/exec.ts"
7 | },
8 | "dependencies": {
9 | "@arbitrum/sdk": "^v3.1.2",
10 | "ts-node": "^10.8.1",
11 | "typescript": "^4.7.3"
12 | },
13 | "author": "",
14 | "license": "ISC"
15 | }
--------------------------------------------------------------------------------