Snippets

chromawallet chroma-chat

Created by Riccardo Sibani
class user { key pubkey; }

class channel {
  key name;
  admin: user;
}

class channel_member { key channel, member: user; }

class message {
  key channel, timestamp;
  index posted_by: user;
  text;
}

class balance {
  key user;
  mutable amount: integer;
}

operation init (founder_pubkey: pubkey) {
    require( (user@*{} limit 1).len() == 0 );
    val founder = create user (founder_pubkey);
    create balance (founder, 1000000);
}

function decrease_balance (user, deduct_amount: integer) {
  require( balance@{user}.amount >= deduct_amount);
  update balance@{user} (amount -= deduct_amount);
}

operation register_user (
     existing_user_pubkey: pubkey,
     new_user_pubkey: pubkey,
     transfer_amount: integer
) {
  require( is_signer(existing_user_pubkey) );
  val registration_cost = 100;
  val existing_user = user@{existing_user_pubkey};
  require( transfer_amount > 0 );
  decrease_balance(existing_user, transfer_amount + registration_cost);
  val new_user = create user (new_user_pubkey);
  create balance (new_user, transfer_amount);
}

operation create_channel ( admin_pubkey: pubkey, name) {
  require( is_signer(admin_pubkey) );
  val admin = user@{admin_pubkey};
  decrease_balance(admin, 100);
  val channel = create channel (admin, name);
  create channel_member (channel, admin);
}

operation add_channel_member (admin_pubkey: pubkey, channel_name: name, member_pubkey: pubkey) {
  require( is_signer(admin_pubkey) );
  val admin_usr = user@{admin_pubkey};
  decrease_balance(admin_usr, 1);
  val channel = channel@{channel_name, admin==user@{admin_pubkey}};
  create channel_member (channel, member=user@{member_pubkey});
}


operation post_message (channel_name: name, pubkey, message: text, nop: byte_array) {
  require( is_signer(pubkey) );
  val channel = channel@{channel_name};
  val member = user@{pubkey};
  require( channel_member@?{channel, member} );
  decrease_balance(member, 1);
  create message (channel, member, text=message, op_context.last_block_time);
}

query get_last_messages(channel_name: name) {
    return message@*{ channel@{channel_name} }
        ( text, poster_pubkey=posted_by.pubkey, -sort timestamp );
}

query get_last_message(channel_name: name) {
    return message@?{channel@{channel_name} } (text, poster_pubkey=posted_by.pubkey, -sort timestamp) limit 1;
}


query get_balance(user_pubkey: text) {
   return balance@{user@{byte_array(user_pubkey)}}.amount;
}

query get_channels(user_pubkey: text) {
    return channel_member@*{member=user@{byte_array(user_pubkey)}}.channel.name;
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.