Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 68 additions & 51 deletions contract/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{near_bindgen, env, setup_alloc, AccountId};
use near_sdk::serde::{Serialize, Deserialize};
use near_sdk::collections::UnorderedMap;
use near_sdk::serde::{Deserialize, Serialize};
use near_sdk::{env, near_bindgen, setup_alloc, AccountId};
use serde_json::json;
use std::collections::HashSet;
use std::convert::From;
use serde_json::json;

setup_alloc!();

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct GuildsPlatform {
guilds: UnorderedMap<String, UpgradableGuild>,
users: UnorderedMap<AccountId, HashSet<String>>
users: UnorderedMap<AccountId, HashSet<String>>,
}

//Initializing the contract
impl Default for GuildsPlatform {
fn default() -> Self {
Self {
guilds: UnorderedMap::new(b"g".to_vec()),
users: UnorderedMap::new(b"u".to_vec())
}
Self {
guilds: UnorderedMap::new(b"g".to_vec()),
users: UnorderedMap::new(b"u".to_vec()),
}
}
}
}

/// Default trait for Guild
impl Default for Guild {
Expand All @@ -49,7 +49,7 @@ pub enum UpgradableGuild {
impl From<UpgradableGuild> for Guild {
fn from(guild: UpgradableGuild) -> Self {
match guild {
UpgradableGuild::CurrentVersion(guild) => guild,
UpgradableGuild::CurrentVersion(guild) => guild,
}
}
}
Expand All @@ -63,60 +63,71 @@ pub struct Guild {

#[near_bindgen]
impl GuildsPlatform {
pub fn create_guild(&mut self, slug: String)
{
match self.guilds.get(&slug){
pub fn create_guild(&mut self, slug: String) {
match self.guilds.get(&slug) {
Some(_value) => {
self.create_log("error","create_guild",&slug,"The guild already exists.");
},
self.create_log("error", "create_guild", &slug, "The guild already exists.");
}
None => {
let guild = UpgradableGuild::CurrentVersion(Guild {
slug: String::from(&slug),
members: HashSet::new(),
});

self.guilds.insert(&slug, &guild);
self.create_log("success","create_guild",&slug,"A new guild was created.");
self.create_log("success", "create_guild", &slug, "A new guild was created.");
}
}
}

pub fn get_guild_info(&self, slug: String) -> Guild {
let guild: Guild = self.guilds.get(&slug).unwrap_or_default().into();

return guild
return guild;
}

pub fn join_guild(&mut self, slug: String) {

if self.guild_exists(&slug){
if self.guild_exists(&slug) {
let mut guild: Guild = self.guilds.get(&slug).unwrap_or_default().into();
let account_to_insert = env::predecessor_account_id();

if guild.members.get(&account_to_insert).is_none() {
guild.members.insert(String::from(&account_to_insert));
self.guilds.insert(&slug,&UpgradableGuild::CurrentVersion(guild));
self.guilds
.insert(&slug, &UpgradableGuild::CurrentVersion(guild));

let mut user_list: HashSet<AccountId>;
match self.check_if_user(){
match self.check_if_user() {
true => {
user_list = self.users.get(&env::predecessor_account_id()).unwrap_or_default();
},
user_list = self
.users
.get(&env::predecessor_account_id())
.unwrap_or_default();
}
false => {
user_list = HashSet::new();
}
};

user_list.insert(slug.to_string());
self.users.insert(&env::predecessor_account_id(),&user_list);

self.create_log("success","join_guild",&slug,"The user joined a guild successfully.");
}
else{
self.create_log("error","join_guild",&slug,"The was already member of the guild.");
self.users
.insert(&env::predecessor_account_id(), &user_list);

self.create_log(
"success",
"join_guild",
&slug,
"The user joined a guild successfully.",
);
} else {
self.create_log(
"error",
"join_guild",
&slug,
"The was already member of the guild.",
);
}
}

}

pub fn get_num_members(&self, slug: String) -> usize {
Expand All @@ -126,14 +137,14 @@ impl GuildsPlatform {
}

/// Returns true if the guild exists
pub fn guild_exists(&self, slug: &String) ->bool {
pub fn guild_exists(&self, slug: &String) -> bool {
match self.guilds.get(&slug) {
Some(_value) => {
self.create_log("success","guild_exists",&slug,"The guild exists.");
self.create_log("success", "guild_exists", &slug, "The guild exists.");
true
},
}
None => {
self.create_log("error","guild_exists",&slug,"The guild doesn't exist.");
self.create_log("error", "guild_exists", &slug, "The guild doesn't exist.");
false
}
}
Expand Down Expand Up @@ -161,38 +172,44 @@ impl GuildsPlatform {
true => {
guild = self.guilds.get(&slug).unwrap_or_default().into();
return guild.members;
},
}
false => {
self.create_log("error","get_member_list",&slug,"The guild doesn't exist.");
self.create_log(
"error",
"get_member_list",
&slug,
"The guild doesn't exist.",
);
return HashSet::<AccountId>::new();
}
};
}

//Checks if the current user is already registered in our platform
pub fn check_if_user(&self) -> bool {
match self.users.get(&env::predecessor_account_id()) {
Some(_user) => true,
None => {
self.create_log("error","check_if_user","none","The user is not part of any guild.");
self.create_log(
"error",
"check_if_user",
"none",
"The user is not part of any guild.",
);
false
},
}
}
}

//Gets the list of guilds a user is part of
pub fn get_guilds_by_user(&self) -> HashSet<String> {
match self.check_if_user() {
true => {
self.users.get(&env::predecessor_account_id()).unwrap_or_default()
},
false => {
HashSet::<String>::new()
},
pub fn get_guilds_by_user(&self, user: String) -> HashSet<String> {
match self.users.get(&user) {
Some(user) => user,
None => HashSet::<String>::new(),
}
}

fn create_log(&self, result: &str, method: &str, slug: &str, msg: &str){
fn create_log(&self, result: &str, method: &str, slug: &str, msg: &str) {
let log_msg = json!({
"result": &result,
"method": &method,
Expand All @@ -201,7 +218,7 @@ impl GuildsPlatform {
"date": env::block_timestamp(),
"message": msg
});
env::log(format!("{}",log_msg.to_string()).as_bytes());
env::log(format!("{}", log_msg.to_string()).as_bytes());
}
}

Expand Down
92 changes: 78 additions & 14 deletions contract/subgraph-guilds-directory/src/mapping.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { near, log, BigInt, json, JSONValueKind } from "@graphprotocol/graph-ts";
import { near, log, BigInt, json, JSONValueKind, JSONValue } from "@graphprotocol/graph-ts";
import { Member, Guild } from "../generated/schema";

export function handleReceipt(receipt: near.ReceiptWithOutcome): void {
const actions = receipt.receipt.actions;

for (let i = 0; i < actions.length; i++) {

handleAction(
actions[i],
receipt.receipt,
Expand All @@ -15,6 +16,60 @@ export function handleReceipt(receipt: near.ReceiptWithOutcome): void {
}
}

class GuildLog {
result: string;
method: string;
guild: string;
user: string;
message: string;
log: string;

constructor(){

this.result = "";
this.method = "";
this.guild = "";
this.user = "";
this.message = "";
this.log = "";
}
}

function createGuildLog(value: string): GuildLog{
let obj = json.fromString(value).toObject();
let newLog = new GuildLog();

//It has to be written this way... ternary operator doesn't work
let res = obj.get("result");
if(res != null){
newLog.result = res.toString();
}

let met = obj.get("method");
if(met != null){
newLog.method = met.toString();
}

let gld = obj.get("guild");
if(gld != null){
newLog.guild = gld.toString();
}

let usr = obj.get("user");
if(usr != null){
newLog.user = usr.toString();
}

let msg = obj.get("message");
if(msg != null){
newLog.message = msg.toString();
}
newLog.log = value;

return newLog;

}

function handleAction(
action: near.ActionValue,
receipt: near.ActionReceipt,
Expand All @@ -32,6 +87,8 @@ function handleAction(

// change the methodName here to the methodName emitting the log in the contract
if (functionCall.methodName == "join_guild") {
let result: GuildLog;

const receiptId = receipt.id.toBase58();

// Maps the formatted log to the LOG entity
Expand All @@ -51,14 +108,17 @@ function handleAction(
members.executorId = outcome.executorId
members.outcomeBlockHash = outcome.blockHash.toBase58()

// Log parsing
if(outcome.logs != null && outcome.logs.length > 0){
members.log = outcome.logs[0]
let splitString = outcome.logs[0].split(' ')
if(splitString != null){
members.member = splitString[0].slice(1, -1)
members.guild = splitString[3].slice(1, -2)
for(let i = 0; i < outcome.logs.length; i++){
result = createGuildLog(outcome.logs[i]);

if(result.method == "join_guild" && result.result == "error"){
return;
}
}
members.log = result.log;
members.member = result.user;
members.guild = result.guild;
}

members.save()
Expand All @@ -69,6 +129,7 @@ function handleAction(

// change the methodName here to the methodName emitting the log in the contract
if (functionCall.methodName == "create_guild") {
let result: GuildLog;
const receiptId = receipt.id.toBase58();

// Maps the formatted log to the LOG entity
Expand All @@ -87,14 +148,17 @@ function handleAction(
guilds.outcomeId = outcome.id.toBase58()
guilds.executorId = outcome.executorId
guilds.outcomeBlockHash = outcome.blockHash.toBase58()

// Log parsing

if(outcome.logs != null && outcome.logs.length > 0){
guilds.log = outcome.logs[0]
let splitString = outcome.logs[0].split(' ')
if(splitString != null){
guilds.guild = splitString[2].slice(1, -1)
for(let i = 0; i < outcome.logs.length; i++){
result = createGuildLog(outcome.logs[i]);

if(result.method == "create_guild" && result.result == "error"){
return;
}
}
guilds.log = result.log;
guilds.guild = result.guild;
}

guilds.save()
Expand Down