Skip to content

Commit

Permalink
fix: update logic to use fixed storage (#9)
Browse files Browse the repository at this point in the history
* update logic to use fixed storage

* update api
  • Loading branch information
miraclx authored Nov 26, 2024
1 parent 3944da8 commit 333f809
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 99 deletions.
8 changes: 2 additions & 6 deletions app/src/api/clientApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ export interface SendProposalMessageRequest {
message: Message;
}

export interface SendProposalMessageResponse {
result: boolean;
}
export interface SendProposalMessageResponse {}

export interface CreateProposalRequest {
receiver: String;
Expand All @@ -39,9 +37,7 @@ export interface ApproveProposalRequest {
proposal_id: string;
}

export interface ApproveProposalResponse {
success: boolean;
}
export interface ApproveProposalResponse {}

export enum ClientMethod {
GET_PROPOSAL_MESSAGES = 'get_proposal_messages',
Expand Down
12 changes: 2 additions & 10 deletions app/src/api/dataSource/LogicApiDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,8 @@ export class LogicApiDataSource implements ClientApi {
return await this.handleError(response.error, {}, this.approveProposal);
}

let result: ApproveProposalResponse = {
success: response?.result?.output?.success ?? false,
};

return {
data: result,
data: {},
error: null,
};
}
Expand Down Expand Up @@ -201,12 +197,8 @@ export class LogicApiDataSource implements ClientApi {
);
}

let sendMessageResponse: SendProposalMessageResponse = {
result: response?.result?.output?.result,
} as SendProposalMessageResponse;

return {
data: sendMessageResponse,
data: {},
error: null,
};
}
Expand Down
8 changes: 4 additions & 4 deletions logic/Cargo.lock

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

4 changes: 0 additions & 4 deletions logic/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ crate-type = ["cdylib"]
calimero-sdk = { git = "https://github.com/calimero-network/core", branch = "master" }
calimero-storage = { git = "https://github.com/calimero-network/core", branch = "master" }

#calimero-sdk = { path = "../../core/crates/sdk" }
#calimero-storage = { path = "../../core/crates/storage" }


[profile.app-release]
inherits = "release"
codegen-units = 1
Expand Down
127 changes: 52 additions & 75 deletions logic/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,45 +1,16 @@
use calimero_sdk::app;
use calimero_sdk::borsh::{BorshDeserialize, BorshSerialize};
use calimero_sdk::env::ext::ProposalId;
use calimero_sdk::env::{self};
use calimero_sdk::env;
use calimero_sdk::env::ext::{AccountId, ProposalId};
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(),
}
use calimero_storage::collections::{UnorderedMap, Vector};

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

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

#[derive(
Expand All @@ -55,70 +26,76 @@ pub struct Message {
created_at: String,
}

#[app::event]
pub enum Event {
ProposalCreated { id: ProposalId },
ApprovedProposal { id: ProposalId },
}

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

pub fn create_new_proposal(receiver: String) -> Result<env::ext::ProposalId, Error> {
env::log("env Call in wasm create new proposal");
let account_id = env::ext::AccountId(receiver);
pub fn create_new_proposal(&mut self, receiver: String) -> Result<ProposalId, Error> {
let account_id = AccountId(receiver);

let amount = 1_000_000_000_000_000_000_000;

let proposal_id = Self::external()
.propose()
.transfer(account_id, amount)
.send();
env::log(&format!("Create new proposal with id: {:?}", proposal_id));

env::emit(&Event::ProposalCreated { id: proposal_id });

let old = self.messages.insert(proposal_id, Vector::new())?;

if old.is_some() {
return Err(Error::msg("proposal already exists??"));
}

Ok(proposal_id)
}

pub fn approve_proposal(proposal_id: ProposalId) -> Result<bool, Error> {
env::log(&format!("Approve proposal: {:?}", proposal_id));
let _ = Self::external().approve(proposal_id);
Ok(true)
pub fn approve_proposal(&self, proposal_id: ProposalId) -> Result<(), Error> {
// fixme: should we need to check this?
// self.messages
// .get(&proposal_id)?
// .ok_or(Error::msg("proposal not found"))?;

Self::external().approve(proposal_id);

env::emit(&Event::ApprovedProposal { id: proposal_id });

Ok(())
}

pub fn get_proposal_messages(&self, proposal_id: ProposalId) -> Result<Vec<Message>, Error> {
env::log(&format!("Get messages for proposal: {:?}", proposal_id));
let res = &self.messages.get(&proposal_id).unwrap();
env::log(&format!(
"Get messages for proposal from storage: {:?}",
res
));
match res {
Some(messages) => Ok(messages.clone()),
None => Ok(vec![]),
}
let Some(msgs) = self.messages.get(&proposal_id)? else {
return Ok(vec![]);
};

let entries = msgs.entries()?;

Ok(entries.collect())
}

pub fn send_proposal_messages(
&mut self,
proposal_id: ProposalId,
message: Message,
) -> Result<bool, Error> {
env::log(&format!(
"send_proposal_messages with id : {:?}",
proposal_id
));
env::log(&format!("send_proposal_messages msg: {:?}", message));

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)
) -> Result<(), Error> {
let mut messages = self.messages.get(&proposal_id)?.unwrap_or_default();

messages.push(message)?;

self.messages.insert(proposal_id, messages)?;

Ok(())
}
}

0 comments on commit 333f809

Please sign in to comment.