Skip to content

Commit

Permalink
Merge branch 'master' into introduce-encryption-key-broadcast2
Browse files Browse the repository at this point in the history
  • Loading branch information
petarjuki7 committed Nov 10, 2024
2 parents 0feaf62 + 3837b0d commit 9d0f433
Show file tree
Hide file tree
Showing 45 changed files with 1,884 additions and 95 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"./apps/only-peers",
"./apps/gen-ext",
"./apps/visited",
"./apps/blockchain",

"./contracts/context-config",
"./contracts/registry",
Expand Down
21 changes: 21 additions & 0 deletions apps/blockchain/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[package]
name = "blockchain"
description = "Calimero increment/decrement application"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
calimero-sdk = { path = "../../crates/sdk" }
calimero-storage = { path = "../../crates/storage" }

[profile.app-release]
inherits = "release"
codegen-units = 1
opt-level = "z"
lto = true
debug = false
panic = "abort"
overflow-checks = true
18 changes: 18 additions & 0 deletions apps/blockchain/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash
set -e

cd "$(dirname $0)"

TARGET="${CARGO_TARGET_DIR:-../../target}"

rustup target add wasm32-unknown-unknown

cargo build --target wasm32-unknown-unknown --profile app-release

mkdir -p res

cp "$TARGET/wasm32-unknown-unknown/app-release/blockchain.wasm" ./res/

if command -v wasm-opt >/dev/null; then
wasm-opt -Oz ./res/blockchain.wasm -o ./res/blockchain.wasm
fi
144 changes: 144 additions & 0 deletions apps/blockchain/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
use calimero_sdk::app;
use calimero_sdk::borsh::{BorshDeserialize, BorshSerialize};
use calimero_sdk::env::{self};
use calimero_sdk::serde::{Deserialize, Serialize};
use calimero_sdk::types::Error;
use calimero_storage::collections::UnorderedMap;
use calimero_storage::entities::Element;
use calimero_storage::AtomicUnit;

#[derive(Clone, Debug, PartialEq, PartialOrd, Deserialize)]
#[serde(crate = "calimero_sdk::serde")]
pub struct CreateProposalRequest {}

#[derive(Clone, Debug, PartialEq, PartialOrd, Deserialize)]
#[serde(crate = "calimero_sdk::serde", rename_all = "camelCase")]
pub struct GetProposalMessagesRequest {
proposal_id: String,
}

#[derive(Clone, Debug, PartialEq, PartialOrd, Deserialize)]
#[serde(crate = "calimero_sdk::serde", rename_all = "camelCase")]
pub struct SendProposalMessageRequest {
proposal_id: String,
message: Message,
}

#[app::event]
pub enum Event {
ProposalCreated(),
}

#[app::state(emits = Event)]
#[derive(AtomicUnit, Clone, Debug, PartialEq, PartialOrd)]
#[root]
#[type_id(1)]
pub struct AppState {
count: u32,
#[storage]
storage: Element,

messages: UnorderedMap<env::ext::ProposalId, Vec<Message>>,
}

#[derive(
Clone, Debug, PartialEq, PartialOrd, BorshSerialize, BorshDeserialize, Serialize, Deserialize,
)]
#[borsh(crate = "calimero_sdk::borsh")]
#[serde(crate = "calimero_sdk::serde")]
pub struct Message {
id: String,
proposal_id: String,
author: String,
text: String,
created_at: String,
}

#[app::logic]
impl AppState {
#[app::init]
pub fn init() -> AppState {
AppState {
count: 0,
storage: Element::root(),
messages: UnorderedMap::new().unwrap(),
}
}

pub fn create_new_proposal(&self, receiver: String) -> Result<bool, Error> {
env::log("env Call in wasm create new proposal");
println!("Call in wasm create new proposal {:?}", receiver);
let account_id = env::ext::AccountId("vuki.testnet".to_string());
let amount = 1;
let proposal_id = Self::external()
.propose()
.transfer(account_id, amount)
.send();

println!("Create new proposal with id: {:?}", proposal_id);

Ok(true)
}

pub fn approve_proposal(&mut self, proposal_id: String) -> Result<bool, Error> {
let proposal_id = env::ext::ProposalId(Self::string_to_u8_32(proposal_id.as_str()));

println!("Approve proposal: {:?}", proposal_id);
let _ = Self::external().approve(proposal_id);
Ok(true)
}

// Messages (discussion)
pub fn get_proposal_messages(
&self,
// request: GetProposalMessagesRequest, I cannot to this??
proposal_id: String,
) -> Result<Vec<Message>, Error> {
env::log("env Get messages for proposal");

let proposal_id = env::ext::ProposalId(Self::string_to_u8_32(proposal_id.as_str()));
let res = &self.messages.get(&proposal_id).unwrap();

match res {
Some(messages) => Ok(messages.clone()),
None => Ok(vec![]),
}
}

pub fn send_proposal_messages(
&mut self,
// request: SendProposalMessageRequest, I cannot to this?? How to use camelCase?
proposal_id: String,
message: Message,
) -> Result<bool, Error> {
env::log("env send_proposal_messages");

let proposal_id = env::ext::ProposalId(Self::string_to_u8_32(proposal_id.as_str()));

println!("Send message to proposal: {:?}", proposal_id);
let proposal_messages = self.messages.get(&proposal_id).unwrap();
match proposal_messages {
Some(mut messages) => {
messages.push(message);
self.messages.insert(proposal_id, messages)?;
}
None => {
let messages = vec![message];
self.messages.insert(proposal_id, messages)?;
}
}
Ok(true)
}

// todo there's no guarantee a proposal Id will be safely encodable as utf8, use bs58 instead
fn string_to_u8_32(s: &str) -> [u8; 32] {
let mut array = [0u8; 32]; // Initialize array with 32 zeroes
let bytes = s.as_bytes(); // Convert the string to bytes

// Copy up to 32 bytes from the string slice into the array
let len = bytes.len().min(32);
array[..len].copy_from_slice(&bytes[..len]);

array
}
}
4 changes: 2 additions & 2 deletions contracts/context-config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ license.workspace = true
crate-type = ["rlib", "cdylib"]

[dependencies]
near-sdk.workspace = true

near-sdk = { workspace = true, features = ["unstable"] }
hex.workspace = true
calimero-context-config = { path = "../../crates/context/config" }

[dev-dependencies]
Expand Down
12 changes: 9 additions & 3 deletions contracts/context-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@

use calimero_context_config::types::{Application, ContextId, ContextIdentity};
use calimero_context_config::Timestamp;
use near_sdk::store::{IterableMap, IterableSet};
use near_sdk::{near, BorshStorageKey};

use near_sdk::store::{IterableMap, IterableSet, LazyOption};
use near_sdk::{near, AccountId, BorshStorageKey};
mod guard;
mod mutate;
mod query;
Expand All @@ -23,6 +22,8 @@ const DEFAULT_VALIDITY_THRESHOLD_MS: Timestamp = 10_000;
pub struct ContextConfigs {
contexts: IterableMap<ContextId, Context>,
config: Config,
proxy_code: LazyOption<Vec<u8>>,
next_proxy_id: u64,
}

#[derive(Debug)]
Expand All @@ -36,6 +37,7 @@ struct Config {
struct Context {
pub application: Guard<Application<'static>>,
pub members: Guard<IterableSet<ContextIdentity>>,
pub proxy: Guard<AccountId>,
}

#[derive(Copy, Clone, Debug, BorshStorageKey)]
Expand All @@ -44,6 +46,7 @@ enum Prefix {
Contexts,
Members(ContextId),
Privileges(PrivilegeScope),
ProxyCode,
}

#[derive(Copy, Clone, Debug)]
Expand All @@ -57,6 +60,7 @@ enum PrivilegeScope {
enum ContextPrivilegeScope {
Application,
MemberList,
Proxy,
}

impl Default for ContextConfigs {
Expand All @@ -66,6 +70,8 @@ impl Default for ContextConfigs {
config: Config {
validity_threshold_ms: DEFAULT_VALIDITY_THRESHOLD_MS,
},
proxy_code: LazyOption::new(Prefix::ProxyCode, None),
next_proxy_id: 0,
}
}
}
Expand Down
Loading

0 comments on commit 9d0f433

Please sign in to comment.