main.sw
contract;
mod types;
use types::{User, Post, Comment, message, states};
use std::storage::storage_vec::*;
storage {
map: StorageMap<Address, User> = StorageMap {},
posts: StorageMap<u64, Post> = StorageMap {},
comments: StorageMap<u64, Comment> = StorageMap {},
id_counter: u64 = 0,
}
impl MyContract for Contract {
#[storage(read, write)]
fn initialize(name: str[30], img: str[200], desc: str[200], country: str[52], date: u64) -> states {
let sender = msg.sender().unwrap();
let entry = storage.map.get(sender).try_read();
match entry {
Some(_) => states::Error(message{msg: "User already exists"}),
None => {
let new_id = storage.id_counter.read() + 1;
let user = User{
id: new_id,
address: sender,
name: name,
img: img,
desc: desc,
country: country,
date: date,
post_count: 0,
};
storage.map.insert(sender, user);
storage.id_counter.write(new_id);
states::Success(message{msg: "User created successfully"})
}
}
}
}
types.sw
library;
use std::storage::storage_vec::*;
pub struct User {
id : u64,
address: Address,
name : str[30],
img : str[200],
desc : str[200],
country : str[52],
date : u64,
post_count : u64,
following : StorageVec<u64> = StorageVec {},
}
pub struct Post {
id : u64,
user_id : u64,
author : str[30],
date : u64,
content : str[700],
likes : StorageVec<u64> = StorageVec {},,
comment_count : u64,
}
pub struct Comment {
id : u64,
user_id : u64,
post_id : u64,
author : str[30],
date : u64,
content : str[200],
}
pub struct message {
msg: str[100],
}
pub enum states{
Success: message,
Error: message,
}