Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration test easy poll #89

Merged
merged 11 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions contracts/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 contracts/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ add-deps:
rustup target add wasm32-unknown-unknown

build: res
@RUSTFLAGS='-C link-arg=-s' cargo build --all --target wasm32-unknown-unknown --release
@RUSTFLAGS='-C link-arg=-s' cargo build --workspace --exclude test-util --target wasm32-unknown-unknown --release
@cp target/wasm32-unknown-unknown/release/*.wasm res/

test: build
Expand Down
2 changes: 1 addition & 1 deletion contracts/Makefile-common.mk
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ build-abi: res


build-all: res
@RUSTFLAGS='-C link-arg=-s' cargo build --all --target wasm32-unknown-unknown --release
@RUSTFLAGS='-C link-arg=-s' cargo build --workspace --exclude test-util --target wasm32-unknown-unknown --release
@cp ../target/wasm32-unknown-unknown/release/*.wasm ../res/
@cargo near abi
@cp ../target/near/*/*_abi.json ../res
Expand Down
1 change: 1 addition & 0 deletions contracts/easy-poll/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ workspaces.workspace = true
near-primitives.workspace = true
near-units.workspace = true
tracing.workspace = true
test-util = { path = "../test-util" }
141 changes: 141 additions & 0 deletions contracts/easy-poll/tests/workspaces.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
use anyhow::Ok;
use easy_poll::{PollResult, Results, Status};
use near_sdk::serde_json::json;
use near_units::parse_near;
use sbt::TokenMetadata;
use test_util::{build_contract, get_block_timestamp, registry_mint_iah_tokens};
use workspaces::{network::Sandbox, Account, AccountId, Contract, Worker};

const IAH_CLASS: u64 = 1;

async fn respond(
easy_poll_contract: &AccountId,
responder: &Account,
poll_id: u64,
) -> anyhow::Result<()> {
let res = responder
.call(easy_poll_contract, "respond")
.args_json(json!({"poll_id": poll_id, "answers": [{"YesNo": true}]}))
.deposit(parse_near!("1 N"))
.max_gas()
.transact()
.await?;
assert!(res.is_success(), "{:?}", res.receipt_failures());
Ok(())
}

async fn init(worker: &Worker<Sandbox>) -> anyhow::Result<(Contract, Account, Account)> {
let authority_acc = worker.dev_create_account().await?;
let flagger = worker.dev_create_account().await?;
let iah_issuer = worker.dev_create_account().await?;
let alice_acc = worker.dev_create_account().await?;
let bob_acc = worker.dev_create_account().await?;
// Setup registry contract
let registry_contract = build_contract(
&worker,
"./../registry",
"new",
json!({"authority": authority_acc.id(), "authorized_flaggers": vec![flagger.id()], "iah_issuer": iah_issuer.id(), "iah_classes": [1]}),
).await?;

// Setup easy-poll contract
let easy_poll_contract = build_contract(
&worker,
"./",
"new",
json!({"sbt_registry": registry_contract.id()}),
)
.await?;
sczembor marked this conversation as resolved.
Show resolved Hide resolved

// populate registry with mocked data
registry_mint_iah_tokens(
registry_contract.id(),
&iah_issuer,
IAH_CLASS,
vec![alice_acc.id()],
)
.await?;

Ok((easy_poll_contract, alice_acc, bob_acc))
sczembor marked this conversation as resolved.
Show resolved Hide resolved
}

#[tokio::test]
async fn flow1() -> anyhow::Result<()> {
amityadav0 marked this conversation as resolved.
Show resolved Hide resolved
// 1. create non-human gated poll
// 2. create human gated poll
// 3. vote for both polls with a human verified account
// 4. vote for both polls with a non-human account
// 5. check the responds were recorded correctly

// import the registry contract from mainnet with data
let worker = workspaces::sandbox().await?;
let (easy_poll_contract, alice, bob) = init(&worker).await?;

let now_ms = get_block_timestamp(&worker).await? / 1_000_000;
// create a poll
let poll_id_non_human_gated: u64 = bob.call(easy_poll_contract.id(), "create_poll")
.args_json(json!({"iah_only": false, "questions": [{"question_type": {"YesNo": false}, "required": true,
"title": "non-human gated"}], "starts_at": now_ms + 20000, "ends_at": now_ms + 300000,
"title": "Testing Poll 1", "tags": ["test"], "description": "poll desc", "link": "test.io"}))
.max_gas()
.transact()
.await?
.json()?;

// create a poll
let poll_id_human_gated: u64 = bob.call(easy_poll_contract.id(), "create_poll")
.args_json(json!({"iah_only": true, "questions": [{"question_type": {"YesNo": false}, "required": true,
"title": "human gated"}], "starts_at": now_ms + 5000, "ends_at": now_ms + 86400000,
"title": "Testing Poll 1", "tags": ["test"], "description": "poll desc", "link": "test.io"}))
.max_gas()
.transact()
.await?
.json()?;

// fast forward
worker.fast_forward(100).await?;

respond(easy_poll_contract.id(), &bob, poll_id_non_human_gated).await?;
respond(easy_poll_contract.id(), &alice, poll_id_non_human_gated).await?;

// This vote should not be registered since the poll is human gated and bob is not human
respond(easy_poll_contract.id(), &bob, poll_id_human_gated).await?;
respond(easy_poll_contract.id(), &alice, poll_id_human_gated).await?;

// assert the results are correct
let res: Option<Results> = bob
.call(easy_poll_contract.id(), "results")
.args_json(json!({ "poll_id": poll_id_non_human_gated }))
.max_gas()
.transact()
.await?
.json()?;

assert_eq!(
res.unwrap(),
Results {
status: Status::NotStarted,
participants_num: 2,
results: vec![PollResult::YesNo((2, 0))]
}
);

let res: Option<Results> = bob
.call(easy_poll_contract.id(), "results")
.args_json(json!({ "poll_id": poll_id_human_gated }))
.max_gas()
.transact()
.await?
.json()?;

assert_eq!(
res.unwrap(),
Results {
status: Status::NotStarted,
participants_num: 1,
results: vec![PollResult::YesNo((1, 0))]
}
);

Ok(())
}
1 change: 1 addition & 0 deletions contracts/kudos/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ near-sandbox-utils.workspace = true
near-units.workspace = true
tokio.workspace = true
anyhow.workspace = true
test-util = { path = "../test-util" }
3 changes: 1 addition & 2 deletions contracts/kudos/tests/test_kudos.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
mod types;
mod utils;
mod workspaces;

use crate::types::*;
use crate::utils::*;
use crate::workspaces::{build_contract, gen_user_account, get_block_timestamp, transfer_near};
use test_util::{build_contract, gen_user_account, get_block_timestamp, transfer_near};
use kudos_contract::WrappedCid;
use kudos_contract::{utils::*, CommentId};
use kudos_contract::{Commentary, PROOF_OF_KUDOS_SBT_CLASS_ID};
Expand Down
3 changes: 1 addition & 2 deletions contracts/kudos/tests/test_required_deposit.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
mod types;
mod utils;
mod workspaces;

use crate::utils::*;
use crate::workspaces::{build_contract, gen_user_account, get_block_timestamp, transfer_near};
use test_util::{build_contract, gen_user_account, get_block_timestamp, transfer_near};
use kudos_contract::{utils::*, WrappedCid};
use kudos_contract::{GIVE_KUDOS_COST, LEAVE_COMMENT_COST, UPVOTE_KUDOS_COST};
use near_sdk::serde_json::json;
Expand Down
3 changes: 1 addition & 2 deletions contracts/kudos/tests/test_social_db.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
mod types;
mod utils;
mod workspaces;

use crate::utils::*;
use crate::workspaces::{build_contract, gen_user_account, transfer_near};
use test_util::{build_contract, gen_user_account, transfer_near};
use kudos_contract::utils::*;
use kudos_contract::SOCIAL_DB_GRANT_WRITE_PERMISSION_COST;
use near_contract_standards::storage_management::{StorageBalance, StorageBalanceBounds};
Expand Down
19 changes: 19 additions & 0 deletions contracts/test-util/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "test-util"
version = "1.3.0"
sczembor marked this conversation as resolved.
Show resolved Hide resolved
authors = ["NDC Devs"]
edition = { workspace = true }
repository = { workspace = true }

[dependencies]
uint.workspace = true
near-sdk.workspace = true
sczembor marked this conversation as resolved.
Show resolved Hide resolved
serde_json.workspace = true
near-contract-standards.workspace = true
sczembor marked this conversation as resolved.
Show resolved Hide resolved
workspaces.workspace = true
anyhow.workspace = true
near-units.workspace = true

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

[dev-dependencies]
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
use anyhow::Ok;
use near_units::parse_near;
use sbt::TokenMetadata;
use serde_json::json;
use std::str::FromStr;
use workspaces::network::{NetworkClient, NetworkInfo, Sandbox};
use workspaces::result::ExecutionSuccess;
use workspaces::AccountId;
use workspaces::{
types::{Balance, KeyType, SecretKey},
Account, Contract, DevNetwork, Worker,
Expand Down Expand Up @@ -99,3 +104,54 @@ where
{
Ok(worker.view_block().await?.timestamp())
}

/// Helper function to issue tokens to the users for testing purposes
pub async fn registry_mint_iah_tokens(
registry: &AccountId,
issuer: &Account,
class_id: u64,
accounts: Vec<&AccountId>,
) -> anyhow::Result<()> {
// populate registry with mocked data
let token_metadata = vec![TokenMetadata {
class: class_id,
issued_at: Some(0),
expires_at: None,
reference: None,
reference_hash: None,
}];
let mut iah_token_spec = Vec::new();

for a in accounts {
iah_token_spec.push((a, token_metadata.clone()));
}

let res = issuer
.call(registry, "sbt_mint")
.args_json(json!({ "token_spec": iah_token_spec }))
.deposit(parse_near!("5 N"))
.max_gas()
.transact()
.await?;
assert!(res.is_success(), "{:?}", res.receipt_failures());

Ok(())
}

/// Helper function to add issuers to the registry
pub async fn registry_addt_issuer(
sczembor marked this conversation as resolved.
Show resolved Hide resolved
registry: &AccountId,
authority: &Account,
issuers: Vec<&AccountId>,
) -> anyhow::Result<()> {
for i in issuers {
let res = authority
.call(registry, "admin_add_sbt_issuer")
.args_json(json!({ "issuer": i }))
.max_gas()
.transact()
.await?;
assert!(res.is_success());
}
Ok(())
}
Loading