Skip to content

Commit

Permalink
Merge branch 'master' into return_deposit_poc
Browse files Browse the repository at this point in the history
  • Loading branch information
sczembor authored Dec 4, 2023
2 parents 7f19990 + 5303227 commit 1e9ca13
Show file tree
Hide file tree
Showing 10 changed files with 146 additions and 11 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ The IAH Registry supports the following extra queries, which are not part of the

Production:

- **SBT registry**: `registry.i-am-human.near` @ registry/v1.6.0
- **SBT registry**: `registry.i-am-human.near` @ registry/v1.7.0
- **Fractal**: `fractal.i-am-human.near` @ oracle/v1.0.1
- verification pubkey base64: `"zqMwV9fTRoBOLXwt1mHxBAF3d0Rh9E9xwSAXR3/KL5E="`
- **Community SBTs**: `community.i-am-human.near` @ community-sbt/v4.3.0
Expand All @@ -66,7 +66,7 @@ Production:

Mainnet Testing:

- `registry-v1.gwg-testing.near` @ registry/v1.6.0
- `registry-v1.gwg-testing.near` @ registry/v1.7.0
IAH issuer: `(fractal.i-am-human.near, [1])`

Deprecated:
Expand All @@ -78,8 +78,8 @@ Deprecated:

- **SBT registry**:
Testnet registry is used to test the issuer behavior. For testing other integrations (eg polling, elections) use the testing-unstable version. Consult issuer contracts to validate which issuer is linked to which registry. We may consider adding migration to `registry-1` to make it compatible with the latest version.
- `registry-v2.i-am-human.testnet` @ registry/v1.6.0 (same as the prod version)
- `registry-unstable.i-am-human.testnet` @ registry/v1.6.0
- `registry-v2.i-am-human.testnet` @ registry/v1.7.0 (same as the prod version)
- `registry-unstable-v2.i-am-human.testnet` @ registry/v1.7.0
- **Demo SBT**: `sbt1.i-am-human.testnet` (the `demo_issuer` contract)
- **Fractal**: `fractal-v2.i-am-human.testnet` @ oracle/v1.0.1
registry: `registry-1.i-am-human.testnet`; Verification pubkey base64: `FGoAI6DXghOSK2ZaKVT/5lSP4X4JkoQQphv1FD4YRto=`, `claim_ttl`: 3600ms, FV class: 1
Expand All @@ -93,6 +93,7 @@ Deprecated:
- SBT Registry:
- `registry.i-am-human.testnet`
- `registry-1.i-am-human.testnet` @ release/v0.2
- `registry-unstable.i-am-human.testnet` @ registry/v1.6.0
- **Fractal**: `i-am-human-staging.testnet` @ oracle/v1.0.1
registry: `registry-1.i-am-human.testnet`; Verification pubkey base64: `FGoAI6DXghOSK2ZaKVT/5lSP4X4JkoQQphv1FD4YRto=`, `claim_ttl`: 3600ms, FV class: 1
- **Community-SBT**: `community-v1.i-am-human.testnet` @ community-sbt/v4.3.0
Expand Down
3 changes: 2 additions & 1 deletion contracts/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 contracts/human_checker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ near-sdk.workspace = true
serde_json.workspace = true

sbt = { path = "../sbt" }
registry = { path = "../registry" }

[dev-dependencies]
anyhow.workspace = true
Expand Down
11 changes: 11 additions & 0 deletions contracts/human_checker/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use near_sdk::json_types::Base64VecU8;
use near_sdk::serde::Deserialize;
use near_sdk::{ext_contract, AccountId, PromiseOrValue};

use registry::errors::IsHumanCallErr;

// imports needed for conditional derive (required for tests)
#[allow(unused_imports)]
use near_sdk::serde::Serialize;
Expand All @@ -15,4 +17,13 @@ pub trait ExtSbtRegistry {
function: String,
payload: String,
) -> PromiseOrValue<bool>;

fn is_human_call_lock(
&mut self,
ctr: AccountId,
function: String,
payload: String,
lock_duration: u64,
with_proof: bool,
) -> Result<Promise, IsHumanCallErr>;
}
51 changes: 50 additions & 1 deletion contracts/human_checker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ 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);
/// maximum time for proposal voting in milliseconds.
pub const VOTING_DURATION: u64 = 20_000;

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
Expand Down Expand Up @@ -106,16 +108,63 @@ impl Contract {
pub fn on_failure(&mut self, error: String) {
env::panic_str(&error)
}
/// Simulates a governance voting. Every valid human (as per IAH registry) can vote.
/// To avoid double voting by an account who is doing soul_transfer while a proposal is
/// active, we require that voing must be called through `iah_registry.is_human_call_lock`.
/// We check that the caller set enough `lock_duration` for soul transfers.
/// Arguments:
/// * `caller`: account ID making a vote (passed by `iah_registry.is_human_call`)
/// * `locked_until`: time in milliseconds, untile when the caller is locked for soul
/// transfers (reported by `iah_registry.is_human_call`).
/// * `iah_proof`: proof of humanity. It's not required and will be ignored.
/// * `payload`: the proposal ID and the vote (approve or reject).
#[payable]
pub fn vote(
&mut self,
caller: AccountId,
locked_until: u64,
#[allow(unused_variables)] iah_proof: Option<SBTs>,
payload: VotePayload,
) {
// for this simulation we imagine that every proposal ID is valid and it's finishing
// at "now" + VOTING_DURATION
require!(
env::predecessor_account_id() == self.registry,
"must be called by registry"
);
require!(
locked_until >= env::block_timestamp_ms() + VOTING_DURATION,
"account not locked for soul transfer for sufficient amount of time"
);
require!(payload.prop_id > 0, "invalid proposal id");
require!(
payload.vote == "approve" || payload.vote == "reject",
"invalid vote: must be either 'approve' or 'reject'"
);

env::log_str(&format!(
"VOTED: voter={}, proposal={}, vote={}",
caller, payload.prop_id, payload.vote,
));
}
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, NearSchema, Clone))]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, Clone))]
#[serde(crate = "near_sdk::serde")]
pub struct RegisterHumanPayload {
pub memo: String,
pub numbers: Vec<u32>,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, Clone))]
#[serde(crate = "near_sdk::serde")]
pub struct VotePayload {
pub prop_id: u32,
pub vote: String,
}

pub(crate) fn expected_vec_payload() -> Vec<u32> {
vec![2, 3, 5, 7, 11]
}
Expand Down
61 changes: 60 additions & 1 deletion contracts/human_checker/tests/workspaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ use near_workspaces::{network::Sandbox, result::ExecutionFinalResult, Account, C
use sbt::{SBTs, TokenMetadata};
use serde_json::json;

use human_checker::RegisterHumanPayload;
use human_checker::{RegisterHumanPayload, VotePayload, VOTING_DURATION};

const REGISTER_HUMAN_TOKEN: &str = "register_human_token";
const MSECOND : u64 = 1000;

struct Suite {
registry: Contract,
Expand All @@ -32,6 +33,23 @@ impl Suite {
Ok(res)
}

pub async fn is_human_call_lock(
&self,
caller: &Account,
lock_duration: u64,
payload: &VotePayload,
) -> anyhow::Result<ExecutionFinalResult> {
let res = caller
.call(self.registry.id(), "is_human_call_lock")
.args_json(json!({"ctr": self.human_checker.id(), "function": "vote", "payload": serde_json::to_string(payload).unwrap(), "lock_duration": lock_duration, "with_proof": false}))
.max_gas()
.transact()
.await?;
println!(">>> is_human_call_lock logs {:?}\n", res.logs());
Ok(res)
}


pub async fn query_sbts(&self, user: &Account) -> anyhow::Result<Option<SBTs>> {
// check the key does not exists in human checker
let r = self
Expand Down Expand Up @@ -174,6 +192,47 @@ async fn is_human_call() -> anyhow::Result<()> {
tokens = suite.query_sbts(&john).await?;
assert_eq!(tokens, None);


//
// Test Vote with lock duration
//

//
// test1: too short lock duration: should fail
let mut payload = VotePayload{prop_id: 10, vote: "approve".to_string()};
let r = suite.is_human_call_lock(&alice, VOTING_DURATION / 3 *2, &payload).await?;
assert!(r.is_failure());
let failure_str = format!("{:?}",r.failures());
assert!(failure_str.contains("sufficient amount of time"), "{}", failure_str);

//
// test2: second call, should not change
let r = suite.is_human_call_lock(&alice, VOTING_DURATION / 3*2, &payload).await?;
assert!(r.is_failure());
let failure_str = format!("{:?}",r.failures());
assert!(failure_str.contains("sufficient amount of time"), "{}", failure_str);

//
// test3: longer call should be accepted, but should fail on wrong payload (vote option)
payload.vote = "wrong-wrong".to_string();
let r = suite.is_human_call_lock(&alice, VOTING_DURATION +MSECOND, &payload).await?;
assert!(r.is_failure());
let failure_str = format!("{:?}",r.failures());
assert!(failure_str.contains("invalid vote: must be either"), "{}", failure_str);

//
// test4: should work with correct input
payload.vote = "approve".to_string();
let r = suite.is_human_call_lock(&alice, VOTING_DURATION +MSECOND, &payload).await?;
assert!(r.is_success());

//
// test5: should fail with not a human
let r = suite.is_human_call_lock(&john, VOTING_DURATION + MSECOND, &payload).await?;
assert!(r.is_failure());
let failure_str = format!("{:?}",r.failures());
assert!(failure_str.contains("is not a human"), "{}", failure_str);

Ok(())
}

Expand Down
10 changes: 8 additions & 2 deletions contracts/registry/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ Change log entries are to be added to the Unreleased section. Example entry:

### Features

### Breaking Changes

### Bug Fixes

## v1.7.0 (2023-11-02)

### Features

- Added `authorized_flaggers` query.
- Added `admin_add_authorized_flagger` method.
- added `is_human_call_lock` method: allows dapp to lock an account for soul transfers and calls a recipient contract when the predecessor has a proof of personhood.
Expand All @@ -30,8 +38,6 @@ Change log entries are to be added to the Unreleased section. Example entry:
- New contract field: `transfer_lock`.
- `sbt_soul_transfer` will fail if an account has an active transfer lock.

### Bug Fixes

## v1.6.0 (2023-10-08)

### Features
Expand Down
2 changes: 1 addition & 1 deletion contracts/registry/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "registry"
version = "1.6.0"
version = "1.7.0"
authors = ["Robert Zaremba 'https://zaremba.ch/'"]
edition = { workspace = true }
repository = { workspace = true }
Expand Down
9 changes: 8 additions & 1 deletion contracts/registry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,20 @@ This implementation requires an admin account (could be a DAO) to add an issuer

## SBT mint

The minting process is a procedure where we assign a new token to the provided receiver and keep track of it in the registry. The `sbt_mint` method must be called by a issuer that is opted-in. Additional:
The minting process is a procedure where we assign a new token to the provided receiver and keep track of it in the registry. The `sbt_mint` method must be called by a issuer that is opted-in. Additionally:

- each `TokenMetadata` provided must have a non zero `class`,
- enough `Near` must be attached to cover the registry storage cost must be provided.

The method will emit the [`Mint`](https://github.com/alpha-fi/i-am-human/blob/master/contracts/sbt/src/events.rs#L69) event when successful. There might be a case when the token vector provided is too long, and the gas is not enough to cover the minting process, then it will panic with `out of gas`.

### Issuers

SBT minting is done by an external entity, usually DAO (but can be any contract or account). In the current implementation, only whitelisted issuers are authorized to mint tokens until we will have more established governance and the protocol will get enough stability.
The diagram below outlines different entities involved in minting process. Issuers always mints tokens under his own namespace. Moreover, when minting, an issuer must specify non zero `class` for every token (this is set in `TokenMetadata`). A recipient can have at most one SBT of the same class.

![Issuers and minting](./issuers.jpg)

## Additional Queries

The IAH Registry supports the following extra queries, which are not part of the NEP-393 standard. See the function docs for more complete documentation.
Expand Down
Binary file added contracts/registry/issuers.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 1e9ca13

Please sign in to comment.