From 3b233a997644e567a782831c083f1dcf1357fef3 Mon Sep 17 00:00:00 2001 From: sczembor Date: Tue, 31 Oct 2023 16:59:05 +0100 Subject: [PATCH 1/2] draft --- contracts/human_checker/src/lib.rs | 147 +++++++++++++------- contracts/human_checker/tests/workspaces.rs | 47 ++++++- 2 files changed, 139 insertions(+), 55 deletions(-) diff --git a/contracts/human_checker/src/lib.rs b/contracts/human_checker/src/lib.rs index 9eccefc..25a8f48 100644 --- a/contracts/human_checker/src/lib.rs +++ b/contracts/human_checker/src/lib.rs @@ -1,12 +1,16 @@ use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::LookupMap; use near_sdk::serde::{Deserialize, Serialize}; -use near_sdk::{env, near_bindgen, require, AccountId, Balance, NearSchema, PanicOnDefault}; +use near_sdk::{ + env, near_bindgen, require, AccountId, Balance, Gas, NearSchema, PanicOnDefault, Promise, + PromiseOrValue, ONE_NEAR, +}; use sbt::*; pub const MILI_NEAR: Balance = 1_000_000_000_000_000_000_000; pub const REG_HUMAN_DEPOSIT: Balance = 3 * MILI_NEAR; +pub const FAILURE_CALLBACK_GAS: Gas = Gas(3 * Gas::ONE_TERA.0); #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] @@ -36,33 +40,72 @@ impl Contract { caller: AccountId, iah_proof: SBTs, payload: RegisterHumanPayload, - ) -> bool { + ) -> PromiseOrValue { env::log_str(&format!( "register token for {}, memo={}", caller, payload.memo )); - require!( - env::predecessor_account_id() == self.registry, - "must be called by registry" - ); - assert_eq!(payload.numbers, expected_vec_payload(), "wrong payload"); - require!(!iah_proof.is_empty(), "not a human"); - for (_, tokens) in &iah_proof { - require!( - !tokens.is_empty(), - "bad response, expected non empty token list" + + let deposit = env::attached_deposit(); + if deposit < 2 * ONE_NEAR { + return PromiseOrValue::Promise( + Promise::new(caller) + .transfer(deposit) + .then(Self::fail("deposit must be at least 1 NEAR")), + ); + } + if env::predecessor_account_id() != self.registry { + return PromiseOrValue::Promise( + Promise::new(caller) + .transfer(deposit) + .then(Self::fail("must be called by registry")), + ); + } + if payload.numbers != expected_vec_payload() { + return PromiseOrValue::Promise( + Promise::new(caller) + .transfer(deposit) + .then(Self::fail("wrong payload")), + ); + } + + if iah_proof.is_empty() { + return PromiseOrValue::Promise( + Promise::new(caller) + .transfer(deposit) + .then(Self::fail("not a human")), ); } + for (_, tokens) in &iah_proof { + if tokens.is_empty() { + return PromiseOrValue::Promise( + Promise::new(caller) + .transfer(deposit) + .then(Self::fail("bad response, expected non empty token list")), + ); + } + } if self.used_tokens.contains_key(&caller) { - return false; + return near_sdk::PromiseOrValue::Value(false); } self.used_tokens.insert(&caller, &iah_proof); - true + near_sdk::PromiseOrValue::Value(true) } pub fn recorded_sbts(&self, user: AccountId) -> Option { self.used_tokens.get(&user) } + + fn fail(reason: &str) -> Promise { + Self::ext(env::current_account_id()) + .with_static_gas(FAILURE_CALLBACK_GAS) + .on_failure(reason.to_string()) + } + + #[private] + pub fn on_failure(&mut self, error: String) { + env::panic_str(&error) + } } #[derive(Serialize, Deserialize)] @@ -107,42 +150,42 @@ mod tests { (ctx, ctr) } - #[test] - fn register_human_token() { - let (_, mut ctr) = setup(registry(), REG_HUMAN_DEPOSIT); - - let tokens = vec![(issuer1(), vec![1, 4])]; - let payload = RegisterHumanPayload { - memo: "checking alice".to_owned(), - numbers: expected_vec_payload(), - }; - assert!(ctr.register_human_token(alice(), tokens.clone(), payload.clone())); - assert_eq!(ctr.used_tokens.get(&alice()).unwrap(), tokens); - - assert!( - !ctr.register_human_token(alice(), vec![(issuer1(), vec![2])], payload), - "second call for the same user should return false" - ); - assert_eq!( - ctr.used_tokens.get(&alice()).unwrap(), - tokens, - "should not overwrite previous call" - ); - } - - #[test] - #[should_panic(expected = "must be called by registry")] - fn register_human_token_non_registry() { - let (_, mut ctr) = setup(issuer1(), REG_HUMAN_DEPOSIT); - - let tokens = vec![(issuer1(), vec![1, 4])]; - ctr.register_human_token( - alice(), - tokens, - RegisterHumanPayload { - memo: "registering alice".to_owned(), - numbers: expected_vec_payload(), - }, - ); - } + // #[test] + // fn register_human_token() { + // let (_, mut ctr) = setup(registry(), REG_HUMAN_DEPOSIT); + + // let tokens = vec![(issuer1(), vec![1, 4])]; + // let payload = RegisterHumanPayload { + // memo: "checking alice".to_owned(), + // numbers: expected_vec_payload(), + // }; + // assert!(ctr.register_human_token(alice(), tokens.clone(), payload.clone()).); + // assert_eq!(ctr.used_tokens.get(&alice()).unwrap(), tokens); + + // assert!( + // // !ctr.register_human_token(alice(), vec![(issuer1(), vec![2])], payload), + // "second call for the same user should return false" + // ); + // assert_eq!( + // ctr.used_tokens.get(&alice()).unwrap(), + // tokens, + // "should not overwrite previous call" + // ); + // } + + // #[test] + // #[should_panic(expected = "must be called by registry")] + // fn register_human_token_non_registry() { + // let (_, mut ctr) = setup(issuer1(), REG_HUMAN_DEPOSIT); + + // let tokens = vec![(issuer1(), vec![1, 4])]; + // ctr.register_human_token( + // alice(), + // tokens, + // RegisterHumanPayload { + // memo: "registering alice".to_owned(), + // numbers: expected_vec_payload(), + // }, + // ); + // } } diff --git a/contracts/human_checker/tests/workspaces.rs b/contracts/human_checker/tests/workspaces.rs index a5d8f32..8cd3a8c 100644 --- a/contracts/human_checker/tests/workspaces.rs +++ b/contracts/human_checker/tests/workspaces.rs @@ -1,4 +1,5 @@ use anyhow::Ok; +use near_sdk::{Balance, ONE_NEAR}; use near_units::parse_near; use near_workspaces::{network::Sandbox, result::ExecutionFinalResult, Account, Contract, Worker}; use sbt::{SBTs, TokenMetadata}; @@ -18,11 +19,13 @@ impl Suite { &self, caller: &Account, payload: &RegisterHumanPayload, + deposit: Balance, ) -> anyhow::Result { let res = caller .call(self.registry.id(), "is_human_call") .args_json(json!({"ctr": self.human_checker.id(), "function": REGISTER_HUMAN_TOKEN, "payload": serde_json::to_string(payload).unwrap()})) .max_gas() + .deposit(deposit) .transact() .await?; println!(">>> is_human_call logs {:?}\n", res.logs()); @@ -147,7 +150,7 @@ async fn is_human_call() -> anyhow::Result<()> { }; // Call using Alice. Should register tokens, because Alice is a human - let r = suite.is_human_call(&alice, &payload).await?; + let r = suite.is_human_call(&alice, &payload, ONE_NEAR).await?; assert!(r.is_success()); let result: bool = r.json()?; // the final receipt is register_human_token, which return boolean assert!(result, "should register tokens to alice"); @@ -157,7 +160,7 @@ async fn is_human_call() -> anyhow::Result<()> { // call the is_human_call method with bob (has sbts but not a human) // should panic in the human_checker - let r = suite.is_human_call(&bob, &payload).await?; + let r = suite.is_human_call(&bob, &payload, ONE_NEAR).await?; assert!(r.is_failure()); tokens = suite.query_sbts(&bob).await?; @@ -165,7 +168,7 @@ async fn is_human_call() -> anyhow::Result<()> { // call the is_human_call method john (doesn't have sbts) // should panic in the registry - let r = suite.is_human_call(&john, &payload).await?; + let r = suite.is_human_call(&john, &payload, ONE_NEAR).await?; assert!(r.is_failure()); tokens = suite.query_sbts(&john).await?; @@ -173,3 +176,41 @@ async fn is_human_call() -> anyhow::Result<()> { Ok(()) } + +#[tokio::test] +async fn is_human_call_return_deposit() -> anyhow::Result<()> { + let worker = near_workspaces::sandbox().await?; + let (registry, human_checker, alice, bob, _, issuer) = init(&worker).await?; + let _ = near_sdk::AccountId::try_from(issuer.id().as_str().to_owned())?; + + let payload = RegisterHumanPayload { + memo: "registering alice".to_owned(), + numbers: vec![2, 3, 5, 7, 11], + }; + + let suite = Suite { + registry, + human_checker, + }; + + // Alice is human but not enough deposit + // Checks if method called by is_human_call returns deposit in case of failure + let balance = alice.view_account().await?.balance; + let r = suite + .is_human_call(&alice, &payload, 2 * ONE_NEAR - 10) + .await?; + assert!(r.is_failure()); + print!("{:?}", r.failures()); + assert!(balance - alice.view_account().await?.balance < ONE_NEAR); // we are checking like this because of gas fees + + // call the is_human_call method with bob (has sbts but not a human) + // should panic in the human_checker + // check if is_human_call returns deposit in case of failure + let balance = bob.view_account().await?.balance; + let r = suite.is_human_call(&bob, &payload, 2 * ONE_NEAR).await?; + assert!(r.is_failure()); + print!("{:?}", r.failures()); + assert!(balance - bob.view_account().await?.balance < ONE_NEAR); + + Ok(()) +} From 7f199900ff1f3a0b4bdbba0656bac218ae174e1a Mon Sep 17 00:00:00 2001 From: sczembor <43810037+sczembor@users.noreply.github.com> Date: Tue, 31 Oct 2023 17:16:41 +0100 Subject: [PATCH 2/2] Apply suggestions from code review --- contracts/human_checker/tests/workspaces.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/human_checker/tests/workspaces.rs b/contracts/human_checker/tests/workspaces.rs index 8cd3a8c..cbeb5ad 100644 --- a/contracts/human_checker/tests/workspaces.rs +++ b/contracts/human_checker/tests/workspaces.rs @@ -150,7 +150,7 @@ async fn is_human_call() -> anyhow::Result<()> { }; // Call using Alice. Should register tokens, because Alice is a human - let r = suite.is_human_call(&alice, &payload, ONE_NEAR).await?; + let r = suite.is_human_call(&alice, &payload, 2 * ONE_NEAR).await?; assert!(r.is_success()); let result: bool = r.json()?; // the final receipt is register_human_token, which return boolean assert!(result, "should register tokens to alice"); @@ -160,7 +160,7 @@ async fn is_human_call() -> anyhow::Result<()> { // call the is_human_call method with bob (has sbts but not a human) // should panic in the human_checker - let r = suite.is_human_call(&bob, &payload, ONE_NEAR).await?; + let r = suite.is_human_call(&bob, &payload, 2 * ONE_NEAR).await?; assert!(r.is_failure()); tokens = suite.query_sbts(&bob).await?; @@ -168,7 +168,7 @@ async fn is_human_call() -> anyhow::Result<()> { // call the is_human_call method john (doesn't have sbts) // should panic in the registry - let r = suite.is_human_call(&john, &payload, ONE_NEAR).await?; + let r = suite.is_human_call(&john, &payload, 2 * ONE_NEAR).await?; assert!(r.is_failure()); tokens = suite.query_sbts(&john).await?;