Skip to content

Commit

Permalink
Merge pull request #11 from B3Pay/update
Browse files Browse the repository at this point in the history
Update request bug
  • Loading branch information
b3hr4d authored Jul 8, 2023
2 parents 4287d21 + 86a8cec commit 6d97610
Show file tree
Hide file tree
Showing 40 changed files with 494 additions and 144 deletions.
8 changes: 4 additions & 4 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion backend/b3_system/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "b3_system"
version = "0.0.15"
version = "0.0.16"
edition = "2021"

[lib]
Expand Down
1 change: 1 addition & 0 deletions backend/b3_system/b3_system.did
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ service : () -> {
get_canister_version_by_user : (principal, nat64) -> (text);
get_canisters : () -> (vec principal) query;
get_controllers : () -> (vec principal) query;
get_create_canister_wallet_cycle : () -> (nat) query;
get_release : (text, text) -> (Release) query;
get_release_by_hash_string : (text, vec nat8) -> (Release) query;
get_release_by_index : (text, nat64) -> (Release) query;
Expand Down
10 changes: 8 additions & 2 deletions backend/b3_system/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{str::FromStr, vec};

use crate::guard::caller_is_controller;
use b3_helper_lib::{
constants::CREATE_SIGNER_CANISTER_CYCLES,
constants::CREATE_WALLET_CANISTER_CYCLES,
release::ReleaseName,
revert,
types::{CanisterId, SignerId, Version, WalletCanisterInitArgs},
Expand Down Expand Up @@ -33,6 +33,12 @@ fn get_states() -> UserState {
with_state(|s| s.user_state(user_id)).unwrap_or_else(revert)
}

#[candid_method(query)]
#[query]
fn get_create_canister_wallet_cycle() -> u128 {
CREATE_WALLET_CANISTER_CYCLES
}

#[candid_method(query)]
#[query(guard = "caller_is_controller")]
fn get_user_ids() -> Vec<SignerId> {
Expand Down Expand Up @@ -84,7 +90,7 @@ async fn create_wallet_canister(name: String) -> Result<UserState, String> {
let mut user_state = with_state_mut(|s| s.init_user(owner_id)).unwrap_or_else(revert);

let wallet_canister = user_state
.create_with_cycles(vec![owner_id, system_id], CREATE_SIGNER_CANISTER_CYCLES)
.create_with_cycles(vec![owner_id, system_id], CREATE_WALLET_CANISTER_CYCLES)
.await
.unwrap_or_else(revert);

Expand Down
2 changes: 1 addition & 1 deletion backend/b3_wallet/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "b3_wallet"
version = "0.0.0-alpha.30"
version = "0.0.0-alpha.32"
edition = "2021"

[lib]
Expand Down
7 changes: 4 additions & 3 deletions backend/b3_wallet/b3_wallet.did
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ type Request = variant {
type RequestStatus = variant { Fail; Success; Expired; Pending };
type Response = variant { Reject; Confirm };
type Result = variant { Ok : nat; Err : text };
type Result_1 = variant { Ok : ProcessedRequest; Err : text };
type RetrieveBtcStatus = variant {
Signing;
Confirmed : record { txid : vec nat8 };
Expand Down Expand Up @@ -430,6 +431,7 @@ service : () -> {
is_connected : () -> (bool) query;
load_wasm : (vec nat8) -> (nat64);
name : () -> (text) query;
process_request : (nat64) -> ();
refresh_settings : () -> ();
remove_setting_metadata : (text) -> ();
request_account_rename : (RenameAccount, text, opt nat64) -> (nat64);
Expand All @@ -439,15 +441,14 @@ service : () -> {
request_delete_account : (HideAccount, text, opt nat64) -> (nat64);
request_maker : (Request, text, opt nat64) -> (nat64);
request_send : (SendToken, text, opt nat64) -> (nat64);
request_sign_message : (text, vec nat8) -> (vec nat8);
request_sign_transaction : (text, vec nat8, nat64) -> (vec nat8);
request_transfer_btc : (BtcTransfer, text, opt nat64) -> (nat64);
request_transfer_icp : (IcpTransfer, text, opt nat64) -> (nat64);
request_update_settings : (UpdateCanisterSettings, text, opt nat64) -> (
nat64,
);
request_upgrade_canister : (text) -> (nat64);
reset_accounts : () -> ();
response : (nat64, Response) -> (ProcessedRequest);
response : (nat64, Response) -> (Result_1);
retrieve_btc_status : (Minter, nat64) -> (RetrieveBtcStatus) query;
setting_and_signer : () -> (WalletSettingsAndSigners) query;
signer_add : (principal, Roles) -> (vec record { principal; Signer });
Expand Down
37 changes: 28 additions & 9 deletions backend/b3_wallet/src/processed.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::permit::caller_is_signer;
use crate::permit::{caller_is_admin, caller_is_signer};
use b3_helper_lib::{revert, types::RequestId};
use b3_permit_lib::{
error::PermitError,
processed::processed::ProcessedRequest,
store::{with_pending_mut, with_permit, with_permit_mut, with_processed_request},
types::{ProcessedRequestList, Response},
Expand All @@ -25,7 +26,7 @@ pub fn get_processed_list() -> ProcessedRequestList {

#[candid_method(update)]
#[update(guard = "caller_is_signer")]
pub async fn response(request_id: RequestId, answer: Response) -> ProcessedRequest {
pub async fn response(request_id: RequestId, answer: Response) -> Result<ProcessedRequest, String> {
let caller = ic_cdk::caller();

let request = with_pending_mut(&request_id, |request| {
Expand All @@ -42,20 +43,38 @@ pub async fn response(request_id: RequestId, answer: Response) -> ProcessedReque
if request.is_failed() {
let processed = ProcessedRequest::from(request);

with_permit_mut(|s| s.insert_processed(request_id, processed.clone()))
.unwrap_or_else(revert);
if let Err(err) = with_permit_mut(|s| s.insert_processed(request_id, processed.clone())) {
return Err(err.to_string());
}

return processed;
return Ok(processed);
}

if request.is_confirmed() {
let processed = request.execute().await;

with_permit_mut(|s| s.insert_processed(request_id, processed.clone()))
.unwrap_or_else(revert);
if let Err(err) = with_permit_mut(|s| s.insert_processed(request_id, processed.clone())) {
return Err(err.to_string());
}

return processed;
return Ok(processed);
}

request.into()
Ok(request.into())
}

#[candid_method(update)]
#[update(guard = "caller_is_admin")]
pub fn process_request(request_id: RequestId) {
let caller = ic_cdk::caller();

with_permit_mut(|s| {
let mut processed: ProcessedRequest =
s.request(&request_id).unwrap_or_else(revert).clone().into();

processed.fail(PermitError::RequestRemovedByAdmin(caller.to_string()));

s.insert_processed(request_id, processed)
.unwrap_or_else(revert);
});
}
59 changes: 32 additions & 27 deletions backend/b3_wallet/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
permit::{caller_is_admin, caller_is_signer},
wallet::version,
};
use b3_helper_lib::{revert, time::NanoTimeStamp, types::RequestId};
use b3_helper_lib::{revert, time::NanoTimeStamp, types::RequestId, wasm::with_wasm};
use b3_permit_lib::{
pending::new::RequestArgs,
request::{
Expand All @@ -11,7 +11,7 @@ use b3_permit_lib::{
icp::transfer::IcpTransfer,
inner::{
account::{CreateAccount, RemoveAccount, RenameAccount},
setting::UpdateCanisterSettings,
setting::{UpdateCanisterSettings, UpgradeCanister},
signer::AddSigner,
},
request::{Request, RequestTrait},
Expand All @@ -20,8 +20,6 @@ use b3_permit_lib::{
store::{with_permit, with_permit_mut, with_signer_check, with_signer_ids_by_role},
types::PendingRequestList,
};
use b3_wallet_lib::ledger::subaccount::SubaccountTrait;
use b3_wallet_lib::store::with_ledger;
use ic_cdk::{export::candid::candid_method, query, update};

// QUERY ---------------------------------------------------------------------
Expand Down Expand Up @@ -101,7 +99,7 @@ pub fn request_connect() -> RequestId {
let caller = ic_cdk::caller();

let request = AddSigner {
name: "B3 Peyment".to_string(),
name: "B3Peyment".to_string(),
role: Roles::Canister,
signer_id: caller,
expires_at: None,
Expand Down Expand Up @@ -314,6 +312,8 @@ pub fn request_send(
) -> RequestId {
let caller = ic_cdk::caller();

request.validate_request().unwrap_or_else(revert);

let role = Roles::Admin;
let allowed_signers = with_signer_ids_by_role(role, |signer_ids| signer_ids.to_vec());

Expand All @@ -328,33 +328,38 @@ pub fn request_send(

with_permit_mut(|s| {
let new_request = s.new_request(caller, request_args);

s.insert_new_request(new_request)
})
}

#[candid_method(update)]
#[update(guard = "caller_is_signer")]
pub async fn request_sign_message(account_id: String, message_hash: Vec<u8>) -> Vec<u8> {
let ledger = with_ledger(&account_id, |ledger| ledger.clone()).unwrap_or_else(revert);

ledger
.subaccount
.sign_with_ecdsa(message_hash)
.await
.unwrap_or_else(revert)
}
pub async fn request_upgrade_canister(wasm_version: String) -> RequestId {
let caller = ic_cdk::caller();

#[candid_method(update)]
#[update(guard = "caller_is_signer")]
pub async fn request_sign_transaction(
account_id: String,
hex_raw_tx: Vec<u8>,
chain_id: u64,
) -> Vec<u8> {
let ledger = with_ledger(&account_id, |ledger| ledger.clone()).unwrap_or_else(revert);

ledger
.sign_evm_transaction(hex_raw_tx, chain_id)
.await
.unwrap_or_else(revert)
let upgrade_request = with_wasm(|w| UpgradeCanister {
wasm_hash_string: w.generate_hash_string(),
wasm_version,
});

upgrade_request.validate_request().unwrap_or_else(revert);

let role = Roles::Admin;
let allowed_signers = with_signer_ids_by_role(role, |signer_ids| signer_ids.to_vec());

let request_args = RequestArgs {
role,
allowed_signers,
request: upgrade_request.into(),
version: version(),
reason: "Upgrade canister".to_string(),
deadline: None,
};

with_permit_mut(|s| {
let new_request = s.new_request(caller, request_args);

s.insert_new_request(new_request)
})
}
2 changes: 1 addition & 1 deletion backend/lib/b3_helper_lib/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub const RATE_LIMIT: u64 = NanoTimeStamp::NS_PER_MINUTE;

pub const IC_TRANSACTION_FEE_ICP: Tokens = Tokens::from_e8s(10_000);

pub const CREATE_SIGNER_CANISTER_CYCLES: u128 = 1_000_000_000_000;
pub const CREATE_WALLET_CANISTER_CYCLES: u128 = 100_000_000_000;

pub const CANISTER_CREATE_MEMO: Memo = Memo(0x41455243);

Expand Down
2 changes: 1 addition & 1 deletion backend/lib/b3_permit_lib/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "b3_permit_lib"
version = "0.1.3"
version = "0.1.5"
edition = "2021"
description = "This is request library for the B3Pay project."
license = "Apache-2.0"
Expand Down
6 changes: 6 additions & 0 deletions backend/lib/b3_permit_lib/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub enum PermitError {
RequestExpired,
RequestNotFound(RequestId),
RequestAlreadyProcessed(RequestId),
RequestRemovedByAdmin(String),
SignerNotAllowed(String),
SignerNotFound(String),
SignerAlreadyExists(String),
Expand All @@ -38,6 +39,8 @@ pub enum PermitError {
InvalidController,
InvalidTransaction,
SneakyMessage,
AccountNotFound,
ChainNotFound(String, String),
ChainIdNotInitialized
}

Expand Down Expand Up @@ -67,13 +70,16 @@ impl fmt::Display for PermitError {
PermitError::RequestNotFound(ref msg) => write!(f, "Request not found: {}", msg),
PermitError::RequestAlreadySigned(ref signer) => write!(f, "Signer {} already signed", signer),
PermitError::RequestAlreadyProcessed(ref request_id) => write!(f, "Request {} already processed!", request_id),
PermitError::RequestRemovedByAdmin(ref signer) => write!(f, "Request removed by admin: {}", signer),
PermitError::WasmNotSet => write!(f, "Wasm not set!"),
PermitError::InvalidChainId(ref chain_id, ref expected_chain_id) => write!(f, "Invalid chain id! Expected: {}, got: {}", expected_chain_id, chain_id),
PermitError::InvalidAmount => write!(f, "Invalid amount!"),
PermitError::InvalidWasmHash => write!(f, "Invalid wasm hash!"),
PermitError::InvalidController => write!(f, "Invalid controller!"),
PermitError::InvalidTransaction => write!(f, "Invalid transaction!"),
PermitError::SneakyMessage => write!(f, "Sneaky message, if you want to send transaction use 'send_transaction' method!"),
PermitError::AccountNotFound => write!(f, "Account not found!"),
PermitError::ChainNotFound(ref chain_name, ref chain_id) => write!(f, "Chain {} with id {} not found!", chain_name, chain_id),
PermitError::ChainIdNotInitialized => write!(f, "Chain ID not initialized!"),
}
}
Expand Down
10 changes: 2 additions & 8 deletions backend/lib/b3_permit_lib/src/pending/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,9 @@ impl PendingRequest {

pub fn is_rejected(&self) -> bool {
let total_signers = self.allowed_signers.len();
let rejected_responses = self
.responses
.iter()
.filter(|(signer, response)| {
self.allowed_signers.contains(signer) && response.is_reject()
})
.count();
let rejected_responses = self.responses.values().filter(|r| r.is_reject()).count();

rejected_responses * 2 > total_signers
rejected_responses >= (total_signers + 1) / 2
}

pub fn is_confirmed(&self) -> bool {
Expand Down
4 changes: 2 additions & 2 deletions backend/lib/b3_permit_lib/src/processed/processed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ impl ProcessedRequest {
self.status == RequestStatus::Pending
}

pub fn get_error(&self) -> &Option<String> {
&self.error
pub fn get_error(&self) -> Option<&String> {
self.error.as_ref()
}

pub fn get_timestamp(&self) -> u64 {
Expand Down
4 changes: 4 additions & 0 deletions backend/lib/b3_permit_lib/src/request/btc/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,8 @@ impl RequestTrait for BtcTransfer {
fn title(&self) -> String {
format!("Send {} {}", self.amount, self.network)
}

fn message(&self) -> String {
format!("Send {} {}", self.amount, self.network)
}
}
4 changes: 4 additions & 0 deletions backend/lib/b3_permit_lib/src/request/evm/other.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,8 @@ impl RequestTrait for EvmDeployContract {
fn title(&self) -> String {
format!("Deploy contract on EVM chain {}", self.chain_id)
}

fn message(&self) -> String {
format!("Deploy contract on EVM chain {}", self.chain_id)
}
}
Loading

0 comments on commit 6d97610

Please sign in to comment.