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

Initialize testing for the project #75

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
28 changes: 28 additions & 0 deletions .github/workflows/lints.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Rust testing

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
clippy:
runs-on: ubuntu-latest
strategy:
matrix:
component: [near, omni-relayer]
steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Rust
uses: actions-rs/toolchain@v1
with:
toolchain: 1.79.0
components: clippy

- name: Run Clippy
run: |
make rust-lint-${{ matrix.component }}

11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.PHONY: rust-lint rust-lint-near rust-lint-omni-relayer

OPTIONS = -D warnings -D clippy::pedantic -A clippy::missing_errors_doc -A clippy::must_use_candidate -A clippy::module_name_repetitions

rust-lint: rust-lint-near rust-lint-relayer

rust-lint-near:
cargo clippy --manifest-path ./near/Cargo.toml -- $(OPTIONS)

rust-lint-omni-relayer:
cargo clippy --manifest-path ./omni-relayer/Cargo.toml -- $(OPTIONS)
13 changes: 8 additions & 5 deletions near/mock/mock-prover/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,23 @@ impl Default for OmniProver {

#[near]
impl OmniProver {
pub fn add_prover(&mut self, prover_id: ProverId, account_id: AccountId) {
self.provers.insert(&prover_id, &account_id);
pub fn add_prover(&mut self, prover_id: &ProverId, account_id: &AccountId) {
self.provers.insert(prover_id, account_id);
}

pub fn remove_prover(&mut self, prover_id: ProverId) {
self.provers.remove(&prover_id);
pub fn remove_prover(&mut self, prover_id: &ProverId) {
self.provers.remove(prover_id);
}

pub fn get_provers(&self) -> Vec<(ProverId, AccountId)> {
self.provers.iter().collect::<Vec<_>>()
}

/// # Panics
///
/// This function will panic if the prover args are not valid.
#[result_serializer(borsh)]
pub fn verify_proof(&self, #[serializer(borsh)] args: VerifyProofArgs) -> ProverResult {
pub fn verify_proof(&self, #[serializer(borsh)] args: &VerifyProofArgs) -> ProverResult {
ProverResult::try_from_slice(&args.prover_args).unwrap()
}
}
16 changes: 8 additions & 8 deletions near/mock/mock-token/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ impl Contract {
/// Initializes the contract with the given total supply owned by the given `owner_id` with
/// default metadata (for example purposes only).
#[init]
pub fn new_default_meta(owner_id: AccountId, total_supply: U128) -> Self {
pub fn new_default_meta(owner_id: &AccountId, total_supply: U128) -> Self {
Self::new(
owner_id,
total_supply,
FungibleTokenMetadata {
&FungibleTokenMetadata {
spec: FT_METADATA_SPEC.to_string(),
name: "Example NEAR fungible token".to_string(),
symbol: "EXAMPLE".to_string(),
Expand All @@ -54,18 +54,18 @@ impl Contract {
/// Initializes the contract with the given total supply owned by the given `owner_id` with
/// the given fungible token metadata.
#[init]
pub fn new(owner_id: AccountId, total_supply: U128, metadata: FungibleTokenMetadata) -> Self {
pub fn new(owner_id: &AccountId, total_supply: U128, metadata: &FungibleTokenMetadata) -> Self {
require!(!env::state_exists(), "Already initialized");
metadata.assert_valid();
let mut this = Self {
token: FungibleToken::new(StorageKey::FungibleToken),
metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)),
metadata: LazyOption::new(StorageKey::Metadata, Some(metadata)),
};
this.token.internal_register_account(&owner_id);
this.token.internal_deposit(&owner_id, total_supply.into());
this.token.internal_register_account(owner_id);
this.token.internal_deposit(owner_id, total_supply.into());

near_contract_standards::fungible_token::events::FtMint {
owner_id: &owner_id,
owner_id,
amount: total_supply,
memo: Some("new tokens are minted"),
}
Expand All @@ -79,7 +79,7 @@ impl Contract {
impl FungibleTokenCore for Contract {
#[payable]
fn ft_transfer(&mut self, receiver_id: AccountId, amount: U128, memo: Option<String>) {
self.token.ft_transfer(receiver_id, amount, memo)
self.token.ft_transfer(receiver_id, amount, memo);
}

#[payable]
Expand Down
31 changes: 19 additions & 12 deletions near/nep141-locker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const STORAGE_BALANCE_OF_GAS: Gas = Gas::from_tgas(3);
const STORAGE_DEPOSIT_GAS: Gas = Gas::from_tgas(3);
const NO_DEPOSIT: NearToken = NearToken::from_near(0);
const ONE_YOCTO: NearToken = NearToken::from_yoctonear(1);
const NEP141_DEPOSIT: NearToken = NearToken::from_yoctonear(1250000000000000000000);
const NEP141_DEPOSIT: NearToken = NearToken::from_yoctonear(1_250_000_000_000_000_000_000);

const SIGN_PATH: &str = "bridge-1";

Expand Down Expand Up @@ -196,7 +196,7 @@ impl Contract {
contract
}

pub fn log_metadata(&self, token_id: AccountId) -> Promise {
pub fn log_metadata(&self, token_id: &AccountId) -> Promise {
ext_token::ext(token_id.clone())
.with_static_gas(LOG_METADATA_GAS)
.ft_metadata()
Expand All @@ -213,7 +213,7 @@ impl Contract {
pub fn log_metadata_callbcak(
&self,
#[callback] metadata: FungibleTokenMetadata,
token_id: AccountId,
token_id: &AccountId,
) -> Promise {
let metadata_payload = MetadataPayload {
token: token_id.to_string(),
Expand Down Expand Up @@ -357,12 +357,18 @@ impl Contract {
}
}

/// # Panics
///
/// This function will panic under the following conditions:
///
/// - If the `borsh::to_vec` serialization of the `TransferMessagePayload` fails.
/// - If a `fee` is provided and it doesn't match the fee in the stored transfer message.
#[payable]
pub fn sign_transfer(
&mut self,
nonce: U128,
fee_recipient: Option<AccountId>,
fee: Option<Fee>,
fee: &Option<Fee>,
) -> Promise {
let transfer_message = self.get_transfer_message(nonce);
if let Some(fee) = &fee {
Expand Down Expand Up @@ -390,7 +396,7 @@ impl Contract {
.then(
Self::ext(env::current_account_id())
.with_static_gas(SIGN_TRANSFER_CALLBACK_GAS)
.sign_transfer_callback(transfer_payload, transfer_message.fee),
.sign_transfer_callback(transfer_payload, &transfer_message.fee),
)
}

Expand All @@ -399,7 +405,7 @@ impl Contract {
&mut self,
#[callback_result] call_result: Result<SignatureResponse, PromiseError>,
#[serializer(borsh)] message_payload: TransferMessagePayload,
#[serializer(borsh)] fee: Fee,
#[serializer(borsh)] fee: &Fee,
) {
if let Ok(signature) = call_result {
let nonce = message_payload.nonce;
Expand Down Expand Up @@ -442,7 +448,7 @@ impl Contract {
.with_attached_deposit(attached_deposit)
.with_static_gas(CLAIM_FEE_CALLBACK_GAS)
.fin_transfer_callback(
args.storage_deposit_args,
&args.storage_deposit_args,
env::predecessor_account_id(),
args.native_fee_recipient,
),
Expand All @@ -453,7 +459,7 @@ impl Contract {
#[payable]
pub fn fin_transfer_callback(
&mut self,
#[serializer(borsh)] storage_deposit_args: StorageDepositArgs,
#[serializer(borsh)] storage_deposit_args: &StorageDepositArgs,
#[serializer(borsh)] predecessor_account_id: AccountId,
#[serializer(borsh)] native_fee_recipient: OmniAddress,
) -> PromiseOrValue<U128> {
Expand Down Expand Up @@ -684,14 +690,15 @@ impl Contract {
pub fn get_transfer_message(&self, nonce: U128) -> TransferMessage {
self.pending_transfers
.get(&nonce.0)
.map(|m| m.into_main().message)
.map(storage::TransferMessageStorage::into_main)
.map(|m| m.message)
.sdk_expect("The transfer does not exist")
}

pub fn get_transfer_message_storage(&self, nonce: U128) -> TransferMessageStorageValue {
self.pending_transfers
.get(&nonce.0)
.map(|m| m.into_main())
.map(storage::TransferMessageStorage::into_main)
.sdk_expect("The transfer does not exist")
}

Expand Down Expand Up @@ -740,7 +747,7 @@ impl Contract {
.flatten()
.is_some()
}
_ => false,
PromiseResult::Failed => false,
}
}

Expand Down Expand Up @@ -786,7 +793,7 @@ impl Contract {
let transfer = self
.pending_transfers
.remove(&nonce)
.map(|m| m.into_main())
.map(storage::TransferMessageStorage::into_main)
.sdk_expect("ERR_TRANSFER_NOT_EXIST");

let refund =
Expand Down
7 changes: 5 additions & 2 deletions near/nep141-locker/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use near_contract_standards::storage_management::{StorageBalance, StorageBalance
use near_sdk::{assert_one_yocto, borsh};
use near_sdk::{env, near_bindgen, AccountId, NearToken};

use crate::*;
use crate::{
require, BorshDeserialize, BorshSerialize, ChainKind, Contract, ContractExt, Deserialize, Fee,
OmniAddress, Promise, SdkExpect, Serialize, TransferMessage, U128,
};

#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize, Debug, Clone)]
pub struct TransferMessageStorageValue {
Expand Down Expand Up @@ -111,7 +114,7 @@ impl Contract {
}

pub fn storage_balance_of(&self, account_id: &AccountId) -> Option<StorageBalance> {
self.accounts_balances.get(&account_id)
self.accounts_balances.get(account_id)
}

pub fn required_balance_for_account(&self) -> NearToken {
Expand Down
34 changes: 19 additions & 15 deletions near/omni-prover/evm-prover/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,13 @@ impl EvmProver {
}
}

/// # Panics
///
/// This function will panic in the following situations:
/// - If the log entry at the specified index doesn't match the decoded log entry.
#[handle_result]
pub fn verify_proof(&self, #[serializer(borsh)] input: Vec<u8>) -> Result<Promise, String> {
let args = EvmVerifyProofArgs::try_from_slice(&input).map_err(|_| "ERR_PARSE_ARGS")?;
pub fn verify_proof(&self, #[serializer(borsh)] input: &[u8]) -> Result<Promise, String> {
let args = EvmVerifyProofArgs::try_from_slice(input).map_err(|_| "ERR_PARSE_ARGS")?;

let evm_proof = args.proof;
let header: BlockHeader = rlp::decode(&evm_proof.header_data).map_err(|e| e.to_string())?;
Expand Down Expand Up @@ -76,7 +80,7 @@ impl EvmProver {
.with_static_gas(VERIFY_PROOF_CALLBACK_GAS)
.verify_proof_callback(
args.proof_kind,
evm_proof.log_entry_data,
&evm_proof.log_entry_data,
header.hash.ok_or("ERR_HASH_NOT_SET")?.0,
),
))
Expand All @@ -87,7 +91,7 @@ impl EvmProver {
pub fn verify_proof_callback(
&mut self,
#[serializer(borsh)] kind: ProofKind,
#[serializer(borsh)] log_entry_data: Vec<u8>,
#[serializer(borsh)] log_entry_data: &[u8],
#[serializer(borsh)] expected_block_hash: H256,
#[callback]
#[serializer(borsh)]
Expand Down Expand Up @@ -133,11 +137,11 @@ impl EvmProver {
actual_key.push(el / 16);
actual_key.push(el % 16);
}
Self::_verify_trie_proof(expected_root.to_vec(), &actual_key, proof, 0, 0)
Self::_verify_trie_proof(&expected_root, &actual_key, proof, 0, 0)
}

fn _verify_trie_proof(
expected_root: Vec<u8>,
expected_root: &[u8],
key: &Vec<u8>,
proof: &Vec<Vec<u8>>,
key_index: usize,
Expand All @@ -147,15 +151,15 @@ impl EvmProver {

if key_index == 0 {
// trie root is always a hash
assert_eq!(keccak256(node), expected_root.as_slice());
assert_eq!(keccak256(node), expected_root);
} else if node.len() < 32 {
// if rlp < 32 bytes, then it is not hashed
assert_eq!(node.as_slice(), expected_root);
} else {
assert_eq!(keccak256(node), expected_root.as_slice());
assert_eq!(keccak256(node), expected_root);
}

let node = Rlp::new(&node.as_slice());
let node = Rlp::new(node.as_slice());

if node.iter().count() == 17 {
// Branch node
Expand All @@ -164,17 +168,17 @@ impl EvmProver {
get_vec(&node, 16)
} else {
let new_expected_root = get_vec(&node, key[key_index] as usize);
if !new_expected_root.is_empty() {
if new_expected_root.is_empty() {
// not included in proof
vec![]
} else {
Self::_verify_trie_proof(
new_expected_root,
&new_expected_root,
key,
proof,
key_index + 1,
proof_index + 1,
)
} else {
// not included in proof
vec![]
}
}
} else {
Expand Down Expand Up @@ -210,7 +214,7 @@ impl EvmProver {
assert_eq!(path.as_slice(), &key[key_index..key_index + path.len()]);
let new_expected_root = get_vec(&node, 1);
Self::_verify_trie_proof(
new_expected_root,
&new_expected_root,
key,
proof,
key_index + path.len(),
Expand Down
Loading
Loading