Skip to content

Instantly share code, notes, and snippets.

@gauss314
Created June 11, 2022 06:47
Show Gist options
  • Save gauss314/33b0b0af0317c85f26dd69cfde59b297 to your computer and use it in GitHub Desktop.
Save gauss314/33b0b0af0317c85f26dd69cfde59b297 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.14+commit.80d49f37.js&optimize=false&runs=200&gist=
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.14;
contract Crud {
address public owner;
constructor () {
owner = msg.sender;
}
struct User {
uint256 id;
string name;
string curso;
uint256 createdAt;
}
User [] public users;
uint256 public nextId;
modifier onlyOwner(){
require(msg.sender == owner, "Only owner can emit new certificate");
_;
}
function createUser(string memory _name, string memory _curso) public onlyOwner {
users.push (User(
nextId,
_name,
_curso,
block.timestamp
));
nextId++;
}
function findByNameFirst (string memory _name) public view returns(User memory _user) {
for (uint256 i=0; i<users.length; i++){
if ( keccak256(abi.encodePacked(_name)) == keccak256(abi.encodePacked(users[i].name)) ) {
_user = users[i];
}
}
return _user;
}
function findByNameList (string memory _name) public view returns( uint256 [] memory) {
uint[] memory _ids = new uint[](users.length);
for (uint256 i=0; i<users.length; i++){
if ( keccak256(abi.encodePacked(_name)) == keccak256(abi.encodePacked(users[i].name)) ) {
_ids[i]=i;
}else{
_ids[i]=999999;
}
}
return _ids;
}
function findById (uint256 _id) public view returns (string memory, string memory, uint256){
return (users[_id].name, users[_id].curso, users[_id].createdAt);
}
function update(uint256 _id, string memory _name, string memory _curso) public onlyOwner {
if (keccak256(bytes(_name)) != keccak256(bytes(""))) {
users[_id].name = _name;
}
if (keccak256(bytes(_curso)) != keccak256(bytes(""))) {
users[_id].curso = _curso;
}
}
function deleteById (uint256 _id) public onlyOwner {
delete users[_id];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment