├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md ├── pull_request_template.md └── workflows │ ├── checker.yml │ ├── compile.yml │ ├── contrib.yml │ └── greetings.yml ├── .gitignore ├── LICENSE.md ├── README.md ├── contracts ├── Auction │ ├── DutchAuction.sol │ ├── EnglishAuction.sol │ └── SimpleAuction.sol ├── Banking │ └── BankingSystem.sol ├── Blog │ └── Blog.sol ├── Coins │ └── erc20std.sol ├── DAO │ └── metadao.sol ├── DeFi │ └── yeildGen.sol ├── Ecommerce │ └── ecommerce.sol ├── Escrow │ └── EscrowContract.sol ├── Event_organize │ └── event.sol ├── Games │ ├── Casino.sol │ ├── CoinFlip.sol │ ├── UnoCard.sol │ ├── lottery.sol │ └── tic-tac-toe.sol ├── Health-Rec │ └── HealthRec.sol ├── Memoapp │ └── GetMemo.sol ├── Messaging │ └── Messaging.sol ├── Misc │ ├── ChainlinkETHPriceFetch.sol │ ├── CommitReveal.sol │ ├── CrowdFunding.sol │ ├── DecentralizedParking.sol │ ├── Faucet.sol │ ├── LibraryManagement.sol │ ├── MultiSigWallet.sol │ ├── NFTDropRegistration.sol │ ├── PasswordManager.sol │ ├── PersonalDetailStorage.sol │ ├── ProofOfMerge.sol │ ├── Propertyregistery.sol │ ├── RestaurantsManager.sol │ ├── TaxiService.sol │ ├── TicketingSystem │ │ ├── PriceConverter.sol │ │ └── TicketBooker.sol │ ├── VaccineTracker.sol │ ├── Vesting_Contract.sol │ └── healthVerse.sol ├── NFT Warranty │ ├── README.md │ └── nft-warranty.sol ├── NFT │ ├── Soulbound.sol │ ├── erc1155.sol │ ├── erc2981-erc721.sol │ └── erc721std.sol ├── PreventSpam │ └── CommentMe.sol ├── Real_TimeData_Feed │ ├── Readme.md │ └── RealTime_Data_Feed.sol ├── Salary Payment System │ ├── README.md │ └── SalaryPaymentSystem.sol ├── Shared Wallet │ └── SharedWallet.sol ├── Supplychain │ └── supplychain.sol ├── TimeLock │ ├── TestCoin.sol │ └── TimeLock.sol ├── Voting │ ├── Election.sol │ └── README.md └── blockDNS │ ├── Description.md │ └── dns.sol ├── hardhat.config.js ├── package-lock.json ├── package.json ├── scripts └── deploy.js └── test └── Lock.js /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Metafy Code of Conduct 2 | 3 | Our Pledge 4 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 5 | 6 | ## Our Standards 7 | Examples of behavior that contributes to creating a positive environment include: 8 | 9 | - Using welcoming and inclusive language 10 | - Being respectful of differing viewpoints and experiences 11 | - Gracefully accepting constructive criticism 12 | - Focusing on what is best for the community 13 | - Showing empathy towards other community members 14 | 15 | Examples of unacceptable behavior by participants include: 16 | 17 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 18 | - Trolling, insulting/derogatory comments, and personal or political attacks 19 | - Public or private harassment 20 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 21 | - Other conduct which could reasonably be considered inappropriate in a professional setting 22 | 23 | ## Code Standards 24 | - Every addressed issue solution must be within its own folder. 25 | - Every folder must contain a README.md file with the problem statement and guides to run your code. 26 | - Commit messages must follow the [Commit Message Guidelines](https://github.com/metafy-social/.github/blob/main/profile/COMMIT-MESSAGE-GUIDELINES.md). 27 | - The code must be written in solidity 8. 28 | 29 | ## Our Responsibilities 30 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 31 | 32 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 33 | 34 | ## Scope 35 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 36 | 37 | This Code of Conduct also applies outside the project spaces when the Project Steward has a reasonable belief that an individual's behavior may have a negative impact on the project or its community. 38 | 39 | ## Enforcement 40 | 41 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 42 | reported to the community leaders responsible for enforcement at [support@metafy.social](mailto:support@metafy.social). 43 | All complaints will be reviewed and investigated promptly and fairly. 44 | 45 | All community leaders are obligated to respect the privacy and security of the 46 | reporter of any incident. 47 | 48 | ## Enforcement Guidelines 49 | 50 | Community leaders will follow these Community Impact Guidelines in determining 51 | the consequences for any action they deem in violation of this Code of Conduct: 52 | 53 | ### 1. Correction 54 | 55 | **Community Impact**: Use of inappropriate language or other behavior deemed 56 | unprofessional or unwelcome in the community. 57 | 58 | **Consequence**: A private, written warning from community leaders, providing 59 | clarity around the nature of the violation and an explanation of why the 60 | behavior was inappropriate. A public apology may be requested. 61 | 62 | ### 2. Warning 63 | 64 | **Community Impact**: A violation through a single incident or series 65 | of actions. 66 | 67 | **Consequence**: A warning with consequences for continued behavior. No 68 | interaction with the people involved, including unsolicited interaction with 69 | those enforcing the Code of Conduct, for a specified period of time. This 70 | includes avoiding interactions in community spaces as well as external channels 71 | like social media. Violating these terms may lead to a temporary or 72 | permanent ban. 73 | 74 | ### 3. Temporary Ban 75 | 76 | **Community Impact**: A serious violation of community standards, including 77 | sustained inappropriate behavior. 78 | 79 | **Consequence**: A temporary ban from any sort of interaction or public 80 | communication with the community for a specified period of time. No public or 81 | private interaction with the people involved, including unsolicited interaction 82 | with those enforcing the Code of Conduct, is allowed during this period. 83 | Violating these terms may lead to a permanent ban. 84 | 85 | ### 4. Permanent Ban 86 | 87 | **Community Impact**: Demonstrating a pattern of violation of community 88 | standards, including sustained inappropriate behavior, harassment of an 89 | individual, or aggression toward or disparagement of classes of individuals. 90 | 91 | **Consequence**: A permanent ban from any sort of public interaction within 92 | the community. 93 | 94 | ## Conflict Resolution 95 | We do not believe that all conflict is bad; healthy debate and disagreement often yield positive results. However, it is never okay to be disrespectful or to engage in behavior that violates the project’s code of conduct. 96 | 97 | If you see someone violating the code of conduct, you are encouraged to address the behavior directly with those involved. Many issues can be resolved quickly and easily, and this gives people more control over the outcome of their dispute. If you are unable to resolve the matter for any reason, or if the behavior is threatening or harassing, report it. We are dedicated to providing an environment where participants feel welcome and safe. 98 | 99 | Reports should be directed to [@advaita-saha](https://github.com/advaita-saha), [@bartick](https://github.com/bartick), [@kriptonian1](https://github.com/kriptonian1), [@agnxsh](https://github.com/agnxsh), [@riyaroy2086](https://github.com/riyaroy2086), or [@sayan011](https://github.com/sayan011) , the Project Steward(s) for **Metafy**. It is the Project Steward’s duty to receive and address reported violations of the code of conduct. They will then work with a committee consisting of representatives from the Open Source Programs Office and the Google Open Source Strategy team. If for any reason you are uncomfortable reaching out to the Project Steward, please email [support@metafy.social](mailto:support@metafy.social). 100 | 101 | We will investigate every complaint, but you may not receive a direct response. We will use our discretion in determining when and how to follow up on reported incidents, which may range from not taking action to permanent expulsion from the project and project-sponsored spaces. We will notify the accused of the report and provide them an opportunity to discuss it before any action is taken. The identity of the reporter will be omitted from the details of the report supplied to the accused. In potentially harmful situations, such as ongoing harassment or threats to anyone's safety, we may take action without notice. 102 | 103 | ## Attribution 104 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 105 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Metafy Discord 4 | url: https://discord.gg/W6PmEjjQsA 5 | about: An invite Link to our discord community 6 | - name: Metafy Website 7 | url: https://metafy.social 8 | about: Our official website 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Is your feature request related to a problem? Please describe. 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | ### Describe the solution you'd like 14 | A clear and concise description of what you want to happen. 15 | 16 | ### Describe alternatives you've considered 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | ### Additional context 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | _Give a summary of the change that you have made_
4 | 5 | Fixes #[ISSUENO] 6 | 7 | ## Dependencies 8 | 9 | _Mention any dependencies/packages used_ 10 | 11 | ## Future Improvements 12 | 13 | _Mention any improvements to be done in future related to any file/feature_ 14 | 15 | ## Mentions 16 | 17 | _Mention and tag the people_ 18 | 19 | ## Screenshots of relevant screens 20 | 21 | _Add screenshots of relevant screens_ 22 | 23 | ## Developer's checklist 24 | 25 | - [ ] My PR follows the style guidelines of this project 26 | - [ ] I have performed a self-check on my work 27 | 28 | **If changes are made in the code:** 29 | 30 | - [ ] I have followed the [coding guidelines](https://google.github.io/styleguide/jsguide.html) 31 | - [ ] My changes in code generate no new warnings 32 | - [ ] My changes are breaking another fix/feature of the project 33 | - [ ] I have added test cases to show that my feature works 34 | - [ ] I have added relevant screenshots in my PR 35 | -------------------------------------------------------------------------------- /.github/workflows/checker.yml: -------------------------------------------------------------------------------- 1 | name: PR has a valid Issue? 2 | 3 | on: 4 | pull_request_target: 5 | types: [ edited, synchronize, opened, reopened ] 6 | 7 | jobs: 8 | checker: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v2 13 | 14 | - name: Issue Validator 15 | uses: HarshCasper/validate-issues-over-pull-requests@v0.1.1 16 | id: validator 17 | with: 18 | prbody: ${{ github.event.pull_request.body }} 19 | prurl: ${{ github.event.pull_request.url }} 20 | 21 | - name: PR has a valid Issue 22 | if: ${{ steps.validator.outputs.valid == 1 }} 23 | env: 24 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 25 | PRNUM: ${{ github.event.pull_request.number }} 26 | run: | 27 | gh pr edit $PRNUM --add-label "PR:Ready-to-Review" 28 | gh pr edit $PRNUM --add-label "hacktoberfest-accepted" 29 | gh pr edit $PRNUM --remove-label "PR:No-Issue" 30 | 31 | - name: PR has no valid Issue 32 | if: ${{ steps.validator.outputs.valid == 0 }} 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | PRNUM: ${{ github.event.pull_request.number }} 36 | run: | 37 | gh pr comment $PRNUM --body "PR is not linked to any issue, please make the corresponding changes in the body." 38 | gh pr edit $PRNUM --add-label "PR:No-Issue" 39 | -------------------------------------------------------------------------------- /.github/workflows/compile.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Hardhat CI 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [ 16.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v2 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | - run: npm ci 29 | - name: Compile Smart Contract 30 | run: npx hardhat compile 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /.github/workflows/contrib.yml: -------------------------------------------------------------------------------- 1 | name: 'Add contributors to readme' 2 | on: 3 | push: 4 | branches: [ master ] 5 | 6 | jobs: 7 | contrib-readme-job: 8 | runs-on: ubuntu-latest 9 | name: A job to automate contrib in readme 10 | steps: 11 | - name: Contribute List 12 | uses: akhilmhdh/contributors-readme-action@v2.3.6 13 | env: 14 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 15 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: 'Welcome New Contributors' 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | pull_request_target: 7 | types: [opened] 8 | 9 | jobs: 10 | welcome-new-contributor: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: 'Greet the contributor' 14 | uses: garg3133/welcome-new-contributors@v1.2 15 | with: 16 | token: ${{ secrets.GITHUB_TOKEN }} 17 | issue-message: | 18 | Thank you for opening your first issue in our repository, one of our maintainers will get in touch with you soon. 19 | 20 | **DO NOT FORGET TO ADD METAMASK WALLET ADDRESS IN THE AUTH FORM** 21 | We at Metafy have some special rewards and swags for the top contributors in general repos and every contributor in web3 repos 22 | For being eligible for that, please authenticate yourself using this link: 23 | https://metafy.social/signup 24 | 25 | **Rewards : T-shirts & NFT ( for blockchain contributions )** 26 | 27 | Best of luck on your Contributions 28 | For further queries you can join our discord for support : https://discord.gg/W6PmEjjQsA 29 | pr-message: | 30 | Thank you for opening your first pull request in our repository, one of our maintainers will get in touch with you soon. 31 | 32 | **DO NOT FORGET TO ADD METAMASK WALLET ADDRESS IN THE AUTH FORM** 33 | We at Metafy have some special rewards and swags for the top contributors in general repos and every contributor in web3 repos 34 | For being eligible for that, please authenticate yourself using this link: 35 | https://metafy.social/signup 36 | 37 | **Rewards : T-shirts & NFT ( for blockchain contributions )** 38 | 39 | Best of luck on your Contributions 40 | For further queries you can join our discord for support : https://discord.gg/W6PmEjjQsA 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | coverage 4 | coverage.json 5 | typechain 6 | typechain-types 7 | .DS_Store 8 | yarn-error.log 9 | 10 | #Hardhat files 11 | cache 12 | artifacts 13 | 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Web3 Smart Contracts

2 |

Show the world the most gas-optimized,secure contract it has ever seen(Just Kidding,It's beginner friendly)

3 |

4 | 5 |

6 |    7 |    8 |    9 |    10 |

11 | 12 |

13 |    14 |    15 |    16 |

17 | 18 | # How to start 19 | 20 | * Think of a cool idea that can be implemented with smart-contracts(can be anything..Game,DeFi-Tool,DAO,something new) . 21 | * Brush up your Solidity Skills (**[Refer here](https://soliditylang.org/)** ) 22 | * That's everything you need fren, now go & BUIDL ⚒️ 23 | 24 | ## Hacktoberfest 2022 Update 25 | 26 | **See full details and guidelines on** 27 | * [Hacktober cheasheat](https://github.com/metafy-social/py-scripts/blob/master/HACKTOBERFEST.md) 28 | * [Official website](https://hacktoberfest.digitalocean.com/) 29 | 30 | 31 |

How to Contribute 🤔

32 | 33 | You can contribute by adding new scripts, improving current scripts or Documentation. Here are some Instructions before making a Pull Request 34 | 35 | ## Here are the steps to Make contribute 👣 36 | 37 | - [x] Take a look at [Contributing Guide](https://github.com/metafy-social/py-scripts/blob/master/CONTRIBUTING.md) (Necessary) 38 | - [x] Create an issue for making any change to code. when issue will be approve you can make a change. 39 | - [x] Pull latest change from upstream branch before starting the changing code. 40 | - [x] Add your file in proper folder(lowercase) with README.md in it. Add requirements.txt if needed. 41 | - [x] Please use flake8 linting in your code (See below to check flake8 linting) 42 | 43 | # Contributors 💪😎 44 | Thanks a lot for spending your time helping! Keep rocking 🍻 45 | 46 | 47 | 48 | 55 | 62 | 69 | 76 | 83 | 90 | 91 | 98 | 105 | 112 | 119 | 126 | 133 | 134 | 141 | 148 | 155 | 162 | 169 | 176 | 177 | 184 | 191 | 198 | 205 | 212 | 219 | 220 | 227 | 234 | 241 | 248 | 255 | 262 | 263 | 270 | 277 | 284 |
49 | 50 | advaita-saha 51 |
52 | Advaita Saha 53 |
54 |
56 | 57 | adityabhattad2021 58 |
59 | Aditya Bhattad 60 |
61 |
63 | 64 | nitantchhajed 65 |
66 | Nitant 67 |
68 |
70 | 71 | ShwetKhatri2001 72 |
73 | Shwet Khatri 74 |
75 |
77 | 78 | kriptonian1 79 |
80 | Sawan Bhattacharya 81 |
82 |
84 | 85 | tsunami03 86 |
87 | Priyadarshini Roy 88 |
89 |
92 | 93 | bartick 94 |
95 | Bartick Maiti 96 |
97 |
99 | 100 | niluk-256 101 |
102 | Niluk 103 |
104 |
106 | 107 | SunilPatel43 108 |
109 | Sunil Patel 110 |
111 |
113 | 114 | issa-me-sush 115 |
116 | Sushthecoda 117 |
118 |
120 | 121 | AnmolSirola 122 |
123 | Anmol 124 |
125 |
127 | 128 | guha-rahul 129 |
130 | Null 131 |
132 |
135 | 136 | Debopom-Banerjee 137 |
138 | Debopom Banerjee 139 |
140 |
142 | 143 | RijuChakraborty 144 |
145 | Riju Chakraborty 146 |
147 |
149 | 150 | supernovahs 151 |
152 | Supernovahs.eth 153 |
154 |
156 | 157 | 0xVikasRushi 158 |
159 | Vikas Rushi 160 |
161 |
163 | 164 | PrakashGatiyala 165 |
166 | Prakash Gatiyala 167 |
168 |
170 | 171 | Vikash-8090-Yadav 172 |
173 | Vikash Yadav 174 |
175 |
178 | 179 | Engineervinay 180 |
181 | Vinay Patil 182 |
183 |
185 | 186 | nirban256 187 |
188 | Nirban Chakraborty 189 |
190 |
192 | 193 | smeax 194 |
195 | Null 196 |
197 |
199 | 200 | antoprince001 201 |
202 | Antony Prince 203 |
204 |
206 | 207 | rajdip-b 208 |
209 | Rajdip Bhattacharya 210 |
211 |
213 | 214 | nabroleonx 215 |
216 | Abel Ayalew 217 |
218 |
221 | 222 | aynp 223 |
224 | Aryan 225 |
226 |
228 | 229 | rahulkarda 230 |
231 | Rahul Karda 232 |
233 |
235 | 236 | riyaroy2086 237 |
238 | Riya Roy 239 |
240 |
242 | 243 | sayan011 244 |
245 | Sayan Chowdhury 246 |
247 |
249 | 250 | ighoshsubho 251 |
252 | Null 253 |
254 |
256 | 257 | vish-han 258 |
259 | Vishal Chauhan 260 |
261 |
264 | 265 | codingis4noobs2 266 |
267 | Null 268 |
269 |
271 | 272 | Dhanush-2605 273 |
274 | Dhanush 275 |
276 |
278 | 279 | yes-im-harsh 280 |
281 | Harsh Chauhan 282 |
283 |
285 | 286 | -------------------------------------------------------------------------------- /contracts/Auction/DutchAuction.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.7; 4 | 5 | interface IERC721 { 6 | function transferFrom( 7 | address _from, 8 | address _to, 9 | uint256 _nftId 10 | ) external; 11 | } 12 | 13 | contract DutchAuction { 14 | event Buy(address winner, uint256 amount); 15 | 16 | IERC721 public immutable nft; 17 | uint256 public immutable nftId; 18 | 19 | address payable public seller; 20 | uint256 public startingPrice; 21 | uint256 public startAt; 22 | uint256 public expiresAt; 23 | uint256 public priceDeductionRate; 24 | address public winner; 25 | 26 | constructor( 27 | uint256 _startingPrice, 28 | uint256 _priceDeductionRate, 29 | address _nft, 30 | uint256 _nftId 31 | ) { 32 | seller = payable(msg.sender); 33 | startingPrice = _startingPrice; 34 | startAt = block.timestamp; 35 | expiresAt = block.timestamp + 7 days; //Expires in week from the start 36 | priceDeductionRate = _priceDeductionRate; 37 | 38 | nft = IERC721(_nft); 39 | nftId = _nftId; 40 | } 41 | 42 | function buy() external payable { 43 | // Check for the timestamp before buy 44 | require(block.timestamp < expiresAt, "auction expired"); 45 | 46 | require(winner == address(0), "auction finished"); 47 | 48 | uint256 timeElapsed = block.timestamp - startAt; 49 | uint256 deduction = priceDeductionRate * timeElapsed; 50 | uint256 price = startingPrice - deduction; 51 | 52 | require(msg.value >= price, "ETH < price"); 53 | 54 | winner = msg.sender; 55 | nft.transferFrom(seller, msg.sender, nftId); 56 | seller.transfer(msg.value); 57 | 58 | emit Buy(msg.sender, msg.value); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /contracts/Auction/EnglishAuction.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.7; 4 | 5 | interface IERC721 { 6 | function transfer(address, uint) external; 7 | 8 | function transferFrom( 9 | address, 10 | address, 11 | uint 12 | ) external; 13 | } 14 | 15 | //Seller of NFT deploys this contract. 16 | //Auction lasts for 7 days. 17 | //Participants can bid by depositing ETH greater than the current highest bidder. 18 | 19 | contract Auction { 20 | event Start(); 21 | event End(address highestBidder, uint highestBid); 22 | event Bid(address indexed sender, uint amount); 23 | event Withdraw(address indexed bidder, uint amount); 24 | 25 | address payable public seller; 26 | 27 | bool public started; 28 | bool public ended; 29 | uint public endAt; 30 | 31 | IERC721 public nft; 32 | uint public nftId; 33 | 34 | uint public highestBid; 35 | address public highestBidder; 36 | mapping(address => uint) public bids; 37 | 38 | constructor () { 39 | seller = payable(msg.sender); 40 | } 41 | 42 | function start(IERC721 _nft, uint _nftId, uint startingBid) external { 43 | require(!started, "Already started!"); 44 | require(msg.sender == seller, "You did not start the auction!"); 45 | highestBid = startingBid; 46 | 47 | nft = _nft; 48 | nftId = _nftId; 49 | nft.transferFrom(msg.sender, address(this), nftId); 50 | 51 | started = true; 52 | endAt = block.timestamp + 7 days; 53 | 54 | emit Start(); 55 | } 56 | 57 | function bid() external payable { 58 | require(started, "Not started."); 59 | require(block.timestamp < endAt, "Ended!"); 60 | require(msg.value > highestBid); 61 | 62 | if (highestBidder != address(0)) { 63 | bids[highestBidder] += highestBid; 64 | } 65 | 66 | highestBid = msg.value; 67 | highestBidder = msg.sender; 68 | 69 | emit Bid(highestBidder, highestBid); 70 | } 71 | 72 | function withdraw() external payable { 73 | uint bal = bids[msg.sender]; 74 | bids[msg.sender] = 0; 75 | (bool sent, bytes memory data) = payable(msg.sender).call{value: bal}(""); 76 | require(sent, "Could not withdraw"); 77 | 78 | emit Withdraw(msg.sender, bal); 79 | } 80 | 81 | function end() external { 82 | require(started, "You need to start first!"); 83 | require(block.timestamp >= endAt, "Auction is still ongoing!"); 84 | require(!ended, "Auction already ended!"); 85 | 86 | if (highestBidder != address(0)) { 87 | nft.transfer(highestBidder, nftId); 88 | (bool sent, bytes memory data) = seller.call{value: highestBid}(""); 89 | require(sent, "Could not pay seller!"); 90 | } else { 91 | nft.transfer(seller, nftId); 92 | } 93 | 94 | ended = true; 95 | emit End(highestBidder, highestBid); 96 | } 97 | } -------------------------------------------------------------------------------- /contracts/Auction/SimpleAuction.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0 2 | pragma solidity ^0.8.4; 3 | 4 | contract SimpleAuction { 5 | // Parameters of the auction. Times are either 6 | // absolute unix timestamps (seconds since 1970-01-01) 7 | // or time periods in seconds. 8 | address payable public beneficiary; 9 | uint256 public auctionEndTime; 10 | 11 | // Current state of the auction. 12 | address public highestBidder; 13 | uint256 public highestBid; 14 | 15 | // Allowed withdrawals of previous bids 16 | mapping(address => uint256) pendingReturns; 17 | 18 | // Set to true at the end, disallows any change. 19 | // By default initialized to `false`. 20 | bool ended; 21 | 22 | // Events that will be emitted on changes. 23 | event HighestBidIncreased(address bidder, uint256 amount); 24 | event AuctionEnded(address winner, uint256 amount); 25 | 26 | // Errors that describe failures. 27 | /// The auction has already ended. 28 | error AuctionAlreadyEnded(); 29 | /// There is already a higher or equal bid. 30 | error BidNotHighEnough(uint256 highestBid); 31 | /// The auction has not ended yet. 32 | error AuctionNotYetEnded(); 33 | /// The function auctionEnd has already been called. 34 | error AuctionEndAlreadyCalled(); 35 | 36 | /// Create a simple auction with `biddingTime` 37 | /// seconds bidding time on behalf of the 38 | /// beneficiary address `beneficiaryAddress`. 39 | constructor(uint256 biddingTime, address payable beneficiaryAddress) { 40 | beneficiary = beneficiaryAddress; 41 | auctionEndTime = block.timestamp + biddingTime; 42 | } 43 | 44 | /// Bid on the auction with the value sent 45 | /// together with this transaction. 46 | /// The value will only be refunded if the 47 | /// auction is not won. 48 | function bid() external payable { 49 | // Revert the call if the bidding 50 | // period is over. 51 | if (block.timestamp > auctionEndTime) revert AuctionAlreadyEnded(); 52 | 53 | // If the bid is not higher, send the 54 | // money back (the revert statement 55 | // will revert all changes in this 56 | // function execution including 57 | // it having received the money). 58 | if (msg.value <= highestBid) revert BidNotHighEnough(highestBid); 59 | 60 | if (highestBid != 0) { 61 | // Sending back the money by simply using 62 | // highestBidder.send(highestBid) is a security risk 63 | // because it could execute an untrusted contract. 64 | // It is always safer to let the recipients 65 | // withdraw their money themselves. 66 | pendingReturns[highestBidder] += highestBid; 67 | } 68 | highestBidder = msg.sender; 69 | highestBid = msg.value; 70 | emit HighestBidIncreased(msg.sender, msg.value); 71 | } 72 | 73 | /// Withdraw a bid that was overbid. 74 | function withdraw() external returns (bool) { 75 | uint256 amount = pendingReturns[msg.sender]; 76 | if (amount > 0) { 77 | // It is important to set this to zero because the recipient 78 | // can call this function again as part of the receiving call 79 | // before `send` returns. 80 | pendingReturns[msg.sender] = 0; 81 | 82 | // msg.sender is not of type `address payable` and must be 83 | // explicitly converted using `payable(msg.sender)` in order 84 | // use the member function `send()`. 85 | if (!payable(msg.sender).send(amount)) { 86 | // No need to call throw here, just reset the amount owing 87 | pendingReturns[msg.sender] = amount; 88 | return false; 89 | } 90 | } 91 | return true; 92 | } 93 | 94 | /// End the auction and send the highest bid 95 | /// to the beneficiary. 96 | function auctionEnd() external { 97 | // 1. Conditions 98 | if (block.timestamp < auctionEndTime) revert AuctionNotYetEnded(); 99 | if (ended) revert AuctionEndAlreadyCalled(); 100 | 101 | // 2. Effects 102 | ended = true; 103 | emit AuctionEnded(highestBidder, highestBid); 104 | 105 | // 3. Interaction 106 | beneficiary.transfer(highestBid); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /contracts/Banking/BankingSystem.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | contract BankingSystem { 5 | 6 | mapping(address => uint256) public balanceOf; // balanceOf, indexed by addresses 7 | 8 | function deposit() public payable { 9 | balanceOf[msg.sender] += msg.value; 10 | } 11 | 12 | function withdraw(uint _amount) public { 13 | require (balanceOf[msg.sender] >= _amount, "Insufficent Funds"); 14 | balanceOf[msg.sender] -= _amount; 15 | (bool sent,) = msg.sender.call{value: _amount}("Sent"); 16 | require(sent, "Failed to Complete"); 17 | } 18 | 19 | // transferAmt function transfers ether from one account to another 20 | function transferAmt(address payable _address, uint _amount) public { 21 | require (balanceOf[msg.sender] >= _amount, "Insufficent Funds"); 22 | _address.transfer(_amount); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /contracts/Blog/Blog.sol: -------------------------------------------------------------------------------- 1 | //SPDX-License-Identifier: Unlicense 2 | pragma solidity ^0.8.7; 3 | 4 | import "hardhat/console.sol"; 5 | import "@openzeppelin/contracts/access/Ownable.sol"; 6 | 7 | //Using inheritance 8 | contract Blog is Ownable { 9 | //creating an event to create a post 10 | event PostCreated(uint id, string title, string _hash); 11 | //creating an event to update a post 12 | event PostUpdated(uint id, string title, string _hash, bool published); 13 | 14 | // creating a struct of post which to define all the propeties a post should hvae 15 | struct Post { 16 | uint id; 17 | string title; 18 | string content; 19 | address publisher; 20 | bool published; 21 | } 22 | 23 | string public name; 24 | uint private latestPostId; 25 | 26 | //creating a mapping 27 | mapping(uint => Post) private idToPost; 28 | mapping(string => Post) private hashToPost; 29 | 30 | // defining a contructor so that while deploying it would show the deployer's name 31 | constructor(string memory _name) { 32 | console.log("Deploy with name: ", name); 33 | name = _name; 34 | } 35 | 36 | //function to update name 37 | function updateName(string memory _name) public onlyOwner { 38 | name = _name; 39 | } 40 | // function to get a Post 41 | function getPost(string memory _hash) public view returns (Post memory) { 42 | return hashToPost[_hash]; 43 | } 44 | // function to create a post 45 | function createPost(string memory title, string memory _hash) public { 46 | Post memory post = Post({ 47 | id: ++latestPostId, 48 | title: title, 49 | content: _hash, 50 | publisher: msg.sender, 51 | published: true 52 | }); 53 | hashToPost[_hash] = post; 54 | idToPost[latestPostId] = post; 55 | 56 | emit PostCreated(latestPostId, title, _hash); 57 | } 58 | 59 | //function to update the post 60 | function updatePost(uint id, string memory title, string memory _hash, bool published) public { 61 | require(idToPost[id].publisher == msg.sender, "forbidden"); 62 | Post storage post = idToPost[id]; 63 | post.title = title; 64 | post.content = _hash; 65 | post.published = published; 66 | hashToPost[_hash] = post; 67 | 68 | emit PostUpdated(id, title, _hash, published); 69 | } 70 | // funciton to get the updated post 71 | function getPosts() public view returns (Post[] memory posts) { 72 | posts = new Post[](latestPostId); 73 | 74 | for(uint i=1; i<=latestPostId; i++) { 75 | posts[i-1] = idToPost[i]; 76 | } 77 | 78 | return posts; 79 | } 80 | } -------------------------------------------------------------------------------- /contracts/Coins/erc20std.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 5 | import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; 6 | import "@openzeppelin/contracts/access/Ownable.sol"; 7 | 8 | // constructor with token name and symbol 9 | contract AdvaitaCoin is ERC20, ERC20Burnable, Ownable { 10 | constructor() ERC20("Advaita Coin", "ADV") { 11 | _mint(msg.sender, 10000 * 10 ** decimals()); 12 | } 13 | 14 | function mint(address to, uint256 amount) public onlyOwner { 15 | _mint(to, amount); 16 | } 17 | } -------------------------------------------------------------------------------- /contracts/DAO/metadao.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | contract MetaDAO { 5 | 6 | event PostCreated (bytes32 indexed postId, address indexed postOwner, bytes32 indexed parentId, bytes32 contentId, bytes32 categoryId); 7 | event ContentAdded (bytes32 indexed contentId, string contentUri); 8 | event CategoryCreated (bytes32 indexed categoryId, string category); 9 | event Voted (bytes32 indexed postId, address indexed postOwner, address indexed voter, uint80 reputationPostOwner, uint80 reputationVoter, int40 postVotes, bool up, uint8 reputationAmount); 10 | 11 | struct post { 12 | address postOwner; 13 | bytes32 parentPost; 14 | bytes32 contentId; 15 | int40 votes; 16 | bytes32 categoryId; 17 | } 18 | 19 | mapping (address => mapping (bytes32 => uint80)) reputationRegistry; 20 | mapping (bytes32 => string) categoryRegistry; 21 | mapping (bytes32 => string) contentRegistry; 22 | mapping (bytes32 => post) postRegistry; 23 | mapping (address => mapping (bytes32 => bool)) voteRegistry; 24 | 25 | function createPost(bytes32 _parentId, string calldata _contentUri, bytes32 _categoryId) external { 26 | address _owner = msg.sender; 27 | bytes32 _contentId = keccak256(abi.encode(_contentUri)); 28 | bytes32 _postId = keccak256(abi.encodePacked(_owner,_parentId, _contentId)); 29 | contentRegistry[_contentId] = _contentUri; 30 | postRegistry[_postId].postOwner = _owner; 31 | postRegistry[_postId].parentPost = _parentId; 32 | postRegistry[_postId].contentId = _contentId; 33 | postRegistry[_postId].categoryId = _categoryId; 34 | emit ContentAdded(_contentId, _contentUri); 35 | emit PostCreated (_postId, _owner,_parentId,_contentId,_categoryId); 36 | } 37 | 38 | function voteUp(bytes32 _postId, uint8 _reputationAdded) external { 39 | address _voter = msg.sender; 40 | bytes32 _category = postRegistry[_postId].categoryId; 41 | address _contributor = postRegistry[_postId].postOwner; 42 | require (postRegistry[_postId].postOwner != _voter, "you cannot vote your own posts"); 43 | require (voteRegistry[_voter][_postId] == false, "Sender already voted in this post"); 44 | require (validateReputationChange(_voter,_category,_reputationAdded)==true, "This address cannot add this amount of reputation points"); 45 | postRegistry[_postId].votes += 1; 46 | reputationRegistry[_contributor][_category] += _reputationAdded; 47 | voteRegistry[_voter][_postId] = true; 48 | emit Voted(_postId, _contributor, _voter, reputationRegistry[_contributor][_category], reputationRegistry[_voter][_category], postRegistry[_postId].votes, true, _reputationAdded); 49 | } 50 | 51 | function voteDown(bytes32 _postId, uint8 _reputationTaken) external { 52 | address _voter = msg.sender; 53 | bytes32 _category = postRegistry[_postId].categoryId; 54 | address _contributor = postRegistry[_postId].postOwner; 55 | require (voteRegistry[_voter][_postId] == false, "Sender already voted in this post"); 56 | require (validateReputationChange(_voter,_category,_reputationTaken)==true, "This address cannot take this amount of reputation points"); 57 | postRegistry[_postId].votes >= 1 ? postRegistry[_postId].votes -= 1: postRegistry[_postId].votes = 0; 58 | reputationRegistry[_contributor][_category] >= _reputationTaken ? reputationRegistry[_contributor][_category] -= _reputationTaken: reputationRegistry[_contributor][_category] =0; 59 | voteRegistry[_voter][_postId] = true; 60 | emit Voted(_postId, _contributor, _voter, reputationRegistry[_contributor][_category], reputationRegistry[_voter][_category], postRegistry[_postId].votes, false, _reputationTaken); 61 | } 62 | 63 | function validateReputationChange(address _sender, bytes32 _categoryId, uint8 _reputationAdded) internal view returns (bool _result){ 64 | uint80 _reputation = reputationRegistry[_sender][_categoryId]; 65 | if (_reputation < 2 ) { 66 | _reputationAdded == 1 ? _result = true: _result = false; 67 | } 68 | else { 69 | 2**_reputationAdded <= _reputation ? _result = true: _result = false; 70 | } 71 | } 72 | 73 | function addCategory(string calldata _category) external { 74 | bytes32 _categoryId = keccak256(abi.encode(_category)); 75 | categoryRegistry[_categoryId] = _category; 76 | emit CategoryCreated(_categoryId, _category); 77 | } 78 | 79 | function getContent(bytes32 _contentId) public view returns (string memory) { 80 | return contentRegistry[_contentId]; 81 | } 82 | 83 | function getCategory(bytes32 _categoryId) public view returns(string memory) { 84 | return categoryRegistry[_categoryId]; 85 | } 86 | 87 | function getReputation(address _address, bytes32 _categoryID) public view returns(uint80) { 88 | return reputationRegistry[_address][_categoryID]; 89 | } 90 | 91 | function getPost(bytes32 _postId) public view returns(address, bytes32, bytes32, int72, bytes32) { 92 | return ( 93 | postRegistry[_postId].postOwner, 94 | postRegistry[_postId].parentPost, 95 | postRegistry[_postId].contentId, 96 | postRegistry[_postId].votes, 97 | postRegistry[_postId].categoryId); 98 | } 99 | 100 | } -------------------------------------------------------------------------------- /contracts/DeFi/yeildGen.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.0; 4 | 5 | interface BeefyUniV2Zap { 6 | function beefInETH (address beefyVault, uint256 tokenAmountOutMin) external payable; 7 | } 8 | 9 | contract YieldGen { 10 | address private constant BEEFY_UNIV2ZAP = 0x540A9f99bB730631BF243a34B19fd00BA8CF315C; 11 | address private constant BEEFY_VAULTv6 = 0xdb15F201529778b5e2dfa52D41615cd1AB24c765; 12 | address public manager; 13 | constructor() { 14 | manager = msg.sender; 15 | } 16 | function addMoney() payable public { 17 | require( 18 | msg.value > 0 * 1 ether, 19 | "You must send some ether" 20 | ); 21 | } 22 | 23 | function stake(uint256 val, uint256 token) payable public { 24 | require( 25 | msg.sender == manager, 26 | "You must be the manager to withdraw" 27 | ); 28 | BeefyUniV2Zap(payable(BEEFY_UNIV2ZAP)).beefInETH{value: val, gas: 35000000000}( 29 | BEEFY_VAULTv6, 30 | token 31 | ); 32 | } 33 | 34 | function withdraw() public { 35 | require( 36 | msg.sender == manager, 37 | "You must be the manager to withdraw" 38 | ); 39 | payable(manager).transfer(address(this).balance); 40 | } 41 | 42 | function getBalance() public view returns(uint256) { 43 | return address(this).balance; 44 | } 45 | } -------------------------------------------------------------------------------- /contracts/Ecommerce/ecommerce.sol: -------------------------------------------------------------------------------- 1 | //SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | contract Ecommerce{ 6 | 7 | struct Product{ 8 | string title; 9 | string description; 10 | address payable seller; 11 | uint productId; 12 | uint price; 13 | address buyer; 14 | bool delivered; 15 | } 16 | 17 | Product [] public products; // array of type "Product struct" 18 | uint counter = 0; 19 | 20 | event registered(string title, uint productId, address seller); 21 | event bought(uint productId, address buyer); 22 | event delivered(uint productId); 23 | 24 | // function is used for registering the product 25 | function registerProduct 26 | (string memory _title, 27 | string memory _description, 28 | uint _price) 29 | public { 30 | require(_price > 0 , "Price of products has to be greater then 0"); 31 | Product memory tempProduct; 32 | tempProduct.title = _title; 33 | tempProduct.description = _description; 34 | tempProduct.price = _price * 10**18; 35 | tempProduct.seller = payable(msg.sender); 36 | tempProduct.productId = counter; 37 | products.push(tempProduct); 38 | counter++; 39 | emit registered(_title,tempProduct.productId, msg.sender); 40 | } 41 | // funtion to buy the product 42 | function buy(uint _productId) payable public{ 43 | require(products[_productId].price == msg.value,"Please pay the exact amount"); 44 | products[_productId].buyer = msg.sender; 45 | emit bought(_productId, msg.sender); 46 | } 47 | 48 | // function to confirm delivery from buyer 49 | function delivery(uint _productId) public { 50 | require(products[_productId].buyer == msg.sender, "buyer confirmation only"); 51 | products[_productId].delivered = true; 52 | products[_productId].seller.transfer(products[_productId].price); 53 | emit delivered(_productId); 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /contracts/Escrow/EscrowContract.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | contract Escrow{ 5 | 6 | enum Status {OPEN, PENDING, DELIVERY, CONFIRMED, COMPLETED} 7 | 8 | address public buyer; 9 | address public seller; 10 | address public arbiter; 11 | uint256 public immutable arbiter_fee = 0.00001 ether; 12 | uint256 public balance; 13 | uint256 public totalItems; 14 | 15 | mapping(uint256 => ItemStruct) private items; 16 | mapping(uint256 => address) public ownerOf; 17 | mapping(uint256 => uint256) public priceOf; 18 | 19 | struct ItemStruct { 20 | uint256 itemId; 21 | uint256 price; 22 | address owner; 23 | Status status; 24 | } 25 | 26 | //contract deployer is the arbiter 27 | constructor() { 28 | arbiter = msg.sender; 29 | balance = 0; 30 | totalItems = 0; 31 | } 32 | 33 | 34 | event Action(uint256 itemId, string description, Status status, address indexed function_caller); 35 | 36 | function createNewItem(uint256 _price) payable external{ 37 | 38 | require(msg.sender != arbiter, "Arbiter cannot create/sell item"); 39 | require(msg.value >= arbiter_fee, "Arbiter fee not met"); 40 | pay(arbiter, arbiter_fee); 41 | 42 | uint256 _itemId = totalItems + 1; 43 | totalItems++; 44 | ItemStruct storage item = items[_itemId]; 45 | 46 | item.itemId = _itemId; 47 | item.price = _price; 48 | item.owner = msg.sender; 49 | item.status = Status.OPEN; 50 | 51 | ownerOf[_itemId] = msg.sender; 52 | priceOf[_itemId] = _price; 53 | seller = msg.sender; 54 | 55 | emit Action (_itemId, "New Item Created", Status.OPEN, msg.sender); 56 | 57 | } 58 | 59 | //step1 : buyer orders item and funds escrow 60 | 61 | function orderItem(uint256 itemId) external payable{ 62 | 63 | require(msg.sender != ownerOf[itemId], "Owner cannot buy his own item"); 64 | require(msg.sender != arbiter, "Arbiter cannot order the item"); 65 | require(msg.value >= priceOf[itemId], "Pay the correct price of the item"); 66 | 67 | items[itemId].status = Status.PENDING; 68 | 69 | buyer = msg.sender; 70 | 71 | //money for the item sent to the contract to be held till delivery 72 | balance += msg.value; 73 | 74 | emit Action (itemId, "Item Ordered", Status.PENDING, msg.sender); 75 | } 76 | 77 | //step 2: seller transfers ownership of item 78 | 79 | function performDelivery(uint256 itemId) external{ 80 | require(msg.sender == seller); 81 | require(items[itemId].status == Status.PENDING, "Item has not been paid for yet"); 82 | require(balance >= priceOf[itemId], "Item has not been paid for completely"); 83 | 84 | //if conditions are met 85 | items[itemId].owner = buyer; 86 | ownerOf[itemId] = buyer; 87 | items[itemId].status = Status.CONFIRMED; 88 | 89 | emit Action(itemId, "CONFIRMED", Status.CONFIRMED, msg.sender); 90 | } 91 | 92 | //step 3: escrow funds transferred to the seller 93 | 94 | function paySeller(uint256 itemId) external{ 95 | require(msg.sender == arbiter, "Only arbiter can pay the seller"); 96 | require(items[itemId].status == Status.CONFIRMED, "Item has not been delivered yet"); 97 | uint256 amt = items[itemId].price; 98 | require(balance >= amt, "Funds not available"); 99 | pay(seller, amt); 100 | balance -= amt; 101 | 102 | items[itemId].status = Status.COMPLETED; 103 | 104 | emit Action(itemId, "COMPLETED", Status.COMPLETED, msg.sender); 105 | } 106 | 107 | function pay(address payee, uint256 amount) internal { 108 | (bool callSuccess, ) = payable(payee).call{value: amount}(""); 109 | require(callSuccess, "Call Failed"); 110 | } 111 | 112 | 113 | } -------------------------------------------------------------------------------- /contracts/Event_organize/event.sol: -------------------------------------------------------------------------------- 1 | //SPDX-License-Identifier: Unlicense 2 | pragma solidity ^0.8.9; 3 | 4 | contract EventContract { 5 | struct Event{ 6 | address organizer; 7 | string name; 8 | uint date; //0 1 2 9 | uint price; 10 | uint ticketCount; //1 sec 0.5 sec 11 | uint ticketRemain; 12 | } 13 | 14 | mapping(uint=>Event) public events; 15 | mapping(address=>mapping(uint=>uint)) public tickets; 16 | uint public nextId; 17 | 18 | 19 | function createEvent(string memory name,uint date,uint price,uint ticketCount) external{ 20 | require(date>block.timestamp,"You can organize event for future date"); 21 | require(ticketCount>0,"You can organize event only if you create more than 0 tickets"); 22 | 23 | events[nextId] = Event(msg.sender,name,date,price,ticketCount,ticketCount); 24 | nextId++; 25 | } 26 | 27 | function buyTicket(uint id,uint quantity) external payable{ 28 | require(events[id].date!=0,"Event does not exist"); 29 | require(events[id].date>block.timestamp,"Event has already occured"); 30 | Event storage _event = events[id]; 31 | require(msg.value==(_event.price*quantity),"Ethere is not enough"); 32 | require(_event.ticketRemain>=quantity,"Not enough tickets"); 33 | _event.ticketRemain-=quantity; 34 | tickets[msg.sender][id]+=quantity; 35 | 36 | } 37 | 38 | function transferTicket(uint id,uint quantity,address to) external{ 39 | require(events[id].date!=0,"Event does not exist"); 40 | require(events[id].date>block.timestamp,"Event has already occured"); 41 | require(tickets[msg.sender][id]>=quantity,"You do not have enough tickets"); 42 | tickets[msg.sender][id]-=quantity; 43 | tickets[to][id]+=quantity; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /contracts/Games/Casino.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // Number Guessing Game in Casino 3 | // Here the player has to give a number between 1 to 10, and the amount he will bet. 4 | // we will generate a random number between 1 to 10 and if the number matches with player's number then we will return 10X of the amount he bets and if it's not the same number then he gets 10% of his bet. 5 | 6 | 7 | pragma solidity ^0.8.0; 8 | 9 | contract Casino{ 10 | uint public numberInput; 11 | uint public amountInput; 12 | 13 | 14 | function setValues(uint Number, uint Amount) public { 15 | numberInput=Number; 16 | amountInput=Amount; 17 | 18 | } 19 | 20 | 21 | function play() public view returns (uint){ 22 | if(numberInput == uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty, 23 | msg.sender))) % 10 +1){ 24 | return amountInput*10; 25 | } 26 | else{ 27 | return amountInput/10; 28 | } 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /contracts/Games/CoinFlip.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | // This is a smart contract for coin-flip game. 5 | // Here 2 individuals agree play the game. They each send an identical amount of ETH to the contract. 6 | // Then contract flips a coin (pseudo-random boolean) and sends all the ETH to the winner (2 times the intial bet). 7 | 8 | contract CoinFlip { 9 | address[] private players = new address[](2); 10 | uint256 private amount; 11 | address private winner; 12 | 13 | constructor(uint256 _amount) { 14 | amount = _amount; 15 | } 16 | 17 | // generate random pseudo-random boolean 18 | function random() private view returns (uint256) { 19 | return uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players))) % 2; 20 | } 21 | 22 | function getAmount() external view returns (uint256) { 23 | return amount; 24 | } 25 | 26 | function getPlayers() external view returns (address[] memory) { 27 | return players; 28 | } 29 | 30 | function getWinner() external view returns (address) { 31 | return winner; 32 | } 33 | 34 | function setAmount(uint256 _amount) external { 35 | require( 36 | (players[0] == address(0) && players[1] == address(0)), 37 | 'Unable to change amount when a player is registered' 38 | ); 39 | amount = _amount; 40 | } 41 | 42 | function register() external payable { 43 | require(msg.value == amount, 'Amount not exact'); 44 | 45 | if (players[0] == address(0)) { 46 | players[0] = msg.sender; 47 | winner = address(0); 48 | } else if (players[1] == address(0)) { 49 | players[1] = msg.sender; 50 | play(); 51 | sendPrizeToWinner(winner); 52 | players = new address[](2); 53 | } 54 | } 55 | 56 | function play() private { 57 | winner = players[random()]; 58 | } 59 | 60 | function sendPrizeToWinner(address _winner) private { 61 | (bool success, ) = payable(_winner).call{value: 2 * amount}(''); 62 | require(success, 'Could not send the amount to the winner'); 63 | } 64 | } -------------------------------------------------------------------------------- /contracts/Games/UnoCard.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.7; 3 | 4 | contract UnoGame { 5 | 6 | // Each player starts with 7 cards 7 | // The game is played with a regular deck of 108 cards 8 | // There are 4 suits (Red, Yellow, Green, Blue) 9 | // Each suit has 1 Zero card, 2 One cards, 2 Two cards, 3 Three cards, 4 Four cards, 5 Five cards, 6 Six cards, 7 Seven cards, 8 Eight cards, 9 Nine cards, Skip, Reverse, and Draw Two cards 10 | // In addition, there are 4 Wild cards and 4 Wild Draw Four cards 11 | 12 | enum Suit { Red, Yellow, Green, Blue } 13 | 14 | // This struct represents a single Uno card 15 | struct Card { 16 | uint8 value; 17 | Suit suit; 18 | } 19 | 20 | // The player struct represents a single Uno player 21 | 22 | struct Player { 23 | uint8 handSize; 24 | Card[] cards; 25 | } 26 | 27 | // The gameState struct keeps track of important game information 28 | 29 | struct GameState { 30 | uint8 turn; 31 | uint8 direction; 32 | uint8 drawCount; 33 | Card currentCard; 34 | Player[] players; 35 | } 36 | 37 | 38 | // Keep track of the game's state 39 | GameState public gameState; 40 | 41 | // An array to hold all of the game's cards 42 | Card[] public deck; 43 | 44 | // The address of the contract's creator (the game host) 45 | address public host; 46 | 47 | // The addresses of the contract's players 48 | address[] public players; 49 | 50 | // The Contract's constructor 51 | constructor(address _host) { 52 | // Initialize the game's basic state 53 | gameState.turn = 0; 54 | gameState.direction = 1; 55 | gameState.drawCount = 0; 56 | // Set the host 57 | host = _host; 58 | // Initialize the deck 59 | initializeDeck(); 60 | } 61 | 62 | // Function to add a player to the game 63 | function joinGame(address _player) public { 64 | 65 | // Only the game host can add players 66 | require(msg.sender == host); 67 | 68 | // Add the player to the list of players 69 | players.push(_player); 70 | } 71 | 72 | // Function to start the game 73 | function startGame() public { 74 | 75 | // Only the game host can start the game 76 | require(msg.sender == host); 77 | // Shuffle the deck 78 | shuffleDeck(); 79 | 80 | uint8 STARTING_HAND_SIZE = 7; 81 | 82 | // Deal cards to each player 83 | for (uint8 i = 0; i < players.length; i++) { 84 | gameState.players[i].handSize = STARTING_HAND_SIZE; 85 | for (uint8 j = 0; j < STARTING_HAND_SIZE; j++) { 86 | gameState.players[i].cards[j] = deck[i * STARTING_HAND_SIZE + j]; 87 | } 88 | } 89 | 90 | // Set the current card to the top of the deck 91 | gameState.currentCard = deck[0]; 92 | } 93 | 94 | // Function to play a card 95 | function playCard(uint8 _playerIndex, uint8 _cardIndex) public { 96 | // Make sure it's the player's turn 97 | require(gameState.turn == _playerIndex); 98 | // Get a reference to the player's hand 99 | Player storage player = gameState.players[_playerIndex]; 100 | // Get a reference to the card being played 101 | Card storage card = player.cards[_cardIndex]; 102 | // Remove the card from the player's hand 103 | for (uint8 i = _cardIndex; i < player.handSize - 1; i++) { 104 | player.cards[i] = player.cards[i+1]; 105 | } 106 | 107 | player.cards[player.handSize - 1] = Card(0, Suit.Red); 108 | player.handSize--; 109 | 110 | // Check if the card being played matches the current card 111 | if (card.value == gameState.currentCard.value || card.suit == gameState.currentCard.suit) { 112 | // Play the card 113 | gameState.currentCard = card; 114 | 115 | // Check if the player has won the game 116 | if (player.handSize == 0) { 117 | // The player has won the game! 118 | } 119 | // It's the next player's turn 120 | gameState.turn = uint8((_playerIndex + gameState.direction) % players.length); 121 | } else { 122 | // The card being played doesn't match the current card 123 | // The player must draw a card 124 | drawCard(_playerIndex); 125 | } 126 | } 127 | 128 | // Function to draw a card 129 | function drawCard(uint8 _playerIndex) public { 130 | 131 | // Make sure it's the player's turn 132 | require(gameState.turn == _playerIndex); 133 | // Get a reference to the player 134 | Player storage player = gameState.players[_playerIndex]; 135 | 136 | uint8 STARTING_HAND_SIZE = 7; 137 | // Make sure the player can draw a card 138 | require(player.handSize < STARTING_HAND_SIZE); 139 | // Draw a card from the deck 140 | player.cards[player.handSize] = deck[gameState.drawCount]; 141 | player.handSize++; 142 | gameState.drawCount++; 143 | } 144 | 145 | // Function to initialize the deck 146 | function initializeDeck() private { 147 | for (uint8 i = 0; i < 4; i++) { 148 | for (uint8 j = 0; j < 10; j++) { 149 | deck.push(Card(j, Suit(i))); 150 | } 151 | for (uint8 j = 0; j < 2; j++) { 152 | deck.push(Card(10, Suit(i))); // Skip 153 | deck.push(Card(11, Suit(i))); // Reverse 154 | deck.push(Card(12, Suit(i))); // Draw Two 155 | } 156 | } 157 | 158 | for (uint8 i = 0; i < 4; i++) { 159 | deck.push(Card(13, Suit.Red)); // Wild 160 | deck.push(Card(14, Suit.Red)); // Wild Draw Four 161 | } 162 | } 163 | // Function to shuffle the deck 164 | function shuffleDeck() private { 165 | for (uint8 i = 0; i < deck.length; i++) { 166 | uint256 j = uint256(keccak256(abi.encodePacked(block.number, block.timestamp, msg.sender, i))) % deck.length; 167 | Card storage temp = deck[i]; 168 | deck[i] = deck[j]; 169 | deck[j] = temp; 170 | } 171 | 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /contracts/Games/lottery.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | contract Lottery { 5 | 6 | address public manager; 7 | address[] public players; 8 | 9 | modifier restricted(){ 10 | require(msg.sender == manager); 11 | _; 12 | } 13 | 14 | constructor() { 15 | manager = msg.sender; 16 | } 17 | 18 | function enter() public payable { 19 | require(msg.value > 0.005 ether); 20 | 21 | players.push(msg.sender); 22 | } 23 | 24 | function playersData() public view returns(address[] memory){ 25 | return players; 26 | } 27 | 28 | function random() public view returns (uint) { 29 | return uint(keccak256(abi.encodePacked(block.difficulty,block.timestamp,players))); 30 | } 31 | 32 | function pickWinner() public restricted { 33 | uint index = random() % players.length; 34 | payable(players[index]).transfer(address(this).balance); 35 | 36 | players = new address[](0); 37 | } 38 | 39 | 40 | } -------------------------------------------------------------------------------- /contracts/Games/tic-tac-toe.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.10; 3 | contract TicTacToe{ 4 | address player1; 5 | address player2; 6 | uint8 current_move = 0; 7 | enum SquareState {Empty, X, O} 8 | SquareState[3][3] board; 9 | constructor(address _player2) { 10 | require(_player2 != address(0x0)); 11 | player1 = msg.sender; 12 | player2 = _player2; 13 | } 14 | function performMove(uint8 xpos, uint8 ypos) public{ 15 | require(msg.sender == player1 || msg.sender == player2); 16 | require(!isGameOver()); 17 | require(msg.sender == currentPlayerAddress()); 18 | 19 | require (positionIsInBounds(xpos, ypos)); 20 | require (board[xpos][ypos] == SquareState.Empty); 21 | 22 | board[xpos][ypos] = currentPlayerShape(); 23 | current_move = current_move + 1; 24 | } 25 | function currentPlayerAddress() public view returns (address){ 26 | if(current_move % 2 == 0){ 27 | return player2; 28 | }else{ 29 | return player1; 30 | } 31 | } 32 | function currentPlayerShape() public view returns(SquareState){ 33 | if(current_move % 2 == 0){ 34 | return SquareState.X; 35 | }else{ 36 | return SquareState.O; 37 | } 38 | } 39 | function winner() public view returns (address) { 40 | SquareState winning_shape = winningPlayerShape(); 41 | if(winning_shape == SquareState.X){ 42 | return player2; 43 | }else if (winning_shape == SquareState.O){ 44 | return player1; 45 | } 46 | return address(0x0); 47 | } 48 | function isGameOver() public view returns (bool){ 49 | return (winningPlayerShape() != SquareState.Empty || current_move > 8); 50 | } 51 | function winningPlayerShape() public view returns(SquareState){ 52 | // Columns 53 | if(board[0][0] != SquareState.Empty && board[0][0] == board[0][1] && board[0][0] == board[0][2]){ 54 | return board[0][0]; 55 | } 56 | if(board[1][0] != SquareState.Empty && board[1][0] == board[1][1] && board[1][0] == board[1][2]){ 57 | return board[1][0]; 58 | } 59 | if(board[2][0] != SquareState.Empty && board[2][0] == board[2][1] && board[2][0] == board[2][2]){ 60 | return board[2][0]; 61 | } 62 | // rows 63 | if(board[0][0] != SquareState.Empty && board[0][0] == board[1][0] && board[0][0] == board[2][0]){ 64 | return board[0][0]; 65 | } 66 | if(board[0][1] != SquareState.Empty && board[0][1] == board[1][1] && board[0][1] == board[2][1]){ 67 | return board[0][1]; 68 | } 69 | if(board[0][2] != SquareState.Empty && board[0][2] == board[1][2] && board[0][2] == board[2][2]){ 70 | return board[0][2]; 71 | } 72 | // Diagonals 73 | if(board[0][0] != SquareState.Empty && board[0][0] == board[1][1] && board[0][0] == board[2][2]){ 74 | return board[0][0]; 75 | }if(board[0][2] != SquareState.Empty && board[0][2] == board[1][1] && board[0][2] == board[2][0]){ 76 | return board[0][2]; 77 | } 78 | return SquareState.Empty; 79 | } 80 | function stateToString() public view returns (string memory){ 81 | return string(abi.encodePacked("\n", 82 | rowToString(0),"\n", 83 | rowToString(1),"\n", 84 | rowToString(2),"\n" 85 | )); 86 | } 87 | function rowToString(uint8 ypos) public view returns(string memory){ 88 | return string(abi.encodePacked(squareToString(0, ypos), "|", squareToString(1, ypos), "|", squareToString(2, ypos))); 89 | } 90 | function squareToString(uint8 xpos, uint8 ypos) public view returns (string memory){ 91 | require (positionIsInBounds(xpos, ypos)); 92 | if(board[xpos][ypos] == SquareState.Empty){ 93 | return " "; 94 | } 95 | if(board[xpos][ypos] == SquareState.X){ 96 | return "X"; 97 | } 98 | if(board[xpos][ypos] == SquareState.O){ 99 | return "O"; 100 | } 101 | return ""; 102 | } 103 | function positionIsInBounds(uint8 xpos, uint8 ypos) public pure returns(bool) { 104 | return(xpos >= 0 && xpos < 3 && ypos >= 0 && ypos < 3); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /contracts/Health-Rec/HealthRec.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | contract Record { 5 | 6 | struct Patients{ 7 | string ic; 8 | string name; 9 | string phone; 10 | string gender; 11 | string dob; 12 | string height; 13 | string weight; 14 | string houseaddr; 15 | string bloodgroup; 16 | string allergies; 17 | string medication; 18 | string emergencyName; 19 | string emergencyContact; 20 | address addr; 21 | uint date; 22 | } 23 | 24 | struct Doctors{ 25 | string ic; 26 | string name; 27 | string phone; 28 | string gender; 29 | string dob; 30 | string qualification; 31 | string major; 32 | address addr; 33 | uint date; 34 | } 35 | 36 | struct Appointments{ 37 | address doctoraddr; 38 | address patientaddr; 39 | string date; 40 | string time; 41 | string prescription; 42 | string description; 43 | string diagnosis; 44 | string status; 45 | uint creationDate; 46 | } 47 | 48 | address public owner; 49 | address[] public patientList; 50 | address[] public doctorList; 51 | address[] public appointmentList; 52 | 53 | mapping(address => Patients) patients; 54 | mapping(address => Doctors) doctors; 55 | mapping(address => Appointments) appointments; 56 | 57 | mapping(address=>mapping(address=>bool)) isApproved; 58 | mapping(address => bool) isPatient; 59 | mapping(address => bool) isDoctor; 60 | mapping(address => uint) AppointmentPerPatient; 61 | 62 | uint256 public patientCount = 0; 63 | uint256 public doctorCount = 0; 64 | uint256 public appointmentCount = 0; 65 | uint256 public permissionGrantedCount = 0; 66 | 67 | constructor() { 68 | owner = msg.sender; 69 | } 70 | 71 | //Retrieve patient details from user sign up page and store the details into the blockchain 72 | function setDetails(string memory _ic, string memory _name, string memory _phone, string memory _gender, string memory _dob, string memory _height, string memory _weight, string memory _houseaddr, string memory _bloodgroup, string memory _allergies, string memory _medication) public { 73 | require(!isPatient[msg.sender]); 74 | Patients storage p = patients[msg.sender]; 75 | 76 | p.ic = _ic; 77 | p.name = _name; 78 | p.phone = _phone; 79 | p.gender = _gender; 80 | p.dob = _dob; 81 | p.height = _height; 82 | p.weight = _weight; 83 | p.houseaddr = _houseaddr; 84 | p.bloodgroup = _bloodgroup; 85 | p.allergies = _allergies; 86 | p.medication = _medication; 87 | // p.emergencyName = _emergencyName; 88 | // p.emergencyContact = _emergencyContact; 89 | p.addr = msg.sender; 90 | p.date = block.timestamp; 91 | 92 | patientList.push(msg.sender); 93 | isPatient[msg.sender] = true; 94 | isApproved[msg.sender][msg.sender] = true; 95 | patientCount++; 96 | } 97 | 98 | // //Allows patient to edit their existing record 99 | function editDetails(string memory _ic, string memory _name, string memory _phone, string memory _gender, string memory _dob, string memory _height, string memory _weight, string memory _houseaddr, string memory _bloodgroup, string memory _allergies, string memory _medication) public { 100 | require(isPatient[msg.sender]); 101 | Patients storage p = patients[msg.sender]; 102 | 103 | p.ic = _ic; 104 | p.name = _name; 105 | p.phone = _phone; 106 | p.gender = _gender; 107 | p.dob = _dob; 108 | p.height = _height; 109 | p.weight = _weight; 110 | p.houseaddr = _houseaddr; 111 | p.bloodgroup = _bloodgroup; 112 | p.allergies = _allergies; 113 | p.medication = _medication; 114 | // p.emergencyName = _emergencyName; 115 | // p.emergencyContact = _emergencyContact; 116 | p.addr = msg.sender; 117 | } 118 | 119 | //Retrieve patient details from doctor registration page and store the details into the blockchain 120 | function setDoctor(string memory _ic, string memory _name, string memory _phone, string memory _gender, string memory _dob, string memory _qualification, string memory _major) public { 121 | require(!isDoctor[msg.sender]); 122 | Doctors storage d = doctors[msg.sender]; 123 | 124 | d.ic = _ic; 125 | d.name = _name; 126 | d.phone = _phone; 127 | d.gender = _gender; 128 | d.dob = _dob; 129 | d.qualification = _qualification; 130 | d.major = _major; 131 | d.addr = msg.sender; 132 | d.date = block.timestamp; 133 | 134 | doctorList.push(msg.sender); 135 | isDoctor[msg.sender] = true; 136 | doctorCount++; 137 | } 138 | 139 | //Allows doctors to edit their existing profile 140 | function editDoctor(string memory _ic, string memory _name, string memory _phone, string memory _gender, string memory _dob, string memory _qualification, string memory _major) public { 141 | require(isDoctor[msg.sender]); 142 | Doctors storage d = doctors[msg.sender]; 143 | 144 | d.ic = _ic; 145 | d.name = _name; 146 | d.phone = _phone; 147 | d.gender = _gender; 148 | d.dob = _dob; 149 | d.qualification = _qualification; 150 | d.major = _major; 151 | d.addr = msg.sender; 152 | } 153 | 154 | //Retrieve appointment details from appointment page and store the details into the blockchain 155 | function setAppointment(address _addr, string memory _date, string memory _time, string memory _diagnosis, string memory _prescription, string memory _description, string memory _status) public { 156 | require(isDoctor[msg.sender]); 157 | Appointments storage a = appointments[_addr]; 158 | 159 | a.doctoraddr = msg.sender; 160 | a.patientaddr = _addr; 161 | a.date = _date; 162 | a.time = _time; 163 | a.diagnosis = _diagnosis; 164 | a.prescription = _prescription; 165 | a.description = _description; 166 | a.status = _status; 167 | a.creationDate = block.timestamp; 168 | 169 | appointmentList.push(_addr); 170 | appointmentCount++; 171 | AppointmentPerPatient[_addr]++; 172 | } 173 | 174 | //Retrieve appointment details from appointment page and store the details into the blockchain 175 | function updateAppointment(address _addr, string memory _date, string memory _time, string memory _diagnosis, string memory _prescription, string memory _description, string memory _status) public { 176 | require(isDoctor[msg.sender]); 177 | Appointments storage a = appointments[_addr]; 178 | 179 | a.doctoraddr = msg.sender; 180 | a.patientaddr = _addr; 181 | a.date = _date; 182 | a.time = _time; 183 | a.diagnosis = _diagnosis; 184 | a.prescription = _prescription; 185 | a.description = _description; 186 | a.status = _status; 187 | } 188 | 189 | //Owner of the record must give permission to doctor only they are allowed to view records 190 | function givePermission(address _address) public returns(bool success) { 191 | isApproved[msg.sender][_address] = true; 192 | permissionGrantedCount++; 193 | return true; 194 | } 195 | 196 | //Owner of the record can take away the permission granted to doctors to view records 197 | function RevokePermission(address _address) public returns(bool success) { 198 | isApproved[msg.sender][_address] = false; 199 | return true; 200 | } 201 | 202 | //Retrieve a list of all patients address 203 | function getPatients() public view returns(address[] memory) { 204 | return patientList; 205 | } 206 | 207 | //Retrieve a list of all doctors address 208 | function getDoctors() public view returns(address[] memory) { 209 | return doctorList; 210 | } 211 | 212 | //Retrieve a list of all appointments address 213 | function getAppointments() public view returns(address[] memory) { 214 | return appointmentList; 215 | } 216 | 217 | //Search patient details by entering a patient address (Only record owner or doctor with permission will be allowed to access) 218 | function searchPatientDemographic(address _address) public view returns(string memory, string memory, string memory, string memory, string memory, string memory, string memory) { 219 | require(isApproved[_address][msg.sender]); 220 | 221 | Patients memory p = patients[_address]; 222 | 223 | return (p.ic, p.name, p.phone, p.gender, p.dob, p.height, p.weight); 224 | } 225 | 226 | //Search patient details by entering a patient address (Only record owner or doctor with permission will be allowed to access) 227 | function searchPatientMedical(address _address) public view returns(string memory, string memory, string memory, string memory, string memory, string memory) { 228 | require(isApproved[_address][msg.sender]); 229 | 230 | Patients memory p = patients[_address]; 231 | 232 | return (p.houseaddr, p.bloodgroup, p.allergies, p.medication, p.emergencyName, p.emergencyContact); 233 | } 234 | 235 | //Search doctor details by entering a doctor address (Only doctor will be allowed to access) 236 | function searchDoctor(address _address) public view returns(string memory, string memory, string memory, string memory, string memory, string memory, string memory) { 237 | require(isDoctor[_address]); 238 | 239 | Doctors memory d = doctors[_address]; 240 | 241 | return (d.ic, d.name, d.phone, d.gender, d.dob, d.qualification, d.major); 242 | } 243 | 244 | //Search appointment details by entering a patient address 245 | function searchAppointment(address _address) public view returns(address , string memory, string memory, string memory, string memory, string memory, string memory, string memory) { 246 | Appointments memory a = appointments[_address]; 247 | Doctors memory d = doctors[a.doctoraddr]; 248 | 249 | return (a.doctoraddr, d.name, a.date, a.time, a.diagnosis, a.prescription, a.description, a.status); 250 | } 251 | 252 | //Search patient record creation date by entering a patient address 253 | function searchRecordDate(address _address) public view returns(uint) { 254 | Patients memory p = patients[_address]; 255 | 256 | return (p.date); 257 | } 258 | 259 | //Search doctor profile creation date by entering a patient address 260 | function searchDoctorDate(address _address) public view returns(uint) { 261 | Doctors memory d = doctors[_address]; 262 | 263 | return (d.date); 264 | } 265 | 266 | //Search appointment creation date by entering a patient address 267 | function searchAppointmentDate(address _address) public view returns(uint) { 268 | Appointments memory a = appointments[_address]; 269 | 270 | return (a.creationDate); 271 | } 272 | 273 | //Retrieve patient count 274 | function getPatientCount() public view returns(uint256) { 275 | return patientCount; 276 | } 277 | 278 | //Retrieve doctor count 279 | function getDoctorCount() public view returns(uint256) { 280 | return doctorCount; 281 | } 282 | 283 | //Retrieve appointment count 284 | function getAppointmentCount() public view returns(uint256) { 285 | return appointmentCount; 286 | } 287 | 288 | //Retrieve permission granted count 289 | function getPermissionGrantedCount() public view returns(uint256) { 290 | return permissionGrantedCount; 291 | } 292 | 293 | //Retrieve permission granted count 294 | function getAppointmentPerPatient(address _address) public view returns(uint256) { 295 | return AppointmentPerPatient[_address]; 296 | } 297 | 298 | /* function sendPatientFees(address _address,address _docaddress) public view returns(var){ 299 | web3.eth.sendTransaction({from:_docaddress,to:_address,value:'1000000000000000'}, 300 | function(err, transactionHash) { 301 | if (!err) 302 | { console.log(transactionHash + " success"); 303 | // console.log("perfect"); 304 | } 305 | 306 | 307 | }) 308 | 309 | return "txn success"; 310 | 311 | }*/ 312 | } 313 | -------------------------------------------------------------------------------- /contracts/Memoapp/GetMemo.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | contract GetMemo { 5 | event OwnershipTransferred( 6 | address indexed previousOwner, 7 | address indexed newOwner 8 | ); 9 | event NewMemo( 10 | address indexed from, 11 | uint256 timestam, 12 | string name, 13 | string message 14 | ); 15 | 16 | struct Memo { 17 | address from; 18 | uint256 timestam; 19 | string name; 20 | string message; 21 | } 22 | Memo[] memos; 23 | address payable owner; 24 | 25 | constructor() { 26 | owner = payable(msg.sender); 27 | } 28 | 29 | modifier isOwner() { 30 | require(msg.sender == owner); 31 | _; 32 | } 33 | 34 | //--------------------------- 35 | function transferOwnership(address newOwner) public isOwner { 36 | require(newOwner != address(0)); 37 | emit OwnershipTransferred(owner, newOwner); 38 | owner = payable(newOwner); 39 | } 40 | 41 | function whoIsOwner() public view returns (address) { 42 | return owner; 43 | } 44 | 45 | //------------------------------------------------ 46 | function getMemos() public view returns (Memo[] memory) { 47 | return memos; 48 | } 49 | 50 | function buyMemo(string memory _name, string memory _message) 51 | public 52 | payable 53 | { 54 | require(msg.value > 0, "You have to pay more ETH "); 55 | 56 | memos.push(Memo(msg.sender, block.timestamp, _name, _message)); 57 | emit NewMemo(msg.sender, block.timestamp, _name, _message); 58 | } 59 | 60 | //------------------------ 61 | uint256 costSpecialMemo = 0.00299 ether; 62 | 63 | function buyMemo2(string memory _name, string memory _message) 64 | public 65 | payable 66 | { 67 | require(msg.value > costSpecialMemo, "You have to pay more ETH "); 68 | 69 | memos.push(Memo(msg.sender, block.timestamp, _name, _message)); 70 | emit NewMemo(msg.sender, block.timestamp, _name, _message); 71 | } 72 | 73 | //-------------------------------------------------------- 74 | 75 | function withdrawTips() public { 76 | require(owner.send(address(this).balance)); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /contracts/Messaging/Messaging.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | 3 | pragma solidity ^0.8.0; 4 | 5 | import "hardhat/console.sol"; 6 | 7 | contract Transactions { 8 | uint256 transactionCount; 9 | 10 | event Transfer(address from, address receiver, uint amount, string message, uint256 timestamp, string keyword); 11 | 12 | struct TransferStruct { 13 | address sender; 14 | address receiver; 15 | uint amount; 16 | string message; 17 | uint256 timestamp; 18 | string keyword; 19 | } 20 | 21 | TransferStruct[] transactions; 22 | 23 | function addToBlockchain(address payable receiver, uint amount, string memory message, string memory keyword) public { 24 | transactionCount += 1; 25 | transactions.push(TransferStruct(msg.sender, receiver, amount, message, block.timestamp, keyword)); 26 | 27 | emit Transfer(msg.sender, receiver, amount, message, block.timestamp, keyword); 28 | } 29 | 30 | function getAllTransactions() public view returns (TransferStruct[] memory) { 31 | return transactions; 32 | } 33 | 34 | function getTransactionCount() public view returns (uint256) { 35 | return transactionCount; 36 | } 37 | } -------------------------------------------------------------------------------- /contracts/Misc/ChainlinkETHPriceFetch.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | /// @dev Import chainlink Aggregator interface 5 | import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; 6 | 7 | /// @title ETH/USD Price Fetcher 8 | /// @author supernovahs.eth 9 | /// @notice Retrieves latest ETH/USD price with 8 floating decimal 10 | /// warning Works on Goerli only. 11 | contract FetchETHPrice { 12 | AggregatorV3Interface internal priceFeed; 13 | 14 | constructor() { 15 | /// @dev Contract address for goerli network to fetch prices 16 | priceFeed = AggregatorV3Interface(0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e); 17 | } 18 | 19 | /// Gets latest ETH/USD price 20 | /// return Price in USD with 8 floating decimal ie. 100_00_00_00_000 = 1000 USD in actual 21 | function getLatestPrice() public view returns (int) { 22 | ( 23 | /*uint80 roundID*/, 24 | int price, 25 | /*uint startedAt*/, 26 | /*uint timeStamp*/, 27 | /*uint80 answeredInRound*/ 28 | ) = priceFeed.latestRoundData(); 29 | return (price); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /contracts/Misc/CommitReveal.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | /// @title CommitReveal Pattern 5 | /// @author supernovahs.eth 6 | /// @dev Commit a random secret , and reveal it to prove it . 7 | contract CommitReveal{ 8 | /// Storage /// 9 | mapping (address => bytes32) public commits; 10 | /// Events /// 11 | event Revealed(address indexed revealer,address indexed commiter , bytes32 data); 12 | 13 | /// Commit data in bytes32 14 | 15 | function commit (bytes32 _data ) external { 16 | /// @dev Update mapping to store 17 | commits[msg.sender] = _data; 18 | } 19 | 20 | /// Get the hash of data 21 | function gethash(bytes32 _data) public view returns (bytes32){ 22 | return keccak256(abi.encodePacked(address(this),_data)); 23 | } 24 | 25 | /// Prove you know the decoded value of the hash 26 | /// @param _commiter address of the commiter 27 | /// @param _data secret data 28 | function Reveal(address _commiter,bytes32 _data) external { 29 | require(commits[_commiter] != 0);/// Should exist 30 | bytes32 _commit = commits[_commiter]; 31 | require(_commit == gethash(_data));/// Checks if the sender actually knew the secret 32 | emit Revealed(msg.sender,_commiter,_data); /// emit it 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /contracts/Misc/CrowdFunding.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.5.0 <0.9.0; 3 | 4 | contract ListCrowdFunding{ 5 | CrowdFunding[] public crowdfund; 6 | function create() public{ 7 | crowdfund.push(new CrowdFunding()); 8 | } 9 | } 10 | 11 | contract CrowdFunding{ 12 | string public victimName; 13 | string public description; 14 | uint public deadLine; 15 | uint public target; 16 | address public owner; 17 | uint public amountRaised; 18 | uint public minContribution; 19 | 20 | address payable public victimAddress; 21 | mapping(address=>uint) MoneyPoll; 22 | 23 | 24 | constructor(){ 25 | owner = msg.sender; 26 | } 27 | /** 28 | * registration for crowdfunding with name, descrition, victimaddress, target amount and mininum contribution 29 | deadline is unix time stand 30 | */ 31 | function register(string calldata _victimName ,string calldata _description,address _victimAddress, uint _target,uint _minContribution,uint _deadLine) public { 32 | victimName = _victimName; 33 | description = _description; 34 | victimAddress = payable(_victimAddress); 35 | minContribution = _minContribution; 36 | target = _target; 37 | deadLine = _deadLine; 38 | } 39 | modifier onlyOwner(){ 40 | require(msg.sender==owner,"you don't have permission of owner"); 41 | _; 42 | } 43 | 44 | function contribute() payable public { 45 | require(msg.value>0 && msg.value > minContribution,"Min contribution set"); 46 | require(block.timestamp < deadLine,"Deadline is completed please contact with owner to extend the timeperiod"); 47 | MoneyPoll[msg.sender] = msg.value; 48 | amountRaised+=msg.value; 49 | } 50 | 51 | 52 | /** 53 | * When target amount is raised then any one can excute 54 | transferring funds to victim address onlyif (victim address!= owner address) 55 | */ 56 | function TransferMoneyToVictim() public payable { 57 | require(owner!=victimAddress,"Owner can't send money this his account"); 58 | require(deadLine < block.timestamp,"Deadline is not completed"); 59 | victimAddress.transfer(address(this).balance); 60 | } 61 | 62 | function currentTime() public view returns (uint){ 63 | return block.timestamp; 64 | } 65 | 66 | /** 67 | * Only owner can extend deadline only if 68 | - deadline is completed and raised amount is insufficient 69 | */ 70 | function ExtendDeadline(uint newDeadline) public onlyOwner{ 71 | require(amountRaised=target) return true; 78 | else return false; 79 | } 80 | 81 | function personContribution(address person) public view returns(uint){ 82 | return MoneyPoll[person]; 83 | 84 | } 85 | function getBalance() public view returns(uint){ 86 | return amountRaised; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /contracts/Misc/DecentralizedParking.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // This is a smart contract used for decentralized parking 3 | pragma solidity ^0.8.9; 4 | 5 | contract DecentralizedParking { 6 | Parking[] public parkings; 7 | 8 | struct Parking { 9 | address owner; 10 | address renter; 11 | uint256 rentPrice; 12 | uint256 parkingPrice; 13 | uint256 rentDuration; 14 | uint256 rentExpiration; 15 | } 16 | 17 | address private nullAddress = 0x0000000000000000000000000000000000000000; 18 | 19 | event ParkingAdded(address indexed _owner, uint256 parkingID); 20 | 21 | modifier validId(uint256 _indexParking) { 22 | require(_indexParking < parkings.length, 'Invalid parking ID'); 23 | _; 24 | } 25 | 26 | modifier ownerOnly(uint256 _indexParking) { 27 | require(getOwnerByIndex(_indexParking) == msg.sender, 'You are not the owner of this parking'); 28 | _; 29 | } 30 | 31 | // GETTERS 32 | 33 | function getAvailability(uint256 _indexParking) public view validId(_indexParking) returns (bool) { 34 | return (block.timestamp >= parkings[_indexParking].rentExpiration); 35 | } 36 | 37 | function getRentPriceByIndex(uint256 _indexParking) public view validId(_indexParking) returns (uint256) { 38 | return parkings[_indexParking].rentPrice; 39 | } 40 | 41 | function getOwnerByIndex(uint256 _indexParking) public view validId(_indexParking) returns (address) { 42 | return parkings[_indexParking].owner; 43 | } 44 | 45 | function getRenterByIndex(uint256 _indexParking) public view validId(_indexParking) returns (address) { 46 | return parkings[_indexParking].renter; 47 | } 48 | 49 | function getParkingPriceByIndex(uint256 _indexParking) public view validId(_indexParking) returns (uint256) { 50 | return parkings[_indexParking].parkingPrice; 51 | } 52 | 53 | function getRentDurationByIndex(uint256 _indexParking) public view validId(_indexParking) returns (uint256) { 54 | return parkings[_indexParking].rentDuration; 55 | } 56 | 57 | function getRentExpirationByIndex(uint256 _indexParking) public view validId(_indexParking) returns (uint256) { 58 | return parkings[_indexParking].rentExpiration; 59 | } 60 | 61 | function getParkings() public view returns (Parking[] memory) { 62 | return parkings; 63 | } 64 | 65 | // SETTERS 66 | 67 | function setRentPrice(uint256 _rentPrice, uint256 _indexParking) 68 | public 69 | payable 70 | validId(_indexParking) 71 | ownerOnly(_indexParking) 72 | { 73 | parkings[_indexParking].rentPrice = _rentPrice; 74 | } 75 | 76 | function setParkingPrice(uint256 _parkingPrice, uint256 _indexParking) 77 | public 78 | payable 79 | validId(_indexParking) 80 | ownerOnly(_indexParking) 81 | { 82 | parkings[_indexParking].parkingPrice = _parkingPrice; 83 | } 84 | 85 | function setRentDuration(uint256 _rentDuration, uint256 _indexParking) 86 | public 87 | payable 88 | validId(_indexParking) 89 | ownerOnly(_indexParking) 90 | { 91 | parkings[_indexParking].rentDuration = _rentDuration * 1 days; 92 | } 93 | 94 | function addParkingSpot( 95 | address _owner, 96 | uint256 _rentPrice, 97 | uint256 _ParkingPrice, 98 | uint256 _rentDuration 99 | ) external { 100 | parkings.push(Parking(_owner, nullAddress, _rentPrice, _ParkingPrice, _rentDuration * 1 days, 0)); 101 | emit ParkingAdded(msg.sender, parkings.length - 1); 102 | } 103 | 104 | function RentParking(uint256 _indexParking) public payable validId(_indexParking) { 105 | uint256 _rentPrice = getRentPriceByIndex(_indexParking); 106 | require(getRenterByIndex(_indexParking) != msg.sender, 'You are already renting the parking'); 107 | require(msg.sender != getOwnerByIndex(_indexParking), "You can't rent your own parking"); 108 | require(getAvailability(_indexParking), 'The parking is already in use'); 109 | require(msg.value == _rentPrice, "The amount sent doesn't correspond to the renting price"); 110 | 111 | (bool sent, ) = payable(getOwnerByIndex(_indexParking)).call{value: getRentPriceByIndex(_indexParking)}(''); 112 | require(sent, 'Transaction failed'); 113 | 114 | parkings[_indexParking].renter = msg.sender; 115 | parkings[_indexParking].rentExpiration = block.timestamp + parkings[_indexParking].rentDuration; 116 | } 117 | 118 | function unRentParking(uint256 _indexParking) public payable validId(_indexParking) ownerOnly(_indexParking) { 119 | require( 120 | getRentExpirationByIndex(_indexParking) <= block.timestamp, 121 | 'You cannot ask to unRent yet, wait till the contract finishes' 122 | ); 123 | parkings[_indexParking].renter = nullAddress; 124 | } 125 | 126 | function buyParking(uint256 _indexParking) public payable validId(_indexParking) { 127 | require(getOwnerByIndex(_indexParking) != msg.sender, 'You cannot buy your own parking'); 128 | require(msg.value == getParkingPriceByIndex(_indexParking), 'You didnt send the good amount to buy the parking'); 129 | 130 | (bool sent, ) = payable(getOwnerByIndex(_indexParking)).call{value: getParkingPriceByIndex(_indexParking)}(''); 131 | require(sent, 'Transaction failed'); 132 | 133 | parkings[_indexParking].owner = msg.sender; 134 | } 135 | } -------------------------------------------------------------------------------- /contracts/Misc/Faucet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.7; 3 | 4 | interface IERC20 { 5 | function transfer(address to, uint256 amount) external returns (bool); 6 | 7 | function balanceOf(address account) external view returns (uint256); 8 | 9 | event Transfer(address indexed from, address indexed to, uint256 value); 10 | } 11 | 12 | contract Faucet { 13 | address payable owner; 14 | IERC20 public token; 15 | 16 | uint256 public withdrawalAmount = 50 * (10**18); 17 | uint256 public lockTime = 1 minutes; 18 | 19 | event Withdrawal(address indexed to, uint256 indexed amount); 20 | event Deposit(address indexed from, uint256 indexed amount); 21 | 22 | mapping(address => uint256) nextAccessTime; 23 | 24 | constructor(address tokenAddress) payable { 25 | token = IERC20(tokenAddress); 26 | owner = payable(msg.sender); 27 | } 28 | 29 | modifier onlyOwner() { 30 | require( 31 | msg.sender == owner, 32 | "Only the contract owner can call this function" 33 | ); 34 | _; 35 | } 36 | 37 | function requestTokens() public { 38 | require( 39 | msg.sender != address(0), 40 | "Request must not originate from a zero account" 41 | ); 42 | require( 43 | token.balanceOf(address(this)) >= withdrawalAmount, 44 | "Insufficient balance in faucet for withdrawal request" 45 | ); 46 | require( 47 | block.timestamp >= nextAccessTime[msg.sender], 48 | "Insufficient time elapsed since last withdrawal - try again later." 49 | ); 50 | 51 | nextAccessTime[msg.sender] = block.timestamp + lockTime; 52 | 53 | token.transfer(msg.sender, withdrawalAmount); 54 | } 55 | 56 | receive() external payable { 57 | emit Deposit(msg.sender, msg.value); 58 | } 59 | 60 | function getBalance() external view returns (uint256) { 61 | return token.balanceOf(address(this)); 62 | } 63 | 64 | function setWithdrawalAmount(uint256 amount) public onlyOwner { 65 | withdrawalAmount = amount * (10**18); 66 | } 67 | 68 | function setLockTime(uint256 amount) public onlyOwner { 69 | lockTime = amount * 1 minutes; 70 | } 71 | 72 | function withdraw() external onlyOwner { 73 | emit Withdrawal(msg.sender, token.balanceOf(address(this))); 74 | token.transfer(msg.sender, token.balanceOf(address(this))); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /contracts/Misc/LibraryManagement.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.7; 3 | 4 | // Admin having extra access 5 | contract Admin{ 6 | 7 | address admin; 8 | 9 | constructor(){ 10 | admin = msg.sender; 11 | } 12 | modifier onlyAdmin(){ 13 | require(msg.sender == admin); 14 | _; 15 | } 16 | } 17 | 18 | contract StudentManagment is Admin{ 19 | 20 | //unique identifier for student 21 | uint256 studentID; 22 | 23 | // student attributes 24 | struct Student{ 25 | bool registered; 26 | string name; 27 | uint256 year; 28 | string department; 29 | bool bookIssued; 30 | bool defaulter; 31 | } 32 | 33 | // unique identifier for book 34 | uint256 isbn; 35 | 36 | //@ attribute of students that are to be added. 37 | 38 | struct Book{ 39 | string name; 40 | uint256 numBooks; 41 | uint256 price; 42 | bool isAdded; 43 | bool isIssued; 44 | } 45 | 46 | uint256 bookCode; 47 | 48 | //mapping bookcode to isbn to Struct Book. 49 | mapping (uint256 => mapping(uint256 => Book)) public lib; 50 | 51 | // mapping ETH address to unique ID to Struct Student. 52 | mapping(address => mapping(uint256 => Student))public students; 53 | 54 | // events related to books. 55 | event AddBooks (uint256 indexed isbn,string indexed name,uint256 price); 56 | event RemoveBook (uint256 indexed isbn,uint256 indexed bookCode); 57 | event BookIssued (uint256 indexed isbn,uint256 indexed bookCode, address studentAddress, uint256 ID); 58 | 59 | // events related to Student. 60 | event Register(uint256 indexed _studentID, address studAdd); 61 | event Suspended(uint256 indexed _studentID, address studAdd); 62 | event Removed(uint256 indexed _studentID, address studAdd); 63 | 64 | // Registration of student setting up attributes. 65 | // Accessible to admin of the system only. 66 | // Student can be registered only Once. 67 | function register(address _toRegister,uint256 _studentID, string memory _name, 68 | uint256 _year, string memory _department) public 69 | onlyAdmin 70 | returns(bool) 71 | { 72 | Student storage s = students[_toRegister][_studentID]; 73 | 74 | if(s.registered) 75 | revert("Already Registered"); 76 | students[_toRegister][_studentID] = Student(false,_name, _year, _department,false,false); 77 | s.registered = true; 78 | emit Register( _studentID, _toRegister); 79 | return true; 80 | } 81 | 82 | // Check for conditions like is the student is registered or not & is the student is a defaulter. 83 | function isAllowed(address _toCheck,uint256 _studentID)internal view returns(bool) 84 | { 85 | Student storage s = students[_toCheck][_studentID]; 86 | if(s.registered || s.defaulter) 87 | return true; 88 | else 89 | return false; 90 | } 91 | 92 | // Only admin is allowed to remove student from the system. 93 | // delete() will remove all the existing attribute of the student of that particular ETH address and ID. 94 | function remove(uint256 _studentID,address _toRemove)public onlyAdmin returns(bool) 95 | { 96 | 97 | Student storage s = students[_toRemove][_studentID]; 98 | 99 | if(s.registered) 100 | delete(students[_toRemove][_studentID]); 101 | else 102 | revert("No student"); 103 | emit Removed(_studentID, _toRemove); 104 | return true; 105 | } 106 | 107 | // Admin will suspend the student from the system. 108 | function suspend(uint256 _studentID, address _toSuspend)public onlyAdmin returns(bool) 109 | { 110 | 111 | Student storage s = students[_toSuspend][_studentID]; 112 | 113 | if(s.registered) 114 | s.defaulter = true; 115 | else 116 | revert("No student"); 117 | emit Suspended(_studentID, _toSuspend); 118 | return true; 119 | } 120 | 121 | // Adding books with unique _isbn number and _bookcode and other attributes of a book. 122 | // A book with a unique combination of _isbn and _bookcode can be added only once. 123 | function addBooks(uint256 _bookCode,uint256 _isbn,string memory _name,uint256 _price)public 124 | onlyAdmin returns(bool) 125 | { 126 | Book storage b = lib[_bookCode][_isbn]; 127 | 128 | lib[_bookCode][_isbn] = Book(_name,1,_price,true,false); 129 | if(bookCode == _bookCode && isbn != _isbn) 130 | b.numBooks++; 131 | emit AddBooks(_isbn,_name,_price); 132 | return(true); 133 | } 134 | 135 | // Books issued is added to the address that requested the issue. 136 | // Checks the availiblity of the requested book. 137 | // The Book is marked as Issued if the transaction go through. 138 | function issueBook(uint256 _bookCode, uint256 _isbn, address _requestIssue, uint256 _id)public 139 | returns(bool) 140 | { 141 | Book storage b = lib[_bookCode][_isbn]; 142 | require(isAllowed(_requestIssue, _id), "Not allowed to issue "); 143 | 144 | if(b.isIssued || (b.numBooks == 0)) 145 | revert("Book is not available"); 146 | b.isIssued = true; 147 | b.numBooks--; 148 | emit BookIssued(_isbn,_bookCode, _requestIssue, _id); 149 | return true; 150 | } 151 | 152 | // TRemove books & all the attributes are deleted. 153 | // Check that the book isn't issued and there exists a desired book in the system. 154 | function removeBooks(uint256 _bookCode,uint256 _isbn)public onlyAdmin returns(bool) 155 | { 156 | Book storage b = lib[_bookCode][_isbn]; 157 | 158 | if(b.isIssued || (b.numBooks == 0)) 159 | revert("No such book Exist in the library"); 160 | delete(lib[_bookCode][_isbn]); 161 | emit RemoveBook(_bookCode,_isbn); 162 | return true; 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /contracts/Misc/MultiSigWallet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | contract MultiSigWallet { 5 | 6 | // Events 7 | event Deposit(address indexed sender, uint amount); 8 | event Submit(uint); 9 | event Approve(address indexed owner, uint indexed transectionId); 10 | event Revoke(address indexed owner, uint indexed transectionId); 11 | event Execute(uint indexed transectionId); 12 | 13 | struct Transaction { 14 | address to; 15 | uint value; 16 | bytes data; 17 | bool executed; 18 | } 19 | 20 | 21 | // Modifiers 22 | modifier onlyOwner() { 23 | require(isOwner[msg.sender], "Owners required"); 24 | _; 25 | } 26 | 27 | modifier transectionExists(uint _transactionId) { 28 | require( 29 | _transactionId < transactions.length, 30 | "Transection do not exists" 31 | ); 32 | _; 33 | } 34 | 35 | modifier notApproved(uint _transactionId) { 36 | require( 37 | !approved[_transactionId][msg.sender], 38 | "Transection alreay approved" 39 | ); 40 | _; 41 | } 42 | 43 | modifier notExecuted(uint _transactionId) { 44 | require( 45 | !transactions[_transactionId].executed, 46 | "Transection already executed" 47 | ); 48 | _; 49 | } 50 | 51 | // State variables 52 | address[] public owners; 53 | mapping(address => bool) public isOwner; 54 | uint public required; 55 | 56 | Transaction[] public transactions; 57 | mapping(uint => mapping(address => bool)) public approved; 58 | 59 | constructor(address[] memory _owners, uint _required) { 60 | require(_owners.length > 0, "Owners required"); 61 | require( 62 | _required > 0 && _required <= _owners.length, 63 | "Invalid required number of owners" 64 | ); 65 | 66 | for (uint i = 0; i < _owners.length; i++) { 67 | address owner = _owners[i]; 68 | 69 | require(owner != address(0), "Invalid owner"); 70 | require(!isOwner[owner], "Owner not unique"); 71 | 72 | isOwner[owner] = true; 73 | owners.push(owner); 74 | } 75 | 76 | required = _required; 77 | } 78 | 79 | receive() external payable { 80 | emit Deposit(msg.sender, msg.value); 81 | } 82 | 83 | function submit( 84 | address _to, 85 | uint _value, 86 | bytes calldata _data 87 | ) external onlyOwner { 88 | transactions.push( 89 | Transaction({to: _to, value: _value, data: _data, executed: false}) 90 | ); 91 | 92 | emit Submit(transactions.length - 1); 93 | } 94 | 95 | function approve(uint _transactionId) 96 | external 97 | onlyOwner 98 | transectionExists(_transactionId) 99 | notApproved(_transactionId) 100 | notExecuted(_transactionId) 101 | { 102 | approved[_transactionId][msg.sender] = true; 103 | emit Approve(msg.sender, _transactionId); 104 | } 105 | 106 | function _getApprovalCount(uint _transactionId) 107 | private 108 | view 109 | returns (uint count) 110 | { 111 | for (uint i = 0; i < owners.length; i++) { 112 | if (approved[_transactionId][owners[i]]) { 113 | count += 1; 114 | } 115 | } 116 | } 117 | 118 | function execute(uint _transactionId) 119 | external 120 | transectionExists(_transactionId) 121 | notExecuted(_transactionId) 122 | { 123 | require( 124 | _getApprovalCount(_transactionId) > required, 125 | "Not sufficient approvals for the transection" 126 | ); 127 | Transaction storage transection = transactions[_transactionId]; 128 | 129 | transection.executed = true; 130 | 131 | (bool success, ) = transection.to.call{value: transection.value}( 132 | transection.data 133 | ); 134 | require(success, "Transection failed"); 135 | 136 | emit Execute(_transactionId); 137 | } 138 | 139 | function revoke(uint _transactionId) 140 | external 141 | onlyOwner 142 | transectionExists(_transactionId) 143 | notExecuted(_transactionId) 144 | { 145 | require( 146 | approved[_transactionId][msg.sender], 147 | "Transection was not approved, hence cannot revoke." 148 | ); 149 | approved[_transactionId][msg.sender] = false; 150 | emit Revoke(msg.sender, _transactionId); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /contracts/Misc/NFTDropRegistration.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0 2 | // This contract allows users to register their NFT drop 3 | pragma solidity ^0.8.0; 4 | 5 | contract nftsinaction { 6 | address public owner; 7 | //Define a NFT drop object 8 | struct Drop { 9 | string imageUri; 10 | string name; 11 | string description; 12 | string social_1; 13 | string social_2; 14 | string websiteUri; 15 | string price; 16 | uint256 supply; 17 | uint256 presale; 18 | uint256 sale; 19 | uint8 chain; 20 | bool approved; 21 | } 22 | 23 | // Example of a NFT drop object 24 | // { "https://testtest.com/3.png", 25 | // "Test Collection", 26 | // "This is my drop for the month", 27 | // "Twitter", 28 | // "https://testtest.com", 29 | // "fasfas", 30 | // "0.03", 31 | // "22", 32 | // "1635790237", 33 | // "1635790237", 34 | // "1", 35 | // false } 36 | 37 | //Create a list to hold the objects 38 | Drop[] public drops; 39 | mapping (uint256 => address) public users; 40 | 41 | constructor() { 42 | owner = msg.sender; 43 | } 44 | 45 | modifier onlyOwner { 46 | require(msg.sender == owner, "You are not the owner."); 47 | _; 48 | } 49 | 50 | //Get the NFT drop object list 51 | function getDrops() public view returns (Drop[] memory) { 52 | return drops; 53 | } 54 | 55 | //Add to the NFT drop object list 56 | function addDrop(Drop memory _drop) public { 57 | _drop.approved = false; 58 | drops.push(_drop); 59 | uint256 id = drops.length -1; 60 | users[id] = msg.sender; 61 | } 62 | 63 | //Update from the NFT drop object list 64 | function updateDrop( 65 | uint256 _index, Drop memory _drop) public { 66 | require(msg.sender == users[_index], "You are not the owner of this drop."); 67 | _drop.approved = false; 68 | drops[_index] = _drop; 69 | } 70 | 71 | //Remove from the NFT drop object list 72 | //Approve an NFT object to enable displaying 73 | function approveDrop(uint256 _index) public onlyOwner { 74 | Drop storage drop = drops[_index]; 75 | drop.approved = true; 76 | } 77 | } -------------------------------------------------------------------------------- /contracts/Misc/PasswordManager.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0 2 | pragma solidity >=0.7.0 <0.9.0; 3 | 4 | contract PasswordManager { 5 | 6 | struct Password { 7 | uint id; 8 | string service; 9 | string login; 10 | string password; 11 | } 12 | 13 | mapping(address => mapping(uint => Password)) passwords; 14 | mapping(address => uint[]) ids; 15 | 16 | event passwordAdded(string service, string login, string password, uint id); 17 | event passwordUpdated(string service, string login, string password, uint id); 18 | event passwordDeleted(uint id); 19 | 20 | modifier entryExists(uint id) { 21 | require(passwords[msg.sender][id].id != 0, "The requested entry was not found!"); 22 | _; 23 | } 24 | 25 | modifier isNotEmpty(string memory service, string memory login, string memory password) { 26 | require(bytes(service).length != 0, "The service name can't be empty."); 27 | require(bytes(login).length != 0, "The login can't be empty."); 28 | require(bytes(password).length != 0, "The password can't be empty."); 29 | _; 30 | } 31 | 32 | function addPassword(string memory service, string memory login, string memory password) isNotEmpty(service, login, password) public { 33 | uint id = block.timestamp; 34 | ids[msg.sender].push(id); 35 | passwords[msg.sender][id] = Password(id, service, login, password); 36 | emit passwordAdded(service, login, password, id); 37 | } 38 | 39 | function getAllPasswordIds() external view returns(uint[] memory) { 40 | return ids[msg.sender]; 41 | } 42 | 43 | function getPasswordById(uint id) entryExists(id) external view returns(Password memory) { 44 | Password memory p = passwords[msg.sender][id]; 45 | return p; 46 | } 47 | 48 | function updatePassword(string memory service, string memory login, string memory password, uint id) entryExists(id) isNotEmpty(service, login, password) public { 49 | Password memory p = passwords[msg.sender][id]; 50 | p.login = login; 51 | p.service = service; 52 | p.password = password; 53 | passwords[msg.sender][id] = p; 54 | emit passwordUpdated(service, login, password, id); 55 | } 56 | 57 | function deletePassword(uint id) entryExists(id) public { 58 | delete passwords[msg.sender][id]; 59 | for (uint x=0; x=0.7.0 <0.9.0; 3 | 4 | contract PersonalDetailStorage { 5 | 6 | struct DetailStore { 7 | string name; 8 | string email; 9 | mapping(string => string) data; 10 | string[] keys; 11 | } 12 | 13 | mapping(address => DetailStore) details; 14 | 15 | event DataAdded(string key, string value); 16 | event DataUpdated(string oldKey, string newKey); 17 | event DataDeleted(string key); 18 | event BasicDataUpdateSuccessful(); 19 | 20 | modifier isKVNonEmpty(string memory key, string memory value) { 21 | require(bytes(key).length != 0, "The key can't be empty"); 22 | require(bytes(value).length != 0, "The value can't be empty"); 23 | _; 24 | } 25 | 26 | modifier isKNonEmpty(string memory key) { 27 | require(bytes(key).length != 0, "The key can't be empty"); 28 | _; 29 | } 30 | 31 | modifier isKeyUnique(string memory key) { 32 | require(getIndexOfKey(key) == -1, "A similar key already exists!"); 33 | _; 34 | } 35 | 36 | function getIndexOfKey(string memory key) private view returns(int) { 37 | for (uint a = 0; a < details[msg.sender].keys.length; a++) 38 | if (keccak256(abi.encodePacked(details[msg.sender].keys[a])) == keccak256(abi.encodePacked(key))) 39 | return int(a); 40 | return -1; 41 | } 42 | 43 | function saveData(string memory key, string memory value) isKVNonEmpty(key, value) isKeyUnique(key) public { 44 | details[msg.sender].data[key] = value; 45 | details[msg.sender].keys.push(key); 46 | emit DataAdded(key, value); 47 | } 48 | 49 | function deleteData(string memory key) isKNonEmpty(key) public { 50 | int index = getIndexOfKey(key); 51 | assert(index != -1); 52 | delete details[msg.sender].data[key]; 53 | delete details[msg.sender].keys[uint(index)]; 54 | emit DataDeleted(key); 55 | } 56 | 57 | function updateData(string memory existingKey, string memory newKey, string memory value) isKVNonEmpty(existingKey, newKey) external { 58 | deleteData(existingKey); 59 | saveData(newKey, value); 60 | emit DataUpdated(existingKey, newKey); 61 | } 62 | 63 | function getKeys() external view returns(string[] memory) { 64 | return details[msg.sender].keys; 65 | } 66 | 67 | function getValue(string memory key) isKNonEmpty(key) external view returns(string memory) { 68 | return details[msg.sender].data[key]; 69 | } 70 | 71 | function getBasicData() external view returns(string memory, string memory) { 72 | return (details[msg.sender].name, details[msg.sender].email); 73 | } 74 | 75 | function setBasicData(string memory name, string memory email) external { 76 | details[msg.sender].name = name; 77 | details[msg.sender].email = email; 78 | emit BasicDataUpdateSuccessful(); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /contracts/Misc/ProofOfMerge.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | /// @title Merge verify onChain 5 | /// @author supernovahs.eth 6 | /// @dev Verifies that Ethereum switched to Proof of stake using the difficulty opcode . 7 | /// For more info Refer https://eips.ethereum.org/EIPS/eip-4399#reusing-the-difficulty-opcode-instead-of-introducing-a-new-one 8 | contract VerifyMerge{ 9 | 10 | /// Checks difficulty of current block 11 | /// return bool -> Merge is successfull ? true : false 12 | function Merge() public view returns (bool){ 13 | return (block.difficulty ==0 || block.difficulty > 2**64); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /contracts/Misc/Propertyregistery.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier:MIT 2 | pragma solidity >=0.7.0 <0.9.0; 3 | 4 | contract PropertyRegistry{ 5 | 6 | struct paper{ 7 | address owner; 8 | string propAddress; 9 | uint area; 10 | } 11 | 12 | mapping (address => paper)public PropertyDB; 13 | 14 | function registraiton(string memory _Address,uint _area)public{ 15 | PropertyDB[msg.sender].owner=msg.sender; 16 | PropertyDB[msg.sender].propAddress=_Address; 17 | PropertyDB[msg.sender].area=_area; 18 | } 19 | 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /contracts/Misc/RestaurantsManager.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.7; 3 | 4 | contract RestaurantsManager { 5 | 6 | // Review structure 7 | struct Review{ 8 | uint bill_id; 9 | address restaurant_id; 10 | uint curr_time; 11 | uint rating_value ; 12 | bytes32 comment; 13 | } 14 | 15 | uint valid_duration = 3 days; 16 | 17 | function stringToBytes32(string memory source) private pure returns (bytes32 result) { 18 | bytes memory tempEmptyStringTest = bytes(source); 19 | if (tempEmptyStringTest.length == 0) { 20 | return 0x0; 21 | } 22 | assembly { 23 | result := mload(add(source, 32)) 24 | } 25 | } 26 | 27 | // Restaurant structures 28 | struct Restaurant{ 29 | address restaurant_id; 30 | uint total_rating_value; 31 | uint number_of_votes; 32 | } 33 | 34 | // Enter the MetaMask address of a person you want to have as charperson. 35 | // Here is a random address used for testing purpose 36 | address public chairperson=0x4C44cC4c444C444444cCCCC44ccC444C44C4c4C4; 37 | 38 | 39 | // A dynamically-sized array of `restaurant` structs. 40 | Restaurant[] restaurants; 41 | uint[] bill_ids; 42 | uint[] expiry_times; 43 | address[] restaurant_ids; 44 | mapping(address => uint) rinds; 45 | mapping(address => bytes32[]) rcomments; 46 | 47 | function addRestaurant(address _restaurant_id) public { 48 | require( 49 | msg.sender == chairperson, 50 | "Only chairperson can add a restaurant." 51 | ); 52 | // the address has to be new to be added 53 | if (rinds[_restaurant_id] >= restaurants.length){ 54 | restaurants.push(Restaurant( 55 | { 56 | restaurant_id: _restaurant_id, 57 | total_rating_value: 0, 58 | number_of_votes: 0 59 | })); 60 | rinds[_restaurant_id] = restaurants.length-1; 61 | } 62 | } 63 | 64 | function addBillID(uint bill_id, address restaurant_id) public { 65 | require( 66 | msg.sender == chairperson, 67 | "Only chairperson can add a restaurant." 68 | ); 69 | bill_ids.push(bill_id); 70 | expiry_times.push(block.timestamp + valid_duration); 71 | restaurant_ids.push(restaurant_id); 72 | } 73 | 74 | function addReview(uint bill_id, 75 | address restaurant_id, 76 | uint rating_value, 77 | string memory comment) 78 | public { 79 | uint i; 80 | for(i=0; i < bill_ids.length; i++){ 81 | if(bill_ids[i] == bill_id) 82 | { 83 | if(expiry_times[i] > block.timestamp && 84 | restaurant_ids[i] == restaurant_id) 85 | { 86 | uint ind = rinds[restaurant_id]; 87 | if (rating_value>5){ 88 | restaurants[ind].total_rating_value += 5; 89 | } 90 | else{ 91 | restaurants[ind].total_rating_value += rating_value; 92 | } 93 | restaurants[ind].number_of_votes += 1; 94 | rcomments[restaurant_id].push(stringToBytes32(comment)); 95 | 96 | // following will work even if length is 1 97 | bill_ids[i] = bill_ids[bill_ids.length-1]; 98 | restaurant_ids[i] = restaurant_ids[bill_ids.length-1]; 99 | expiry_times[i] = expiry_times[bill_ids.length-1]; 100 | delete bill_ids[bill_ids.length-1]; 101 | delete restaurant_ids[bill_ids.length-1]; 102 | delete expiry_times[bill_ids.length-1]; 103 | } 104 | } 105 | } 106 | } 107 | 108 | function calcul(uint a, uint b, uint precision) private pure returns ( uint) { 109 | return a*(10**precision)/b; 110 | } 111 | 112 | function uint2str(uint _i) internal pure returns (string memory _uintAsString) { 113 | if (_i == 0) { 114 | return "0"; 115 | } 116 | uint j = _i; 117 | uint len; 118 | while (j != 0) { 119 | len++; 120 | j /= 10; 121 | } 122 | bytes memory bstr = new bytes(len); 123 | uint k = len - 1; 124 | while (_i != 0) { 125 | bstr[k--] = bytes1(uint8(48 + _i % 10)); 126 | _i /= 10; 127 | } 128 | return string(bstr); 129 | } 130 | 131 | string public avg_rating_requested; 132 | uint public number_of_ratings_requested; 133 | string public comments_requested=''; 134 | 135 | function getReviews(address _restaurant_id) public 136 | { 137 | uint ind = rinds[_restaurant_id]; 138 | if (ind <= restaurants.length){ 139 | Restaurant memory r = restaurants[ind]; 140 | if (r.number_of_votes>0){ 141 | avg_rating_requested = uint2str(calcul(r.total_rating_value, r.number_of_votes, 2)); 142 | } 143 | else { 144 | avg_rating_requested = '000'; 145 | } 146 | number_of_ratings_requested =r.number_of_votes; 147 | bytes32[] memory temp = rcomments[_restaurant_id]; 148 | for(uint i=0; i Order) orders; 26 | 27 | // order lifecycle events 28 | event OrderRequested(address client, uint id, uint xDep, uint yDep, uint xDest, uint yDest); 29 | event OrderConfirmed(address client, uint id, uint price); 30 | event OrderPaid(address client, uint id, uint value); 31 | event OrderFinished(address client, uint id); 32 | 33 | event OrderCompleted( 34 | uint id, 35 | uint price 36 | ); 37 | 38 | constructor(address _clientAddress) { 39 | companyAddress = payable(msg.sender); 40 | 41 | clientAddress = _clientAddress; 42 | } 43 | 44 | // Request Ride 45 | function requestOrder(uint xDep, uint yDep, uint xDest, uint yDest) public { 46 | require(msg.sender == clientAddress); 47 | 48 | orderCount ++; 49 | orders[orderCount] = Order(orderCount, xDep, yDep, xDest, yDest, 0, 0, false, false); 50 | 51 | emit OrderRequested(msg.sender, orderCount, xDep, yDep, xDest, yDest); 52 | } 53 | 54 | // Confirm Ride 55 | function confirmOrder(uint id, uint price) public { 56 | require(msg.sender == companyAddress); 57 | require(id >= 0); 58 | require(id <= orderCount); 59 | 60 | orders[id].confirmed = true; 61 | orders[id].price = price; 62 | emit OrderConfirmed(clientAddress, id, price); 63 | } 64 | 65 | // Pay after Ride 66 | function payForOrder(uint id, uint price) payable public { 67 | require(msg.sender == clientAddress); 68 | require(id >= 0); 69 | require(id <= orderCount); 70 | require(orders[id].price == msg.value); 71 | 72 | orders[id].paid = msg.value; 73 | emit OrderPaid(msg.sender, id, price); 74 | } 75 | 76 | // Mark the order/ride as finished 77 | function finishOrder(uint id) payable public { 78 | require(msg.sender == clientAddress); 79 | require(id >= 0); 80 | require(id <= orderCount); 81 | 82 | orders[id].completed = true; 83 | emit OrderFinished(msg.sender, id); 84 | 85 | companyAddress.transfer(orders[id].paid); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /contracts/Misc/TicketingSystem/PriceConverter.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; 5 | 6 | library PriceConverter { 7 | 8 | 9 | function getLatestPrice() internal view returns (uint256){ 10 | AggregatorV3Interface priceFeed = AggregatorV3Interface(0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e); 11 | (, int256 answer, , ,) = priceFeed.latestRoundData(); 12 | 13 | return uint256(answer * 10000000000); 14 | } 15 | 16 | function getConvertedAmount(uint256 ethAmount) internal view returns (uint256){ 17 | uint256 ethPrice = getLatestPrice(); 18 | uint256 ethAmountInUSD = (ethPrice * ethAmount) / (1000000000000000000); 19 | return ethAmountInUSD; 20 | } 21 | } -------------------------------------------------------------------------------- /contracts/Misc/TicketingSystem/TicketBooker.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; 5 | import "./PriceConverter.sol"; 6 | 7 | error NotOwner(); 8 | 9 | contract TicketBooker{ 10 | 11 | using PriceConverter for uint256; 12 | 13 | address public immutable Host; 14 | uint256 public constant TICKET_PRICE = 2 * 10 ** 18; //Price set at 2 dollars 15 | uint256 public currentTicketID = 1; 16 | 17 | mapping(uint256 => address) public TicketIDToAddress; 18 | uint256 [] public Ticket_IDs; 19 | 20 | 21 | constructor(){ 22 | Host = msg.sender; 23 | } 24 | 25 | function buyTicket() public payable{ 26 | require((msg.value.getConvertedAmount()) >= TICKET_PRICE, "Spend more ETH"); 27 | TicketIDToAddress[currentTicketID] = msg.sender; 28 | Ticket_IDs.push(currentTicketID); 29 | currentTicketID++; 30 | } 31 | 32 | 33 | 34 | modifier onlyHost { 35 | if(msg.sender != Host) revert NotOwner(); 36 | _; 37 | } 38 | 39 | function verifyTicket(uint256 ticket_id, address claimer) public onlyHost view returns (bool){ 40 | if(TicketIDToAddress[ticket_id] == claimer){ 41 | return true; 42 | } 43 | return false; 44 | } 45 | 46 | receive() external payable{ 47 | buyTicket(); 48 | } 49 | 50 | fallback() external payable{ 51 | buyTicket(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /contracts/Misc/VaccineTracker.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.7; 4 | import "@openzeppelin/contracts/access/Ownable.sol"; 5 | 6 | contract VaccineTracker is Ownable { 7 | // State variables 8 | 9 | // Contract variables 10 | address public contractOwner; 11 | bool public isActive; 12 | 13 | // Batch variables 14 | struct VaccineBatch { 15 | string batchId; 16 | string lab; 17 | address labAddress; 18 | string description; 19 | uint256 creationDate; 20 | string deliveryDate; 21 | uint64 units; 22 | string currentStatus; 23 | address destination; 24 | } 25 | 26 | struct ConservationParams { 27 | string temperature; 28 | string humidity; 29 | string luminosity; 30 | } 31 | 32 | uint256[] public timestamps; 33 | 34 | mapping(string => VaccineBatch) private stock; 35 | mapping(string => mapping(uint256 => string)) private status; 36 | mapping(string => mapping(uint256 => ConservationParams)) private params; 37 | mapping(address => mapping(string => bool)) private wallet; 38 | 39 | // Modifiers 40 | 41 | modifier batchExists(string memory batchId) { 42 | require( 43 | stock[batchId].units != 0, 44 | "A batch with this batchId does not exist" 45 | ); 46 | _; 47 | } 48 | 49 | modifier contractActive() { 50 | require(isActive, "Sorry, contract disabled"); 51 | _; 52 | } 53 | 54 | // Events 55 | 56 | event CreateBatch( 57 | string message, 58 | address addressLab, 59 | string batchId, 60 | string lab, 61 | uint256 creationDate 62 | ); 63 | event DeliverBatch( 64 | string message, 65 | address addressLab, 66 | string batchId, 67 | address to, 68 | uint256 deliverDate 69 | ); 70 | event ConfirmDeliver( 71 | string message, 72 | string batchId, 73 | address to, 74 | uint256 deliveryDate 75 | ); 76 | event RegisterParams( 77 | string message, 78 | string batchId, 79 | string temperature, 80 | string humidity, 81 | string luminosity 82 | ); 83 | 84 | // Constructor 85 | 86 | constructor() { 87 | contractOwner = msg.sender; 88 | admin[msg.sender] = true; 89 | isActive = true; 90 | } 91 | 92 | // User management 93 | 94 | mapping(address => bool) private admin; 95 | 96 | function addAdmin(address _newAdmin) external { 97 | require(isActive, "Contract disabled"); 98 | require( 99 | msg.sender == contractOwner, 100 | "Identity is not the contract owner" 101 | ); 102 | require(!admin[_newAdmin], "Identity is already an admin"); 103 | admin[_newAdmin] = true; 104 | } 105 | 106 | function deleteAdmin(address _noAdmin) external { 107 | require(isActive, "Contract disabled"); 108 | require( 109 | msg.sender == contractOwner, 110 | "Identity is not the contract owner" 111 | ); 112 | require(admin[_noAdmin], "Identity is not an admin"); 113 | admin[_noAdmin] = false; 114 | } 115 | 116 | function isAdmin(address _entity) external view returns (bool) { 117 | require(isActive, "Contract disabled"); 118 | require( 119 | msg.sender == contractOwner, 120 | "Identity is not the contract owner" 121 | ); 122 | return (admin[_entity]); 123 | } 124 | 125 | // Write functions 126 | 127 | function createBatch( 128 | string calldata batchId, 129 | string calldata lab, 130 | string calldata description, 131 | string calldata deliveryDate, 132 | uint64 units 133 | ) public contractActive { 134 | require( 135 | stock[batchId].units == 0, 136 | "A batch with this batchId already exists" 137 | ); 138 | timestamps.push(block.timestamp); 139 | stock[batchId] = VaccineBatch( 140 | batchId, 141 | lab, 142 | msg.sender, 143 | description, 144 | block.timestamp, 145 | deliveryDate, 146 | units, 147 | "ready", 148 | address(0) 149 | ); 150 | status[batchId][block.timestamp] = "ready"; 151 | params[batchId][block.timestamp] = ConservationParams("-", "-", "-"); 152 | wallet[msg.sender][batchId] = true; 153 | emit CreateBatch( 154 | "Vaccine batch successfully created", 155 | msg.sender, 156 | batchId, 157 | lab, 158 | block.timestamp 159 | ); 160 | } 161 | 162 | function deliverBatch(string memory batchId, address to) 163 | public 164 | batchExists(batchId) 165 | contractActive 166 | { 167 | require( 168 | keccak256(bytes(stock[batchId].currentStatus)) == 169 | keccak256(bytes("ready")), 170 | "Batch not ready to ship" 171 | ); 172 | timestamps.push(block.timestamp); 173 | status[batchId][block.timestamp] = "shipped"; 174 | params[batchId][block.timestamp] = ConservationParams("-", "-", "-"); 175 | stock[batchId].destination = to; 176 | stock[batchId].currentStatus = "shipped"; 177 | emit DeliverBatch( 178 | "Vaccine batch successfully shipped", 179 | msg.sender, 180 | batchId, 181 | to, 182 | block.timestamp 183 | ); 184 | } 185 | 186 | function confirmDelivery(string memory batchId) 187 | public 188 | batchExists(batchId) 189 | contractActive 190 | { 191 | require( 192 | keccak256(bytes(stock[batchId].currentStatus)) == 193 | keccak256(bytes("shipped")), 194 | "Batch not shipped" 195 | ); 196 | require( 197 | stock[batchId].destination == msg.sender, 198 | "The address is not the receiver of the batch" 199 | ); 200 | timestamps.push(block.timestamp); 201 | status[batchId][block.timestamp] = "delivered"; 202 | params[batchId][block.timestamp] = ConservationParams("-", "-", "-"); 203 | stock[batchId].currentStatus = "delivered"; 204 | wallet[stock[batchId].labAddress][batchId] = false; 205 | wallet[msg.sender][batchId] = true; 206 | emit ConfirmDeliver( 207 | "Vaccine batch successfully delivered", 208 | batchId, 209 | msg.sender, 210 | block.timestamp 211 | ); 212 | } 213 | 214 | function registerParams( 215 | string memory batchId, 216 | string memory temperature, 217 | string memory humidity, 218 | string memory luminosity 219 | ) public batchExists(batchId) contractActive { 220 | require( 221 | keccak256(bytes(stock[batchId].currentStatus)) == 222 | keccak256(bytes("shipped")), 223 | "Batch not shipped" 224 | ); 225 | timestamps.push(block.timestamp); 226 | params[batchId][block.timestamp] = ConservationParams( 227 | temperature, 228 | humidity, 229 | luminosity 230 | ); 231 | emit RegisterParams( 232 | "Params successfully registered for batch", 233 | batchId, 234 | temperature, 235 | humidity, 236 | luminosity 237 | ); 238 | } 239 | 240 | // Read functions 241 | 242 | function getBatch(string calldata batchId) 243 | public 244 | view 245 | returns ( 246 | string memory, 247 | string memory, 248 | address, 249 | string memory, 250 | uint256, 251 | uint64, 252 | string memory 253 | ) 254 | { 255 | return ( 256 | stock[batchId].batchId, 257 | stock[batchId].lab, 258 | stock[batchId].labAddress, 259 | stock[batchId].description, 260 | stock[batchId].creationDate, 261 | stock[batchId].units, 262 | stock[batchId].currentStatus 263 | ); 264 | } 265 | 266 | function getCurrentStatus(string calldata batchId) 267 | public 268 | view 269 | batchExists(batchId) 270 | contractActive 271 | returns (string memory) 272 | { 273 | return (stock[batchId].currentStatus); 274 | } 275 | 276 | function isOwner(address owner, string memory batchId) 277 | public 278 | view 279 | batchExists(batchId) 280 | contractActive 281 | returns (bool) 282 | { 283 | if (wallet[owner][batchId]) { 284 | return true; 285 | } 286 | return false; 287 | } 288 | 289 | // Traceability functions 290 | 291 | // Specific timestamp 292 | 293 | function getParams(string calldata batchId, uint256 timestamp) 294 | public 295 | view 296 | batchExists(batchId) 297 | contractActive 298 | returns ( 299 | string memory, 300 | string memory, 301 | string memory 302 | ) 303 | { 304 | return ( 305 | params[batchId][timestamp].temperature, 306 | params[batchId][timestamp].humidity, 307 | params[batchId][timestamp].luminosity 308 | ); 309 | } 310 | 311 | function getStatus(string calldata batchId, uint256 timestamp) 312 | public 313 | view 314 | batchExists(batchId) 315 | contractActive 316 | returns (string memory) 317 | { 318 | return (status[batchId][timestamp]); 319 | } 320 | 321 | // All the values 322 | 323 | function getAllTemp(string calldata batchId) 324 | public 325 | view 326 | batchExists(batchId) 327 | contractActive 328 | returns (string[] memory) 329 | { 330 | string[] memory temperatures = new string[](timestamps.length); 331 | uint256 timestampIt; 332 | for (uint256 i = 0; i < timestamps.length; i++) { 333 | timestampIt = timestamps[i]; 334 | temperatures[i] = params[batchId][timestampIt].temperature; 335 | } 336 | return temperatures; 337 | } 338 | 339 | function getAllHum(string calldata batchId) 340 | public 341 | view 342 | batchExists(batchId) 343 | contractActive 344 | returns (string[] memory) 345 | { 346 | string[] memory temperatures = new string[](timestamps.length); 347 | uint256 timestampIt; 348 | for (uint256 i = 0; i < timestamps.length; i++) { 349 | timestampIt = timestamps[i]; 350 | temperatures[i] = params[batchId][timestampIt].humidity; 351 | } 352 | return temperatures; 353 | } 354 | 355 | function getAllLum(string calldata batchId) 356 | public 357 | view 358 | batchExists(batchId) 359 | contractActive 360 | returns (string[] memory) 361 | { 362 | string[] memory temperatures = new string[](timestamps.length); 363 | uint256 timestampIt; 364 | for (uint256 i = 0; i < timestamps.length; i++) { 365 | timestampIt = timestamps[i]; 366 | temperatures[i] = params[batchId][timestampIt].luminosity; 367 | } 368 | return temperatures; 369 | } 370 | 371 | function getAllStatus(string calldata batchId) 372 | public 373 | view 374 | batchExists(batchId) 375 | contractActive 376 | returns (string[] memory) 377 | { 378 | string[] memory allStatus = new string[](timestamps.length); 379 | uint256 timestampIt; 380 | for (uint256 i = 0; i < timestamps.length; i++) { 381 | timestampIt = timestamps[i]; 382 | allStatus[i] = status[batchId][timestampIt]; 383 | } 384 | return allStatus; 385 | } 386 | 387 | // Panic functions 388 | 389 | function enableContract() external onlyOwner { 390 | require(!isActive, "Contract already enabled"); 391 | isActive = true; 392 | } 393 | 394 | function disableContract() external onlyOwner { 395 | require(isActive, "Contract already disabled"); 396 | isActive = false; 397 | } 398 | } 399 | -------------------------------------------------------------------------------- /contracts/Misc/Vesting_Contract.sol: -------------------------------------------------------------------------------- 1 | /// SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | contract Vesting{ 6 | 7 | /// token not included 8 | uint public cliff; // delay from start to iniate vesting 9 | uint public start; // green signal from owner 10 | uint public vesting_duration; // time period between 2 vestings usually 1 month 11 | uint public vesting_cycles; // no of cycles of vesting 12 | uint public totalTokens; 13 | uint public tokensClaimed; 14 | address public owner; // the contract owner 15 | address public receiver; 16 | 17 | 18 | constructor( 19 | uint _cliff, 20 | uint _vesting_duration, 21 | address _owner, 22 | uint _vesting_cycles){ 23 | _owner = msg.sender; 24 | owner = _owner; 25 | vesting_duration = _vesting_duration; 26 | cliff = _cliff; 27 | start = block.timestamp; 28 | vesting_cycles = _vesting_cycles; 29 | 30 | } 31 | 32 | // this function will be used to fund the contract 33 | function fundContract(uint _tokens) public { 34 | require(msg.sender == owner, "only owner can fund it."); 35 | totalTokens = _tokens; 36 | 37 | // send tokens from owner to contract using openzeplin 38 | 39 | } 40 | 41 | // this claimTokens function will send the tokens to the required user 42 | function claimTokens() public { 43 | require(msg.sender != owner,"owner cannot claim tokens"); 44 | require(block.timestamp > start+cliff, "Vesting hasnt started"); 45 | require(totalTokens > 0, "Contract has not been funded"); 46 | 47 | uint time_now = ((block.timestamp)-(start+cliff)); 48 | 49 | uint token_pending = ((totalTokens/vesting_cycles)*(time_now/vesting_cycles)-tokensClaimed); 50 | 51 | //sending token with openzepplin 52 | tokensClaimed = tokensClaimed + token_pending; 53 | 54 | } 55 | 56 | // this function will change the receiver in the vesting contract 57 | function changeReceiver(address newReceiver) public{ 58 | require(msg.sender == owner, "This can be called by owner only"); 59 | newReceiver = msg.sender; 60 | totalTokens = 0; 61 | tokensClaimed = 0; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /contracts/Misc/healthVerse.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | contract BlockHealth { 5 | 6 | // Declaring the public variables to store basic info about the contract 7 | string public aboutUs = "Secure decentralized electronic health records sharing system based on blockchains"; 8 | address public owner; 9 | mapping(address => bool) public managers; 10 | 11 | // Declaring the private variables storing the data of the patients mapped with the doctors 12 | mapping(address => address[]) patientList; 13 | mapping(address => string[]) medicalRecords; 14 | 15 | // Modifier to give access only to the owner of the contract 16 | modifier onlyOwner(){ 17 | require(msg.sender == owner, "Only the owner has access to this"); 18 | _; 19 | } 20 | 21 | // Modifier to only give access to Managers and the Owner of the contract 22 | modifier restricted(){ 23 | require(managers[msg.sender] || owner == msg.sender, "Only allowed managers or the owner can perform this operation"); 24 | _; 25 | } 26 | 27 | // Modifier that only allows patients assigned doctor to see reports 28 | modifier onlyDoctor(address patient){ 29 | bool allowed = false; 30 | for(uint i; i < patientList[msg.sender].length; i++){ 31 | if(patientList[msg.sender][i] == patient){ 32 | allowed = true; 33 | break; 34 | } 35 | } 36 | require(allowed || owner == msg.sender, "You cannot access someone's private information"); 37 | _; 38 | } 39 | 40 | constructor(){ 41 | // Setting the owner of the contract as who deploys it 42 | owner = msg.sender; 43 | } 44 | 45 | // Function to add a Medical Report to the database 46 | function addRecord(address patient, address doctor, string memory url) public restricted { 47 | bool isThere = false; 48 | for(uint i; i < patientList[doctor].length; i++){ 49 | if(patientList[doctor][i] == patient){ 50 | isThere = true; 51 | break; 52 | } 53 | } 54 | if(isThere == false){ 55 | patientList[doctor].push(patient); 56 | } 57 | 58 | medicalRecords[patient].push(url); 59 | 60 | } 61 | 62 | // Function to get the list of patients of a doctor 63 | function getPatients(address doctor) public view restricted returns(address[] memory){ 64 | return patientList[doctor]; 65 | } 66 | 67 | // Function to get the list of my patients ( function which can be called from the doctors account ) 68 | function getMyPatients() public view returns(address[] memory){ 69 | return patientList[msg.sender]; 70 | } 71 | 72 | // Function to get all the medical reports for the doctor to see 73 | function getRecords(address patient) public view onlyDoctor(patient) returns(string[] memory){ 74 | return medicalRecords[patient]; 75 | } 76 | 77 | // Function to get all the medical reports for the patients use 78 | function getMyRecords() public view returns(string[] memory) { 79 | return medicalRecords[msg.sender]; 80 | } 81 | 82 | // Function to assign a new manager 83 | function addManager(address newManager) public onlyOwner { 84 | managers[newManager] = true; 85 | } 86 | 87 | // Function to transfer the ownership of this contract 88 | function transferOwnership(address newOwner) public onlyOwner { 89 | owner = newOwner; 90 | } 91 | 92 | // Function to revoke manager access from anyone 93 | function deleteManager(address oldManager) public onlyOwner { 94 | managers[oldManager] = false; 95 | } 96 | 97 | } -------------------------------------------------------------------------------- /contracts/NFT Warranty/README.md: -------------------------------------------------------------------------------- 1 | # Smart Contract for NFT Warranty 2 | 3 | ## Assumptions 4 | 5 | - Product ID - Identify a particular product. 6 | - Serial Number - Identify a particular product instance. 7 | - A product can be uniquely identified given its Product ID and Serial Number. 8 | - Token ID of NFT genrated for a product is `[Product ID][serial number]`. 9 | 10 | ## Structure 11 | 12 | - #### Owner 13 | 14 | Deployer of the smart contract. 15 | 16 | - #### Admin 17 | 18 | Admins of the smart contract. 19 | 20 | - Can add/remove admins. 21 | - Can add/remove sellers. 22 | 23 | - #### Seller 24 | Seller of the product/warranty (Brands). 25 | - Add/remove products (specify warranty period of each product) 26 | - Mint warranty of a product. 27 | - Replace product (mint a new NFT and burn the old one). 28 | -------------------------------------------------------------------------------- /contracts/NFT Warranty/nft-warranty.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; 5 | import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; 6 | import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; 7 | import "@openzeppelin/contracts/access/Ownable.sol"; 8 | import "@openzeppelin/contracts/utils/Strings.sol"; 9 | 10 | contract WarrantyNFT is ERC721, ERC721URIStorage, ERC721Burnable, Ownable { 11 | address internal contractOwner; 12 | 13 | mapping(address => bool) public isAdmin; 14 | mapping(address => bool) public isSeller; 15 | 16 | mapping(uint256 => bool) public productTransferable; 17 | mapping(uint256 => uint256) public productWarrantyPeriod; 18 | 19 | mapping(uint256 => address) public sellerOf; 20 | mapping(uint256 => uint256) public issueTime; 21 | mapping(uint256 => bool) public transferable; 22 | mapping(uint256 => uint256) public warrantyPeriod; 23 | 24 | event Repair(uint256 indexed tokenID); 25 | event Replace(uint256 indexed tokenID, uint256 indexed newTokenID); 26 | 27 | modifier adminOnly() { 28 | require(isAdmin[msg.sender], "Admin only function"); 29 | _; 30 | } 31 | 32 | modifier sellerOnly() { 33 | require(isSeller[msg.sender], "Seller only function"); 34 | _; 35 | } 36 | 37 | modifier adminOrSellerOnly() { 38 | require( 39 | isAdmin[msg.sender] || isSeller[msg.sender], 40 | "Admin or Seller only function" 41 | ); 42 | _; 43 | } 44 | 45 | /** 46 | * @dev if the product with tokenID exists or not 47 | */ 48 | modifier exists(uint256 tokenID) { 49 | require( 50 | ownerOf(tokenID) != address(0), 51 | "The product either does not exist or has not been sold yet" 52 | ); 53 | _; 54 | } 55 | 56 | /** 57 | * @dev if the product with tokenID is in warranty period or not 58 | */ 59 | modifier inWarranty(uint256 tokenID) { 60 | require( 61 | issueTime[tokenID] + warrantyPeriod[tokenID] > block.timestamp, 62 | "The product is not in warranty period" 63 | ); 64 | _; 65 | } 66 | 67 | /** 68 | * @dev verify if the seller is the one attempting repairs or replacements 69 | */ 70 | modifier verifySeller(uint256 tokenID) { 71 | require(sellerOf[tokenID] == msg.sender, "You are not the seller"); 72 | _; 73 | } 74 | 75 | constructor() ERC721("Warranty", "W") { 76 | contractOwner = msg.sender; 77 | isAdmin[contractOwner] = true; 78 | } 79 | 80 | /** 81 | * @notice Add a new admin 82 | * @dev Only the contract owner and an existing admin can add a new admin 83 | * @param _admin The new admin address 84 | */ 85 | function addAdmin(address _admin) public adminOnly { 86 | isAdmin[_admin] = true; 87 | } 88 | 89 | /** 90 | * @notice Remove an admin 91 | * @dev Only the contract owner and an existing admin can remove an admin. An admin can remove themselves. 92 | * @param _admin The admins address to remove 93 | */ 94 | function removeAdmin(address _admin) public adminOnly { 95 | isAdmin[_admin] = false; 96 | } 97 | 98 | /** 99 | * @notice Add a new seller 100 | * @dev Only the contract owner and the admins can add a new seller 101 | * @param _seller The new seller address to add 102 | */ 103 | function addSeller(address _seller) public adminOnly { 104 | isSeller[_seller] = true; 105 | } 106 | 107 | /** 108 | * @notice Remove a seller 109 | * @dev Only the contract owner and the admins can remove seller 110 | * @param _seller The sellers address to remove 111 | */ 112 | function removeSeller(address _seller) public adminOnly { 113 | isSeller[_seller] = false; 114 | } 115 | 116 | /** 117 | * @notice add a new product 118 | * @dev only a registered seller can add a new product 119 | * @param productID product ID of new product 120 | * @param _warrantyPeriod warranty period offered on the product 121 | * @param _isSoulbound if the product warranty is transferable or not 122 | */ 123 | function addProduct( 124 | uint256 productID, 125 | uint256 _warrantyPeriod, 126 | bool _isSoulbound 127 | ) public sellerOnly { 128 | productWarrantyPeriod[productID] = _warrantyPeriod; 129 | productTransferable[productID] = !_isSoulbound; 130 | } 131 | 132 | function _baseURI() internal pure override returns (string memory) { 133 | return "https://"; 134 | } 135 | 136 | /** 137 | * @notice mints a new token for the given buyer 138 | * @dev serialNo of product is used as token id 139 | * @param buyer wallet address of the buyer 140 | * @param tokenID tokenID of the product 141 | */ 142 | function mintWarrantyNFT( 143 | address buyer, 144 | uint256 productID, 145 | uint256 tokenID 146 | ) public sellerOnly { 147 | sellerOf[tokenID] = msg.sender; 148 | issueTime[tokenID] = block.timestamp; 149 | warrantyPeriod[tokenID] = productWarrantyPeriod[productID]; 150 | _safeMint(buyer, tokenID); 151 | _setTokenURI(tokenID, Strings.toString(productID)); 152 | } 153 | 154 | /** 155 | * @notice Emits an event when the product is repaired 156 | * @param tokenID token ID of the product repaired 157 | */ 158 | function repairProduct(uint256 tokenID) 159 | public 160 | sellerOnly 161 | exists(tokenID) 162 | inWarranty(tokenID) 163 | verifySeller(tokenID) 164 | { 165 | emit Repair(tokenID); 166 | } 167 | 168 | /** 169 | * @notice Emits an event when the product is replaced 170 | * @param tokenID token ID of the product to be replaced 171 | * @param newTokenID token ID of the new product 172 | */ 173 | function replaceProduct(uint256 tokenID, uint256 newTokenID) 174 | public 175 | sellerOnly 176 | exists(tokenID) 177 | inWarranty(tokenID) 178 | verifySeller(tokenID) 179 | { 180 | issueTime[newTokenID] = issueTime[tokenID]; 181 | emit Replace(tokenID, newTokenID); 182 | } 183 | 184 | function isOwner(uint256 tokenID) public view returns (bool) { 185 | if (ownerOf(tokenID) == msg.sender) return true; 186 | else return false; 187 | } 188 | 189 | /** 190 | * @dev Prevents transfering of soulbound tokens 191 | */ 192 | function _beforeTokenTransfer( 193 | address from, 194 | address to, 195 | uint256 tokenID 196 | ) internal virtual override { 197 | if (transferable[tokenID] == false) { 198 | require( 199 | from == address(0) || to == address(0), 200 | "Cannot transfer soulbound tokens" 201 | ); 202 | } 203 | } 204 | 205 | // The following functions are overrides required by Solidity. 206 | function _burn(uint256 tokenId) 207 | internal 208 | override(ERC721, ERC721URIStorage) 209 | { 210 | super._burn(tokenId); 211 | } 212 | 213 | function tokenURI(uint256 tokenId) 214 | public 215 | view 216 | override(ERC721, ERC721URIStorage) 217 | returns (string memory) 218 | { 219 | return super.tokenURI(tokenId); 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /contracts/NFT/Soulbound.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.6; 3 | 4 | import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; 5 | 6 | interface IERC721Metadata { 7 | function name() external view returns (string memory); 8 | 9 | function symbol() external view returns (string memory); 10 | 11 | function tokenURI(uint256 tokenId) external view returns (string memory); 12 | } 13 | 14 | interface IERC4973 { 15 | /// @dev This emits when ownership of any ABT changes by any mechanism. 16 | /// This event emits when ABTs are given or equipped and unequipped 17 | /// (`to` == 0). 18 | event Transfer( 19 | address indexed from, 20 | address indexed to, 21 | uint256 indexed tokenId 22 | ); 23 | 24 | /// @notice Count all ABTs assigned to an owner 25 | /// @dev ABTs assigned to the zero address are considered invalid, and this 26 | /// function throws for queries about the zero address. 27 | /// @param owner An address for whom to query the balance 28 | /// @return The number of ABTs owned by `address owner`, possibly zero 29 | function balanceOf(address owner) external view returns (uint256); 30 | 31 | /// @notice Find the address bound to an ERC4973 account-bound token 32 | /// @dev ABTs assigned to zero address are considered invalid, and queries 33 | /// about them do throw. 34 | /// @param tokenId The identifier for an ABT. 35 | /// @return The address of the owner bound to the ABT. 36 | function ownerOf(uint256 tokenId) external view returns (address); 37 | 38 | /// @notice Removes the `uint256 tokenId` from an account. At any time, an 39 | /// ABT receiver must be able to disassociate themselves from an ABT 40 | /// publicly through calling this function. After successfully executing this 41 | /// function, given the parameters for calling `function give` or 42 | /// `function take` a token must be re-equipable. 43 | /// @dev Must emit a `event Transfer` with the `address to` field pointing to 44 | /// the zero address. 45 | /// @param tokenId The identifier for an ABT. 46 | function unequip(uint256 tokenId) external; 47 | 48 | /// @notice Creates and transfers the ownership of an ABT from the 49 | /// transaction's `msg.sender` to `address to`. 50 | /// @param to The receiver of the ABT. 51 | /// @param uri A distinct Uniform Resource Identifier (URI) for a given ABT. 52 | /// @return A unique `uint256 tokenId`. 53 | function give(address to, string calldata uri) external returns (uint256); 54 | 55 | /// @notice Creates and transfers the ownership of an ABT from an 56 | /// `address from` to the transaction's `msg.sender`. 57 | /// @param from The origin of the ABT. 58 | /// @param uri A distinct Uniform Resource Identifier (URI) for a given ABT. 59 | /// @return A unique `uint256 tokenId` generated by type-casting the `bytes32` 60 | function take(address from, string calldata uri) external returns (uint256); 61 | } 62 | 63 | contract ERC4973 is ERC165, IERC721Metadata, IERC4973 { 64 | string private _name; 65 | string private _symbol; 66 | uint256 private counter; 67 | 68 | mapping(uint256 => address) private _owners; 69 | mapping(uint256 => string) private _tokenURIs; 70 | mapping(address => uint256) private _balances; 71 | 72 | constructor(string memory name_, string memory symbol_) { 73 | _name = name_; 74 | _symbol = symbol_; 75 | counter = 0; 76 | } 77 | 78 | function supportsInterface(bytes4 interfaceId) 79 | public 80 | view 81 | virtual 82 | override 83 | returns (bool) 84 | { 85 | return 86 | interfaceId == type(IERC721Metadata).interfaceId || 87 | interfaceId == type(IERC4973).interfaceId; 88 | } 89 | 90 | function name() public view override returns (string memory) { 91 | return _name; 92 | } 93 | 94 | function symbol() public view override returns (string memory) { 95 | return _symbol; 96 | } 97 | 98 | function tokenURI(uint256 tokenId) 99 | public 100 | view 101 | override 102 | returns (string memory) 103 | { 104 | require(_exists(tokenId), "tokenURI: token doesn't exist"); 105 | return _tokenURIs[tokenId]; 106 | } 107 | 108 | function balanceOf(address owner) public view override returns (uint256) { 109 | // require(owner != address(0), "balanceOf: address zero is not a valid owner"); 110 | return _balances[owner]; 111 | } 112 | 113 | function ownerOf(uint256 tokenId) public view override returns (address) { 114 | address owner = _owners[tokenId]; 115 | require(owner != address(0), "ownerOf: token doesn't exist"); 116 | return owner; 117 | } 118 | 119 | function unequip(uint256 tokenId) public override { 120 | require( 121 | msg.sender == ownerOf(tokenId), 122 | "unequip: sender must be owner" 123 | ); 124 | _burn(tokenId); 125 | } 126 | 127 | function give(address to, string calldata uri) 128 | external 129 | override 130 | returns (uint256) 131 | { 132 | require(msg.sender != to, "give: cannot give from self"); 133 | counter += 1; 134 | uint256 tokenId = counter; 135 | _mint(msg.sender, to, tokenId, uri); 136 | return tokenId; 137 | } 138 | 139 | function take(address from, string calldata uri) 140 | external 141 | override 142 | returns (uint256) 143 | { 144 | require(msg.sender != from, "take: cannot take from self"); 145 | counter += 1; 146 | uint256 tokenId = counter; 147 | _mint(from, msg.sender, tokenId, uri); 148 | return tokenId; 149 | } 150 | 151 | function _exists(uint256 tokenId) internal view returns (bool) { 152 | return _owners[tokenId] != address(0); 153 | } 154 | 155 | function _mint( 156 | address from, 157 | address to, 158 | uint256 tokenId, 159 | string memory uri 160 | ) internal virtual returns (uint256) { 161 | require(!_exists(tokenId), "mint: tokenID exists"); 162 | _balances[to] += 1; 163 | _owners[tokenId] = to; 164 | _tokenURIs[tokenId] = uri; 165 | emit Transfer(from, to, tokenId); 166 | return tokenId; 167 | } 168 | 169 | function _burn(uint256 tokenId) internal virtual { 170 | address owner = ownerOf(tokenId); 171 | 172 | _balances[owner] -= 1; 173 | delete _owners[tokenId]; 174 | delete _tokenURIs[tokenId]; 175 | 176 | emit Transfer(owner, address(0), tokenId); 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /contracts/NFT/erc1155.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; 5 | import "@openzeppelin/contracts/access/Ownable.sol"; 6 | import "@openzeppelin/contracts/security/Pausable.sol"; 7 | import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; 8 | import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; 9 | 10 | contract AdvaitaNFT is ERC1155, Ownable, Pausable, ERC1155Burnable, ERC1155Supply { 11 | constructor() ERC1155("ipfs://") {} 12 | 13 | 14 | /** 15 | * @dev Set a new URI for metadata, only owner can call this function 16 | */ 17 | function setURI(string memory newuri) public onlyOwner { 18 | _setURI(newuri); 19 | } 20 | 21 | /** 22 | * @dev Pause the contract, only owner can call this function 23 | */ 24 | function pause() public onlyOwner { 25 | _pause(); 26 | } 27 | 28 | /** 29 | * @dev Unpause the contract, only owner can call this function 30 | */ 31 | function unpause() public onlyOwner { 32 | _unpause(); 33 | } 34 | 35 | /** 36 | * @dev Mint new NFTs, only owner can call this function 37 | */ 38 | function mint( 39 | address account, 40 | uint256 id, 41 | uint256 amount, 42 | bytes memory data 43 | ) public onlyOwner { 44 | _mint(account, id, amount, data); 45 | } 46 | 47 | /** 48 | * @dev Mint copies of multiple tokenIDs, only owner can call this function 49 | */ 50 | function mintBatch( 51 | address to, 52 | uint256[] memory ids, 53 | uint256[] memory amounts, 54 | bytes memory data 55 | ) public onlyOwner { 56 | _mintBatch(to, ids, amounts, data); 57 | } 58 | 59 | /** 60 | * @dev Keeps track of total supply of tokens. 61 | */ 62 | function _beforeTokenTransfer( 63 | address operator, 64 | address from, 65 | address to, 66 | uint256[] memory ids, 67 | uint256[] memory amounts, 68 | bytes memory data 69 | ) internal override(ERC1155, ERC1155Supply) whenNotPaused { 70 | super._beforeTokenTransfer(operator, from, to, ids, amounts, data); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /contracts/NFT/erc2981-erc721.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.22 <0.9.0; 3 | 4 | import "@openzeppelin/contracts/token/common/ERC2981.sol"; 5 | import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; 6 | import "@openzeppelin/contracts/utils/Counters.sol"; 7 | import "@openzeppelin/contracts/access/Ownable.sol"; 8 | 9 | //URIStorage basically ensures that the URI of the off-chain metadata of the NFT is stored onchain when you mint it 10 | //from the token URI we can get the token ID 11 | 12 | contract BengalTigers is ERC2981, ERC721URIStorage, Ownable { 13 | using Counters for Counters.Counter; 14 | Counters.Counter private _tokenIds; 15 | 16 | constructor() ERC721("BengalTigers", "BGT") { 17 | // Let's set a default royalty whenever a token is created 18 | _setDefaultRoyalty(msg.sender, 100); //100 basis points = 1 percent 19 | } 20 | 21 | //Contract inherited from multiple base classes with supportsInterface function so we override it 22 | 23 | function supportsInterface(bytes4 interfaceId) 24 | public 25 | view 26 | virtual 27 | override(ERC721, ERC2981) 28 | returns (bool) 29 | { 30 | return super.supportsInterface(interfaceId); 31 | } 32 | 33 | //overriding the erc2981 burn function 34 | function _burn(uint256 tokenId) internal virtual override { 35 | super._burn(tokenId); 36 | _resetTokenRoyalty(tokenId); 37 | } 38 | 39 | //allowing the above _burn function to be called publicly 40 | function burnNFT(uint256 tokenId) public { 41 | _burn(tokenId); 42 | } 43 | 44 | function mintNFT(address recipient, string memory tokenURI) 45 | public 46 | onlyOwner 47 | returns (uint256) 48 | { 49 | //increment the token ID by one when minting new NFT 50 | 51 | _tokenIds.increment(); 52 | 53 | //new ID is the incremented Id 54 | 55 | uint256 newItemId = _tokenIds.current(); 56 | 57 | _safeMint(recipient, newItemId); //using safe mint function of ERC721 58 | _setTokenURI(newItemId, tokenURI); //setting the token URI with the given uri for the new token 59 | 60 | return newItemId; //return the freshly minted tokenId 61 | } 62 | 63 | function mintNFTWithRoyalty( 64 | address recipient, 65 | string memory tokenURI, 66 | address royaltyReceiver, 67 | uint96 fees 68 | ) public onlyOwner returns (uint256) { 69 | //minting the NFT 70 | uint256 tokenId = mintNFT(recipient, tokenURI); 71 | //setting the royalty for the freshly minted token 72 | _setTokenRoyalty(tokenId, royaltyReceiver, fees); 73 | 74 | return tokenId; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /contracts/NFT/erc721std.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; 5 | import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; 6 | import "@openzeppelin/contracts/access/Ownable.sol"; 7 | import "@openzeppelin/contracts/utils/Counters.sol"; 8 | 9 | contract AdvaitaNFT is ERC721, ERC721URIStorage, Ownable { 10 | using Counters for Counters.Counter; 11 | 12 | Counters.Counter private _tokenIdCounter; 13 | 14 | constructor() ERC721("AdvaitaNFT", "ADV") {} 15 | 16 | function _baseURI() internal pure override returns (string memory) { 17 | return "ipfs://"; 18 | } 19 | 20 | function safeMint(address to, string memory uri) public onlyOwner { 21 | uint256 tokenId = _tokenIdCounter.current(); 22 | _tokenIdCounter.increment(); 23 | _safeMint(to, tokenId); 24 | _setTokenURI(tokenId, uri); 25 | } 26 | 27 | // The following functions are overrides required by Solidity. 28 | 29 | function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { 30 | super._burn(tokenId); 31 | } 32 | 33 | function tokenURI(uint256 tokenId) 34 | public 35 | view 36 | override(ERC721, ERC721URIStorage) 37 | returns (string memory) 38 | { 39 | return super.tokenURI(tokenId); 40 | } 41 | } -------------------------------------------------------------------------------- /contracts/PreventSpam/CommentMe.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | contract CommentMe { 6 | //It will help us in getting total comments, so far. 7 | uint256 totalComments; 8 | 9 | //Creating event, it helps in logging(cheap storage) 10 | event NewComment(address indexed from, uint256 timestamp, string message); 11 | 12 | //Creating struct(custom data type) 13 | struct Comment { 14 | address commenter; // The address of the user who commented. 15 | string message; // The message the user sent. 16 | uint timestamp; // The timestamp when the user commented. 17 | } 18 | 19 | // declare a variable comments that lets me store an array of structs. 20 | Comment[] comments; 21 | 22 | //Creating map data structure to associate an address with a number, It will help in checking spammers and preventing spam messages. 23 | mapping(address => uint256) public lastCommentedAt; 24 | 25 | function comment(string memory _message) public { 26 | //Making sure that the commenter/Spammer, should wait atlest 1 day(Customizable) before next comment, Hence preventing spam. 27 | require( 28 | lastCommentedAt[msg.sender] + 24 hours < block.timestamp, 29 | "Wait for a day, before next comment." 30 | ); 31 | 32 | lastCommentedAt[msg.sender] = block.timestamp; 33 | 34 | totalComments += 1; 35 | 36 | comments.push(Comment(msg.sender, _message, block.timestamp)); 37 | 38 | emit NewComment(msg.sender, block.timestamp, _message); 39 | } 40 | 41 | function getAllComments() public view returns (Comment[] memory) { 42 | return comments; 43 | } 44 | 45 | function getTotalComments() public view returns (uint256) { 46 | return totalComments; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /contracts/Real_TimeData_Feed/Readme.md: -------------------------------------------------------------------------------- 1 | ## About 2 | 3 | **Let's get started with the intro of the chainlink , basic defination of the data feed , assets and many more technical word.** 4 | 5 | ### What is Chainlink ? 6 | 7 | Chainlink greatly expands the capabilities of smart contracts by enabling access to real-world data and off-chain computation while maintaining the security and reliability guarantees inherent to blockchain technology. In simple word's Chainlink provides you the real data feeds of the assets like ETH/USD , EUR/USD and many more , for the full and clear infromation u can also see their live docs avialable on the https://chain.link/ 8 | 9 | ### What is assets ? 10 | 11 | Asset is basically digital currency in you can invest and hold some equity . In simple word assets are the digital money or currency . 12 | 13 | ### What is Data feed ? 14 | 15 | Data feed is basically the real value price of the assets we are getting through the chainlink. 16 | 17 | ## Prerequisite 18 | 19 |
  • Knowldge of the remix ide
  • 20 |
  • Having the Rinkeby test faucet avialable in the metamask account to get faucet https://faucet.rinkeby.io/
  • 21 | Basic of the solidity. 22 | 23 | ## How Data Feed Get Their Data 24 | Each data feed is updated by a decentralized oracle network. Each oracle operator is rewarded for publishing data. The number of oracles contributing to each feed varies. In order for an update to take place, the data feed aggregator contract must receive responses from a minimum number of oracles or the latest answer will not be updated. You can see the minimum number of oracles for the corresponding feed at chainlink. 25 | For more you can read https://docs.chain.link/docs/architecture-decentralized-model/ . 26 | 27 | ## Code 28 | 29 | ![datafeed](https://user-images.githubusercontent.com/105157723/193408555-ec04ace6-04c5-4ec9-8b45-eb457cece95a.png) 30 | 31 | ## Working 32 | 33 | The above code is written in the remix ide , lets understand the line by line code of this . 34 | 35 | Note : If u don't know how to use Remix ide you can read this https://github.com/Vikash-8090-Yadav/Solidity-Pathshala/blob/main/Blog/How%20to%20use%20remix%20IDE/How%20to%20use%20remix.ide.md 36 | 37 | and if u are not familiar with the solidity then read from here https://github.com/Vikash-8090-Yadav/Solidity-Pathshala/tree/main/Study_Material 38 | 39 | In the above code I am importing **AggregatorV3Interface.sol** 40 | 41 | **An aggregator is the contract that receives periodic data updates from the oracle network. Aggregators store aggregated data on-chain so that consumers can retrieve it and and act upon it within the same transaction. Which define the external functions implemented by Data Feeds.** 42 | 43 | and then in the **contrcutor** i am passing the address of the contract where the ET/USD deployed , remember in this we can't pass our own address beacuse this code on chainlink provide the real data of the assets which is already deployed with this address passed in the constructor . 44 | 45 | By **getLatestPrice( )** function we can get the lastest value of the ETH/USD in the integer form . By using the latestRoundData( ) function which is the method of the AggreatorV3Interface.sol . 46 | 47 | When you deployed the code and click on the getLatestPrice you can see the latest value of the ETH/USD 48 | 49 | #### You can see on the left side below , getLatestPrice -> 0:int256: 114068290588 50 | 51 | -------------------------------------------------------------------------------- /contracts/Real_TimeData_Feed/RealTime_Data_Feed.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.7; 3 | /** 4 | * Fetching the interface for the Aggregator for the further use in the code 5 | */ 6 | 7 | import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; 8 | 9 | contract PriceConsumerV3 { 10 | 11 | AggregatorV3Interface internal priceFeed; 12 | 13 | /** 14 | * Network: Rinkeby 15 | * Aggregator: ETH/USD 16 | * Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e 17 | */ 18 | constructor() { 19 | priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); 20 | } 21 | 22 | /** 23 | * Returns the latest price 24 | */ 25 | function getLatestPrice() public view returns (int) { 26 | ( 27 | /*uint80 roundID*/, 28 | int price, 29 | /*uint startedAt*/, 30 | /*uint timeStamp*/, 31 | /*uint80 answeredInRound*/ 32 | ) = priceFeed.latestRoundData(); 33 | return price; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /contracts/Salary Payment System/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Bulk Salary Payment Smart Contract 3 | 4 | Salary Payment Smart contract is Bulk transfer system where Employees get Monthly bases salary if Company failed to pay money and comnpany payes compensation for every day. 5 | 6 | 7 | # Functions for the companies 8 | - depositMoney - Owner can send the funds to Contract 9 | - registerEmployee - Owner can register new employee with their address and salary 10 | - ChangeSalary - Owner can employee salary increase or decrease 11 | 12 | # Functions for Employee 13 | - SendSalary - Any employee can execute these after 1 month then bulk transfer of funds will added to every Employee Account 14 | - Latepayment - if employee doesn't get their salary after month they will get compensation as per days 15 | - CompanyWalletBalance : both can use this function, which returns the total balance of the contract 16 | 17 | # Compensation Fund 18 | - **For Everyone 1 day compensation fund is 0.001 ether** 19 | - On Calculating number of days late from actual day(pay day) 20 | - compensionTotal = LateDays * compensation(0.001) ether; 21 | - SalaryPerPerson = compensationTotal + employee salary 22 | 23 | ``` 24 | 25 | uint constant public compensation = 0.001 ether; 26 | 27 | function Latepayment() public payable { 28 | require(block.timestamp - finaltime > 1 days,"No late Payment option"); 29 | uint LateDays = (block.timestamp - finaltime) / 1 days ; 30 | uint compensationTotal = LateDays * compensation; // for each day compensation 31 | uint limit = id+1; 32 | for (uint i=0 ; i < limit ; i++){ 33 | address add = (company_Wallet[i].employeeAdd); 34 | uint SalaryPerPerson = company_Wallet[i].salary * 1 ether + compensationTotal; // units are in ether converting 35 | payable(add).transfer(SalaryPerPerson); 36 | } 37 | finaltime = block.timestamp + 100 seconds; 38 | 39 | } 40 | 41 | ``` 42 | 43 | 44 | ## Feedback 45 | 46 | If you have any feedback, please reach out to me twitter or linkedin 47 | -------------------------------------------------------------------------------- /contracts/Salary Payment System/SalaryPaymentSystem.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | contract SalaryPaymentSystem{ 5 | 6 | struct Employee{ 7 | address employeeAdd; 8 | uint salary; 9 | } 10 | 11 | 12 | uint id; 13 | address owner; 14 | uint public finaltime; 15 | 16 | 17 | constructor(){ 18 | owner=msg.sender; 19 | finaltime = block.timestamp + 30.42 days; 20 | } 21 | 22 | mapping(uint=>Employee) company_Wallet; 23 | mapping(address=>uint) salaryInfo; 24 | 25 | 26 | modifier onlyOwner{ 27 | require(msg.sender==owner,"your are not owner"); 28 | _; 29 | } 30 | 31 | 32 | function depositMoney() payable public onlyOwner { 33 | require(msg.value>0,"check balance once"); 34 | } 35 | 36 | function registerEmployee(address _employeeAdd,uint _salary) public onlyOwner{ 37 | require(_salary>0,"Enter the salary of employee"); 38 | require (salaryInfo[_employeeAdd] == 0,"You can't Register employee twice"); 39 | company_Wallet[id] = Employee(_employeeAdd,_salary); 40 | salaryInfo[_employeeAdd] = _salary; 41 | ++id; 42 | } 43 | 44 | function SendSalary() public payable { 45 | require(block.timestamp > finaltime ,"You Can't get Salary Before Payday"); 46 | require(block.timestamp - finaltime < 3 days ,"Your company is doesn't send money on payday you will receive additional funds! use click Latepayment function"); 47 | uint limit = id+1; 48 | for (uint i=0 ; i < limit ; i++){ 49 | address add = (company_Wallet[i].employeeAdd); 50 | uint SalaryPerPerson = company_Wallet[i].salary * 1 ether; // units are in ether converting 51 | payable(add).transfer(SalaryPerPerson); 52 | } 53 | finaltime = block.timestamp + 30.42 days; 54 | } 55 | 56 | 57 | 58 | uint constant public compensation = 0.001 ether; 59 | 60 | function Latepayment() public payable { 61 | require(block.timestamp - finaltime > 1 days,"No late Payment option"); 62 | uint LateDays = (block.timestamp - finaltime) / 1 days ; 63 | uint compensationTotal = LateDays * compensation; // for each day compensation 64 | uint limit = id+1; 65 | for (uint i=0 ; i < limit ; i++){ 66 | address add = (company_Wallet[i].employeeAdd); 67 | uint SalaryPerPerson = company_Wallet[i].salary * 1 ether + compensationTotal; // units are in ether converting 68 | payable(add).transfer(SalaryPerPerson); 69 | } 70 | finaltime = block.timestamp + 100 seconds; 71 | 72 | } 73 | 74 | function CompanyWalletBalance() public view returns(uint){ 75 | return address(this).balance; 76 | } 77 | 78 | function ChangeSalaryofEmployee(address _empadd, uint _newsalary) public onlyOwner{ 79 | require(salaryInfo[_empadd]>0,"Register for a employee"); 80 | require(_newsalary>0,"Please check newsalary balance"); 81 | salaryInfo[_empadd] = _newsalary; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /contracts/Shared Wallet/SharedWallet.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | 5 | contract SharedWallet { 6 | address private _owner; 7 | 8 | mapping(address => bool) private _owners; 9 | 10 | // required owner of the contract 11 | modifier isOwner() { 12 | require(msg.sender == _owner, "Not a contract owner"); 13 | _; 14 | } 15 | 16 | // checks if a user is contract owner or one of owners of a shared wallet 17 | modifier validOwner() { 18 | require(msg.sender == _owner || _owners[msg.sender], "Not contract owner or part of owners of shared wallet"); 19 | _; 20 | } 21 | 22 | event DepositFunds(address from, uint256 amount); 23 | event WithdrawFunds(address from, uint256 amount); 24 | event TransferFunds(address from, address to, uint256 amount); 25 | 26 | constructor() { 27 | _owner = msg.sender; 28 | } 29 | 30 | // add an owner of shared wallet 31 | function addOwner(address owner) public isOwner { 32 | _owners[owner] = true; 33 | } 34 | 35 | // remove an owner of shared wallet 36 | function removeOwner(address owner) public isOwner { 37 | _owners[owner] = false; 38 | } 39 | 40 | // Add the deposit into shared wallet 41 | receive() external payable { 42 | emit DepositFunds(msg.sender, msg.value); 43 | } 44 | 45 | // withdraw fund from the shared wallet into the signer of transaction 46 | function withdraw(uint256 amount) public validOwner { 47 | require(address(this).balance >= amount); 48 | payable(msg.sender).transfer(amount); 49 | emit WithdrawFunds(msg.sender, amount); 50 | } 51 | 52 | // transfer fund from the shared wallet into another address 53 | function transferTo(address payable to, uint256 amount) public validOwner { 54 | require(address(this).balance >= amount); 55 | payable(to).transfer(amount); 56 | emit TransferFunds(msg.sender, to, amount); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /contracts/Supplychain/supplychain.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.8.9; 4 | pragma experimental ABIEncoderV2; 5 | 6 | contract Supplychain { 7 | //product structure initialization 8 | struct S_Item { 9 | uint256 _index; 10 | string _identifier; 11 | uint256 _priceInWei; 12 | } 13 | 14 | //product stats initalization 15 | struct ProductDetails { 16 | uint256 _count; 17 | uint256 _total; 18 | } 19 | 20 | //mapping index to product stats 21 | mapping(uint256 => ProductDetails) public productData; 22 | 23 | //stores all products in array 24 | S_Item[] public productArr; 25 | 26 | //map that stores the item details with item index 27 | mapping(uint256 => S_Item) public items; 28 | 29 | //initialized items index variable 30 | uint256 index; 31 | 32 | enum SupplyChainSteps { 33 | Created, 34 | Paid, 35 | Delivered 36 | } 37 | 38 | //user can create item 39 | function createItem(string memory _identifier, uint256 _priceInWei) public { 40 | items[index]._priceInWei = _priceInWei; 41 | 42 | items[index]._identifier = _identifier; 43 | items[index]._index = index; 44 | productArr.push(items[index]); 45 | //index is incremented 46 | index++; 47 | } 48 | 49 | //function for getting specific product details using index 50 | function getProduct(uint256 ind) public view returns (S_Item memory) { 51 | return items[ind]; 52 | } 53 | 54 | //this function returns array of products 55 | function getProductArray() public view returns (S_Item[] memory) { 56 | return productArr; 57 | } 58 | 59 | //function that gives stats like how many number of products sold and total revenue generated from each product 60 | function Stats(uint256 ind, uint256 amount) public { 61 | productData[ind]._count += 1; 62 | productData[ind]._total += amount; 63 | } 64 | 65 | //payment for each item done from front-end using web.eth.sendTransaction() method amount stored in specofic address in our local blockchain like "GANACHE" 66 | } 67 | -------------------------------------------------------------------------------- /contracts/TimeLock/TestCoin.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | 4 | import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; 5 | 6 | contract TestCoin is ERC20 { 7 | constructor() ERC20('Test Coin', 'TCK') { 8 | _mint(msg.sender, 20 * 10 ** 18); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /contracts/TimeLock/TimeLock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.9; 3 | //0xd9145CCE52D386f254917e481eB44e9943F39138 4 | 5 | import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; 6 | 7 | contract TimeLock{ 8 | 9 | uint public immutable endTime; //end time 10 | address payable public immutable owner; 11 | 12 | constructor(address payable _owner, uint duration_in_seconds){ 13 | endTime = block.timestamp + duration_in_seconds; 14 | owner = _owner; 15 | } 16 | 17 | function deposit(address token, uint amount) external { 18 | 19 | IERC20(token).transferFrom(msg.sender, address(this), amount); 20 | } 21 | 22 | receive() external payable {} 23 | 24 | function withdraw(address token, uint amount) external { 25 | require(msg.sender == owner, "Only owner can withdraw"); 26 | require(block.timestamp >= endTime, "Cannot withdraw before endTime"); 27 | 28 | //number of tokens = 0, so we are just withdrawing ETH 29 | if(token == address(0)){ 30 | owner.transfer(amount); 31 | } 32 | else { 33 | IERC20(token).transfer(owner, amount); 34 | } 35 | 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /contracts/Voting/Election.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.4; 3 | 4 | contract Election { 5 | 6 | // It will represent a single voter. 7 | struct Voter { 8 | uint weight; // weight is accumulated by delegation 9 | bool voted; // if true, that person already voted 10 | address delegate; // person delegated to 11 | uint vote; // index of the voted proposal 12 | } 13 | 14 | // This is a type for a single proposal. 15 | struct Proposal { 16 | string name; // short name 17 | uint voteCount; // number of accumulated votes 18 | } 19 | 20 | address public chairperson; 21 | 22 | // This declares a state variable that 23 | // stores a `Voter` struct for each possible address. 24 | mapping(address => Voter) public voters; 25 | 26 | // A dynamically-sized array of `Proposal` structs. 27 | Proposal[] public proposals; 28 | 29 | /// Create a new ballot to choose one of `proposalNames`. 30 | constructor(string[] memory proposalNames) { 31 | chairperson = msg.sender; 32 | voters[chairperson].weight = 1; 33 | 34 | // For each of the provided proposal names, 35 | // create a new proposal object and add it 36 | // to the end of the array. 37 | for (uint i = 0; i < proposalNames.length; i++) { 38 | 39 | proposals.push(Proposal({ 40 | name: proposalNames[i], 41 | voteCount: 0 42 | })); 43 | } 44 | } 45 | 46 | // Give `voter` the right to vote on this ballot. 47 | // May only be called by `chairperson`. 48 | function giveRightToVote(address voter) external { 49 | require( 50 | msg.sender == chairperson, 51 | "Only chairperson can give right to vote." 52 | ); 53 | require( 54 | !voters[voter].voted, 55 | "The voter already voted." 56 | ); 57 | require(voters[voter].weight == 0); 58 | voters[voter].weight = 1; 59 | } 60 | 61 | /// Delegate your vote to the voter `to`. 62 | function delegate(address to) external { 63 | // assigns reference 64 | Voter storage sender = voters[msg.sender]; 65 | require(sender.weight != 0, "You have no right to vote"); 66 | require(!sender.voted, "You already voted."); 67 | 68 | require(to != msg.sender, "Self-delegation is disallowed."); 69 | while (voters[to].delegate != address(0)) { 70 | to = voters[to].delegate; 71 | require(to != msg.sender, "Found loop in delegation."); 72 | } 73 | 74 | Voter storage delegate_ = voters[to]; 75 | 76 | // Voters cannot delegate to accounts that cannot vote. 77 | require(delegate_.weight >= 1); 78 | 79 | // Since `sender` is a reference, this 80 | // modifies `voters[msg.sender]`. 81 | sender.voted = true; 82 | sender.delegate = to; 83 | 84 | if (delegate_.voted) { 85 | // If the delegate already voted, 86 | // directly add to the number of votes 87 | proposals[delegate_.vote].voteCount += sender.weight; 88 | } else { 89 | // If the delegate did not vote yet, 90 | // add to her weight. 91 | delegate_.weight += sender.weight; 92 | } 93 | } 94 | 95 | /// Give your vote (including votes delegated to you) 96 | /// to proposal `proposals[proposal].name`. 97 | function vote(uint proposal) external { 98 | Voter storage sender = voters[msg.sender]; 99 | require(sender.weight != 0, "Has no right to vote"); 100 | require(!sender.voted, "Already voted."); 101 | sender.voted = true; 102 | sender.vote = proposal; 103 | 104 | // If `proposal` is out of the range of the array, 105 | // this will throw automatically and revert all 106 | // changes. 107 | proposals[proposal].voteCount += sender.weight; 108 | } 109 | function winningProposal() public view 110 | returns (uint winningProposal_) 111 | { 112 | uint winningVoteCount = 0; 113 | for (uint p = 0; p < proposals.length; p++) { 114 | if (proposals[p].voteCount > winningVoteCount) { 115 | winningVoteCount = proposals[p].voteCount; 116 | winningProposal_ = p; 117 | } 118 | } 119 | } 120 | 121 | // Calls winningProposal() function to get the index 122 | // of the winner contained in the proposals array and then 123 | // returns the name of the winner 124 | function winnerName() external view 125 | returns (string memory winnerName_) 126 | { 127 | winnerName_ = proposals[winningProposal()].name; 128 | } 129 | } -------------------------------------------------------------------------------- /contracts/Voting/README.md: -------------------------------------------------------------------------------- 1 | # While deploying Contract, constructor takes Array of String (Participants). 2 | 3 | ![image](https://user-images.githubusercontent.com/96972634/193524186-8deea2e3-8298-4cc9-a1ad-0901b1cb99f2.png) 4 | 5 | # After Deployement List of Functions are available to interact 6 | 7 | ![image](https://user-images.githubusercontent.com/96972634/193524519-d7e3305b-d67e-4c9a-9a72-f0a89db3aff6.png) 8 | 9 | provide voter's address in (giveRightToVote) function. to vote you have to provide Index value of the person you want to vote in (vote) function. 10 | -------------------------------------------------------------------------------- /contracts/blockDNS/Description.md: -------------------------------------------------------------------------------- 1 | # blockDNS 2 | 3 | blockDNS is highly basic implementation of the Domain Name System server built using ethereum. The smart contract is developed in solidity. 4 | DNS translates domain names into corresponding ip addresses so the browser can load the internet resources. 5 | 6 | 7 | https://antoprince001.medium.com/developing-a-blockchain-based-domain-name-system-dns-with-ethereum-c631d8c67bbd 8 | -------------------------------------------------------------------------------- /contracts/blockDNS/dns.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.0; 3 | 4 | contract Dns{ 5 | 6 | 7 | struct Domain{ 8 | string domainName; 9 | string A_Record; 10 | string CNAME; 11 | string TXT; 12 | string NS_Record; 13 | string SOA_Record; 14 | bool exists; 15 | } 16 | 17 | mapping (string => Domain) public nameserver; 18 | 19 | 20 | 21 | function addDomain(string memory _domainName , string memory _A_Record , string memory _CNAME, string memory _TXT ,string memory _NS_Record, string memory _SOA_Record) public returns(bool) { 22 | require(nameserver[_domainName].exists == false,"IP mapping already exists"); 23 | 24 | Domain memory new_domain = Domain(_domainName,_A_Record,_CNAME,_TXT,_NS_Record,_SOA_Record,true); 25 | nameserver[_domainName] = new_domain; 26 | 27 | return true; 28 | } 29 | 30 | 31 | function dnsLookup(string memory _domainName) public view returns (string memory,string memory,string memory,string memory, string memory){ 32 | require(nameserver[_domainName].exists == true,"DNS not configured yet for the domain"); 33 | 34 | return ( nameserver[_domainName].A_Record, nameserver[_domainName].CNAME, nameserver[_domainName].TXT,nameserver[_domainName].NS_Record,nameserver[_domainName].SOA_Record); 35 | } 36 | 37 | function modifyARecord(string memory _domainName, string memory _A_Record) public returns (bool){ 38 | require(nameserver[_domainName].exists == true,"DNS not configured yet for the domain"); 39 | 40 | nameserver[_domainName].A_Record = _A_Record; 41 | return true; 42 | 43 | } 44 | 45 | function modifyCNAMERecord(string memory _domainName, string memory _CNAME) public returns (bool){ 46 | require(nameserver[_domainName].exists == true,"DNS not configured yet for the domain"); 47 | 48 | nameserver[_domainName].CNAME = _CNAME; 49 | return true; 50 | 51 | } 52 | 53 | function modifyTXTRecord(string memory _domainName,string memory _TXT) public returns (bool){ 54 | require(nameserver[_domainName].exists == true,"DNS not configured yet for the domain"); 55 | 56 | nameserver[_domainName].TXT = _TXT; 57 | return true; 58 | } 59 | 60 | function modifyNSRecord(string memory _domainName,string memory _NS_Record) public returns (bool){ 61 | require(nameserver[_domainName].exists == true,"DNS not configured yet for the domain"); 62 | 63 | nameserver[_domainName].NS_Record = _NS_Record; 64 | return true; 65 | } 66 | 67 | function modifySOARecord(string memory _domainName,string memory _SOA_Record) public returns (bool){ 68 | require(nameserver[_domainName].exists == true,"DNS not configured yet for the domain"); 69 | 70 | nameserver[_domainName].SOA_Record = _SOA_Record; 71 | return true; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomicfoundation/hardhat-toolbox"); 2 | // require("@nomiclabs/hardhat-ethers"); 3 | // require("@nomiclabs/hardhat-waffle"); 4 | 5 | /** @type import('hardhat/config').HardhatUserConfig */ 6 | module.exports = { 7 | solidity: "0.8.10", 8 | }; 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "metafy-smart-contracts-hacktoberfest", 3 | "devDependencies": { 4 | "@nomicfoundation/hardhat-network-helpers": "^1.0.0", 5 | "@nomicfoundation/hardhat-toolbox": "^1.0.2", 6 | "hardhat": "^2.11.1" 7 | }, 8 | "dependencies": { 9 | "@aave/core-v3": "^1.16.2", 10 | "@chainlink/contracts": "^0.5.1", 11 | "@nomicfoundation/hardhat-chai-matchers": "^1.0.0", 12 | "@nomiclabs/hardhat-ethers": "^2.0.0", 13 | "@nomiclabs/hardhat-etherscan": "^3.0.0", 14 | "@openzeppelin/contracts": "^4.7.3", 15 | "@typechain/ethers-v5": "^10.1.0", 16 | "@typechain/hardhat": "^6.1.2", 17 | "@types/mocha": "^9.1.0", 18 | "chai": "^4.2.0", 19 | "ethers": "^5.0.0", 20 | "hardhat-gas-reporter": "^1.0.8", 21 | "solidity-coverage": "^0.7.21", 22 | "ts-node": ">=8.0.0", 23 | "typechain": "^8.1.0", 24 | "typescript": ">=4.5.0" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /scripts/deploy.js: -------------------------------------------------------------------------------- 1 | // We require the Hardhat Runtime Environment explicitly here. This is optional 2 | // but useful for running the script in a standalone fashion through `node