Skip to content

Commit

Permalink
fix: use files from master
Browse files Browse the repository at this point in the history
  • Loading branch information
frdomovic committed Dec 4, 2024
1 parent f862a88 commit dbd608f
Show file tree
Hide file tree
Showing 28 changed files with 667 additions and 388 deletions.
43 changes: 43 additions & 0 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions contracts/icp/context-config/.env
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# DFX CANISTER ENVIRONMENT VARIABLES
DFX_VERSION='0.24.2'
DFX_NETWORK='local'
CANISTER_ID_CONTEXT_CONTRACT='bkyz2-fmaaa-aaaaa-qaaaq-cai'
CANISTER_ID='bkyz2-fmaaa-aaaaa-qaaaq-cai'
CANISTER_ID_CONTEXT_CONTRACT='bw4dl-smaaa-aaaaa-qaacq-cai'
CANISTER_ID='bw4dl-smaaa-aaaaa-qaacq-cai'
CANISTER_CANDID_PATH='/Users/alen/www/calimero/core/contracts/icp/context-config/context_contract.did'
# END DFX CANISTER ENVIRONMENT VARIABLES
2 changes: 1 addition & 1 deletion contracts/icp/context-config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ thiserror.workspace = true

[dev-dependencies]
pocket-ic = "6.0.0"
rand.workspace = true
rand = "0.8"
ed25519-dalek = "2.0"
4 changes: 2 additions & 2 deletions contracts/icp/context-config/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ set -e

cd "$(dirname $0)"

TARGET="${CARGO_TARGET_DIR:-./target}"
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/context_contract.wasm ./res/context_contract.wasm
cp $TARGET/wasm32-unknown-unknown/app-release/context_contract.wasm ./res/

if command -v wasm-opt > /dev/null; then
wasm-opt -Oz ./res/context_contract.wasm -o ./res/context_contract.wasm
Expand Down
2 changes: 1 addition & 1 deletion contracts/icp/context-config/context_contract.did
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ service : () -> {
privileges : (blob, vec blob) -> (
vec record { blob; vec ICCapability },
) query;
proxy_contract : (blob) -> (text) query;
proxy_contract : (blob) -> (principal) query;
set_proxy_code : (blob) -> (Result);
}
Empty file modified contracts/icp/context-config/deploy_devnet.sh
100755 → 100644
Empty file.
3 changes: 3 additions & 0 deletions contracts/icp/context-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ pub struct Context {
pub proxy: Guard<Principal>,
}

#[derive(CandidType, Deserialize, Clone, Debug)]
pub struct ContextConfigs {
pub contexts: HashMap<ICContextId, Context>,
pub proxy_code: Option<Vec<u8>>,
pub owner: Principal,
pub ledger_id: Principal,
}

impl Default for ContextConfigs {
Expand All @@ -34,6 +36,7 @@ impl Default for ContextConfigs {
contexts: HashMap::new(),
proxy_code: None,
owner: ic_cdk::api::caller(),
ledger_id: Principal::anonymous(),
}
}
}
Expand Down
8 changes: 5 additions & 3 deletions contracts/icp/context-config/src/mutate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub async fn mutate(signed_request: ICPSigned<Request>) -> Result<(), String> {
.map_err(|e| format!("Failed to verify signature: {}", e))?;

// Check request timestamp
let current_time_ms = ic_cdk::api::time() / 1_000_000; // Convert nanoseconds to milliseconds
if current_time_ms.saturating_sub(request.timestamp_ms) > 5_000 {
let current_time = ic_cdk::api::time();
if current_time.saturating_sub(request.timestamp_ms) > 1000 * 5 {
// 5 seconds threshold
return Err("request expired".to_string());
}
Expand Down Expand Up @@ -99,6 +99,8 @@ async fn deploy_proxy_contract(context_id: &ICContextId) -> Result<Principal, St
.with(|configs| configs.borrow().proxy_code.clone())
.ok_or("proxy code not set")?;

// Get the ledger ID
let ledger_id = CONTEXT_CONFIGS.with(|configs| configs.borrow().ledger_id.clone());
// Create canister with cycles
let create_args = CreateCanisterArgument {
settings: Some(CanisterSettings {
Expand All @@ -119,7 +121,7 @@ async fn deploy_proxy_contract(context_id: &ICContextId) -> Result<Principal, St
let canister_id = canister_record.canister_id;

// Encode init args matching the proxy's init(context_id: ICContextId, ledger_id: Principal)
let init_args = candid::encode_args((context_id.clone(), Principal::anonymous()))
let init_args = candid::encode_args((context_id.clone(), ledger_id))
.map_err(|e| format!("Failed to encode init args: {}", e))?;

let install_args = InstallCodeArgument {
Expand Down
22 changes: 10 additions & 12 deletions contracts/icp/context-config/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,16 @@ fn application_revision(context_id: ICContextId) -> u64 {
}

#[query]
fn proxy_contract(context_id: ICContextId) -> String {
CONTEXT_CONFIGS
.with(|configs: &std::cell::RefCell<crate::ContextConfigs>| {
let configs = configs.borrow();
let context = configs
.contexts
.get(&context_id)
.expect("context does not exist");

(*context.proxy).clone()
})
.to_string()
fn proxy_contract(context_id: ICContextId) -> Principal {
CONTEXT_CONFIGS.with(|configs| {
let configs = configs.borrow();
let context = configs
.contexts
.get(&context_id)
.expect("context does not exist");

(*context.proxy).clone()
})
}

#[query]
Expand Down
46 changes: 45 additions & 1 deletion contracts/icp/context-config/src/sys.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,50 @@
use candid::{CandidType, Deserialize, Principal};
use ic_cdk;

use crate::CONTEXT_CONFIGS;

#[derive(CandidType, Deserialize)]
struct StableStorage {
configs: crate::ContextConfigs,
}

#[ic_cdk::pre_upgrade]
fn pre_upgrade() {
// Verify caller is the owner
CONTEXT_CONFIGS.with(|configs| {
let configs = configs.borrow();
if ic_cdk::api::caller() != configs.owner {
ic_cdk::trap("unauthorized: only owner can upgrade context contract");
}
});

// Store the contract state
let state = CONTEXT_CONFIGS.with(|configs| StableStorage {
configs: configs.borrow().clone(),
});

// Write state to stable storage
match ic_cdk::storage::stable_save((state,)) {
Ok(_) => (),
Err(err) => ic_cdk::trap(&format!("Failed to save stable storage: {}", err)),
}
}

#[ic_cdk::post_upgrade]
fn post_upgrade() {
// Restore the contract state
match ic_cdk::storage::stable_restore::<(StableStorage,)>() {
Ok((state,)) => {
CONTEXT_CONFIGS.with(|configs| {
*configs.borrow_mut() = state.configs;
});
}
Err(err) => ic_cdk::trap(&format!("Failed to restore stable storage: {}", err)),
}
}

#[ic_cdk::update]
pub fn set_proxy_code(proxy_code: Vec<u8>) -> Result<(), String> {
pub fn set_proxy_code(proxy_code: Vec<u8>, ledger_id: Principal) -> Result<(), String> {
CONTEXT_CONFIGS.with(|configs| {
let mut configs = configs.borrow_mut();

Expand All @@ -10,6 +53,7 @@ pub fn set_proxy_code(proxy_code: Vec<u8>) -> Result<(), String> {
return Err("Unauthorized: only owner can set proxy code".to_string());
}

configs.ledger_id = ledger_id;
configs.proxy_code = Some(proxy_code);
Ok(())
})
Expand Down
9 changes: 4 additions & 5 deletions contracts/icp/context-config/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@ fn setup() -> (PocketIc, Principal) {
);

// Set the proxy code
let proxy_code = std::fs::read(
"../proxy-contract/target/wasm32-unknown-unknown/release/proxy_contract.wasm",
)
.expect("failed to read proxy wasm");
let proxy_code = std::fs::read("../proxy-contract/res/proxy_contract.wasm")
.expect("failed to read proxy wasm");
let ledger_id = Principal::from_text("ryjl3-tyaaa-aaaaa-aaaba-cai").unwrap();
pic.update_call(
canister,
Principal::anonymous(),
"set_proxy_code",
candid::encode_one(proxy_code).unwrap(),
candid::encode_args((proxy_code, ledger_id)).unwrap(),
)
.expect("Failed to set proxy code");

Expand Down
3 changes: 2 additions & 1 deletion contracts/icp/proxy-contract/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
bs58.workspace = true
calimero-context-config = { path = "../../../crates/context/config" }
candid = "0.10"
candid = { version = "0.10", features = ["value"] }
ed25519-dalek.workspace = true
hex.workspace = true
ic-cdk = "0.16"
ic-cdk-macros = "0.16"
ic-ledger-types = "0.14.0"
serde = { version = "1.0", features = ["derive"] }
thiserror.workspace = true

Expand Down
23 changes: 11 additions & 12 deletions contracts/icp/proxy-contract/build.sh
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
#!/bin/bash

# Exit on error
#!/bin/sh
set -e

# Ensure we have the wasm32 target
cd "$(dirname $0)"

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

rustup target add wasm32-unknown-unknown

# Build the contract
cargo build --target wasm32-unknown-unknown --release
cargo build --target wasm32-unknown-unknown --profile app-release

# Generate the candid interface
candid-extractor target/wasm32-unknown-unknown/release/proxy_contract.wasm > proxy_contract.did
mkdir -p res

# Stop the replica
dfx stop
cp $TARGET/wasm32-unknown-unknown/app-release/proxy_contract.wasm ./res/

# Start the replica
dfx start --background
if command -v wasm-opt > /dev/null; then
wasm-opt -Oz ./res/proxy_contract.wasm -o ./res/proxy_contract.wasm
fi
16 changes: 16 additions & 0 deletions contracts/icp/proxy-contract/build_contracts.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/bin/sh
set -e

cd "$(dirname $0)"

echo "Building proxy contract..."
./build.sh

echo "Building mock ledger contract..."
./mock/ledger/build.sh

echo "Building mock external contract..."
./mock/external/build.sh

echo "Building context-config contract..."
../context-config/build.sh
12 changes: 12 additions & 0 deletions contracts/icp/proxy-contract/dfx.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@
"candid": "proxy_contract.did",
"package": "proxy_contract",
"type": "rust"
},
"mock_ledger": {
"type": "rust",
"package": "mock_ledger",
"candid": "mock/ledger/ledger.did",
"path": "mock/ledger"
},
"mock_external": {
"type": "rust",
"package": "mock_external",
"candid": "mock/external/external.did",
"path": "mock/external"
}
},
"defaults": {
Expand Down
18 changes: 18 additions & 0 deletions contracts/icp/proxy-contract/mock/external/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/sh
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/mock_external.wasm ./res/

if command -v wasm-opt > /dev/null; then
wasm-opt -Oz ./res/mock_external.wasm -o ./res/mock_external.wasm
fi
9 changes: 5 additions & 4 deletions contracts/icp/proxy-contract/mock/external/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ thread_local! {
}

#[ic_cdk::update]
fn test_method(args: Vec<u8>) {
fn test_method(args: Vec<u8>) -> Vec<u8> {
CALLS.with(|calls| {
calls.borrow_mut().push(args);
});
calls.borrow_mut().push(args.clone());
args // Return the same args back
})
}

#[ic_cdk::query]
fn get_calls() -> Vec<Vec<u8>> {
CALLS.with(|calls| calls.borrow().clone())
}

ic_cdk::export_candid!();
ic_cdk::export_candid!();
Loading

0 comments on commit dbd608f

Please sign in to comment.