Skip to content

Commit 54798c5

Browse files
committed
lint and minor README, test.sh
1 parent 392c552 commit 54798c5

File tree

8 files changed

+173
-92
lines changed

8 files changed

+173
-92
lines changed

README.md

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,9 @@ Smart contracts on NEAR used by the
2424
Run all contracts unit tests like this:
2525

2626
```
27-
cd near-contracts/conversion_proxy
28-
cargo test
29-
cd near-contracts/fungible_conversion_proxy
30-
cargo test
31-
cd near-contracts/fungible_proxy
32-
cargo test
33-
cd near-contracts/mocks
34-
cargo test
27+
cargo test -p conversion_proxy
28+
cargo test -p fungible_conversion_proxy
29+
cargo test -p fungible_proxy
3530
```
3631

3732
## Integration tests

conversion_proxy/src/lib.rs

Lines changed: 56 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use near_sdk::json_types::{ValidAccountId, U128, U64};
33
use near_sdk::serde::{Deserialize, Serialize};
44
use near_sdk::serde_json::json;
55
use near_sdk::{
6-
env, log, near_bindgen, serde_json, AccountId, Balance, Gas, Promise, PromiseResult, Timestamp,
6+
bs58, env, log, near_bindgen, serde_json, AccountId, Balance, Gas, Promise, PromiseResult,
7+
Timestamp,
78
};
89

910
near_sdk::setup_alloc!();
@@ -19,7 +20,6 @@ const BASIC_GAS: Gas = 10_000_000_000_000;
1920
* Switchboard oracle-related declarations
2021
*/
2122

22-
2323
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
2424
pub struct SwitchboardDecimal {
2525
pub mantissa: i128,
@@ -36,7 +36,7 @@ pub struct PriceEntry {
3636

3737
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
3838
pub struct SwitchboarIx {
39-
pub address: Vec<u8>, // This feed address reference a specific price feed, see https://app.switchboard.xyz
39+
pub address: Vec<u8>, // This feed address reference a specific price feed, see https://app.switchboard.xyz
4040
pub payer: Vec<u8>,
4141
}
4242

@@ -46,7 +46,6 @@ trait Switchboard {
4646
fn aggregator_read(ix: SwitchboarIx) -> Promise<PriceEntry>;
4747
}
4848

49-
5049
///
5150
/// This contract
5251
/// - feed_parser: should be a valid Switchboard feed parser
@@ -58,7 +57,7 @@ trait Switchboard {
5857
pub struct ConversionProxy {
5958
pub feed_parser: AccountId,
6059
pub feed_address: Vec<u8>,
61-
pub feed_payer:Vec<u8>,
60+
pub feed_payer: Vec<u8>,
6261
pub owner_id: AccountId,
6362
}
6463

@@ -123,16 +122,24 @@ impl ConversionProxy {
123122
env::prepaid_gas(),
124123
MIN_GAS
125124
);
126-
assert_eq!(currency, "USD", "Only payments denominated in USD are implemented for now");
125+
assert_eq!(
126+
currency, "USD",
127+
"Only payments denominated in USD are implemented for now"
128+
);
127129

128130
let reference_vec: Vec<u8> = hex::decode(payment_reference.replace("0x", ""))
129131
.expect("Payment reference value error");
130132
assert_eq!(reference_vec.len(), 8, "Incorrect payment reference length");
131133

132-
let get_rate = sb_contract::aggregator_read(SwitchboarIx {address: self.feed_address.clone(), payer: self.feed_payer.clone()},
134+
let get_rate = sb_contract::aggregator_read(
135+
SwitchboarIx {
136+
address: self.feed_address.clone(),
137+
payer: self.feed_payer.clone(),
138+
},
133139
&self.feed_parser,
134140
NO_DEPOSIT,
135-
BASIC_GAS,);
141+
BASIC_GAS,
142+
);
136143
let callback_gas = BASIC_GAS * 3;
137144
let process_request_payment = ext_self::rate_callback(
138145
to,
@@ -178,20 +185,22 @@ impl ConversionProxy {
178185
pub fn set_feed_address(&mut self, feed_address: String) {
179186
let signer_id = env::predecessor_account_id();
180187
if self.owner_id == signer_id {
181-
self.feed_address = bs58::decode(feed_address).into_vec().expect("Wrong feed address format");
188+
self.feed_address = bs58::decode(feed_address)
189+
.into_vec()
190+
.expect("Wrong feed address format");
182191
} else {
183192
panic!("ERR_PERMISSION");
184193
}
185194
}
186-
195+
187196
pub fn get_feed_address(&self) -> Vec<u8> {
188197
return self.feed_address.clone();
189198
}
190199

191200
pub fn get_encoded_feed_address(&self) -> String {
192201
return bs58::encode(self.feed_address.clone()).into_string();
193202
}
194-
203+
195204
pub fn set_owner(&mut self, owner: ValidAccountId) {
196205
let signer_id = env::predecessor_account_id();
197206
if self.owner_id == signer_id {
@@ -206,23 +215,35 @@ impl ConversionProxy {
206215
if self.owner_id == signer_id {
207216
let feed_payer = env::signer_account_pk();
208217
let vec_length = feed_payer.len();
209-
println!("feed_payer: {}, len: {}", feed_payer.clone().into_iter().map(|c| c.to_string()).collect::<Vec<String>>().join(","), vec_length);
218+
println!(
219+
"feed_payer: {}, len: {}",
220+
feed_payer
221+
.clone()
222+
.into_iter()
223+
.map(|c| c.to_string())
224+
.collect::<Vec<String>>()
225+
.join(","),
226+
vec_length
227+
);
210228
if vec_length == 32 {
211229
self.feed_payer = env::signer_account_pk();
212230
return;
213231
}
214232
// For some reason the VM prepends a 0 in front of the 32-long vector
215233
if vec_length > 32 {
216-
log!("Trimming the feed_payer pk to fit length 32 from length {}", vec_length);
217-
self.feed_payer = feed_payer[vec_length-32..].to_vec();
218-
return
234+
log!(
235+
"Trimming the feed_payer pk to fit length 32 from length {}",
236+
vec_length
237+
);
238+
self.feed_payer = feed_payer[vec_length - 32..].to_vec();
239+
return;
219240
}
220241
panic!("ERR_OWNER_PK_LENGTH");
221-
} else {
242+
} else {
222243
panic!("ERR_PERMISSION");
223244
}
224245
}
225-
246+
226247
pub fn get_feed_payer(&self) -> Vec<u8> {
227248
return self.feed_payer.clone();
228249
}
@@ -303,26 +324,34 @@ impl ConversionProxy {
303324
PromiseResult::Failed => panic!("ERR_FAILED_ORACLE_FETCH"),
304325
};
305326
// Check rate errors
306-
assert!(rate.num_error == 0 && rate.num_success == 1, "Conversion errors: {}, successes: {}", rate.num_error, rate.num_success);
327+
assert!(
328+
rate.num_error == 0 && rate.num_success == 1,
329+
"Conversion errors: {}, successes: {}",
330+
rate.num_error,
331+
rate.num_success
332+
);
307333
// Check rate validity
308334
assert!(
309335
u64::from(max_rate_timespan) == 0
310-
|| rate.round_open_timestamp >= env::block_timestamp() - u64::from(max_rate_timespan),
336+
|| rate.round_open_timestamp
337+
>= env::block_timestamp() - u64::from(max_rate_timespan),
311338
"Conversion rate too old (Last updated: {})",
312339
rate.round_open_timestamp,
313340
);
314-
let conversion_rate = 0_u128.checked_add_signed(rate.result.mantissa).expect("Negative conversion rate");
341+
let conversion_rate = 0_u128
342+
.checked_add_signed(rate.result.mantissa)
343+
.expect("Negative conversion rate");
315344
let decimals = u32::from(rate.result.scale);
316-
let main_payment =
317-
(Balance::from(amount) * ONE_NEAR * 10u128.pow(decimals) / conversion_rate / ONE_FIAT) as u128;
345+
let main_payment = (Balance::from(amount) * ONE_NEAR * 10u128.pow(decimals)
346+
/ conversion_rate
347+
/ ONE_FIAT) as u128;
318348
let fee_payment = Balance::from(fee_amount) * ONE_NEAR * 10u128.pow(decimals)
319349
/ conversion_rate
320350
/ ONE_FIAT;
321351

322352
let total_payment = main_payment + fee_payment;
323353
// Check deposit
324354
if total_payment > env::attached_deposit() {
325-
326355
Promise::new(payer.clone().to_string()).transfer(env::attached_deposit());
327356
log!(
328357
"Deposit too small for payment (Supplied: {}. Demand (incl. fees): {})",
@@ -387,7 +416,10 @@ mod tests {
387416
VMContext {
388417
current_account_id: predecessor_account_id.clone(),
389418
signer_account_id: predecessor_account_id.clone(),
390-
signer_account_pk: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
419+
signer_account_pk: vec![
420+
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
421+
23, 24, 25, 26, 27, 28, 29, 30, 31,
422+
],
391423
predecessor_account_id,
392424
input: vec![],
393425
block_index: 1,

mocks/src/fpo_oracle_mock.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ impl FPOContract {
5151
mod tests {
5252

5353
use super::*;
54-
// use crate::fpo_oracle_mock::AccountId;
5554
use near_sdk::{testing_env, Balance, Gas, MockedBlockchain, VMContext};
5655
use near_sdk_sim::to_yocto;
5756

mocks/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
pub mod fpo_oracle_mock;
22
pub mod fungible_token_mock;
3-
pub mod switchboard_feed_parser_mock;
3+
pub mod switchboard_feed_parser_mock;
Lines changed: 55 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,30 @@
11
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
22
use near_sdk::serde::{Deserialize, Serialize};
3-
use near_sdk::{Timestamp, env, near_bindgen, bs58};
3+
use near_sdk::{bs58, env, near_bindgen, Timestamp};
44

55
/**
66
* Mocking the Switchboard feed parser contract for tests
77
*/
88

9+
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
10+
pub struct SwitchboardDecimal {
11+
pub mantissa: i128,
12+
pub scale: u32,
13+
}
914

10-
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
11-
pub struct SwitchboardDecimal {
12-
pub mantissa: i128,
13-
pub scale: u32,
14-
}
15-
16-
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
17-
pub struct PriceEntry {
18-
pub result: SwitchboardDecimal,
19-
pub num_success: u32,
20-
pub num_error: u32,
21-
pub round_open_timestamp: Timestamp,
22-
}
15+
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
16+
pub struct PriceEntry {
17+
pub result: SwitchboardDecimal,
18+
pub num_success: u32,
19+
pub num_error: u32,
20+
pub round_open_timestamp: Timestamp,
21+
}
2322

24-
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
25-
pub struct SwitchboarIx {
26-
pub address: Vec<u8>,
27-
pub payer: Vec<u8>,
28-
}
23+
#[derive(BorshDeserialize, BorshSerialize, Serialize, Deserialize)]
24+
pub struct SwitchboarIx {
25+
pub address: Vec<u8>,
26+
pub payer: Vec<u8>,
27+
}
2928

3029
// For mocks: state of Switchboard feed parser
3130
#[near_bindgen]
@@ -36,20 +35,20 @@ pub struct SwitchboardFeedParser {}
3635
impl SwitchboardFeedParser {
3736
#[allow(unused_variables)]
3837
pub fn aggregator_read(&self, ix: SwitchboarIx) -> Option<PriceEntry> {
39-
match &*bs58::encode(ix.address).into_string() {
40-
"testNEARtoUSD" => Some(PriceEntry {
41-
result: SwitchboardDecimal {
42-
mantissa: i128::from(1234000),
43-
scale: u8::from(6).into()
44-
},
45-
num_success: 1,
46-
num_error: 0,
47-
round_open_timestamp: env::block_timestamp() -10,
48-
}),
49-
_ => {
50-
panic!("InvalidAggregator")
51-
},
52-
}
38+
match &*bs58::encode(ix.address).into_string() {
39+
"testNEARtoUSD" => Some(PriceEntry {
40+
result: SwitchboardDecimal {
41+
mantissa: i128::from(1234000),
42+
scale: u8::from(6).into(),
43+
},
44+
num_success: 1,
45+
num_error: 0,
46+
round_open_timestamp: env::block_timestamp() - 10,
47+
}),
48+
_ => {
49+
panic!("InvalidAggregator")
50+
}
51+
}
5352
}
5453
}
5554

@@ -58,7 +57,7 @@ mod tests {
5857

5958
use super::*;
6059
// use crate::switchboard_feed_parser_mock::SwitchboardFeedParser;
61-
use near_sdk::{testing_env, Balance, Gas, MockedBlockchain, VMContext, AccountId};
60+
use near_sdk::{testing_env, AccountId, Balance, Gas, MockedBlockchain, VMContext};
6261
use near_sdk_sim::to_yocto;
6362

6463
fn get_context(
@@ -88,32 +87,46 @@ mod tests {
8887
}
8988
#[test]
9089
fn aggregator_read() {
91-
let disp_vec = bs58::decode("E81iAUr7RPDUksAFtZxn7curbUVRy1Gps6sr6JnQALHx").into_vec().expect("!!").into_iter().map(|c| c.to_string()).collect::<Vec<String>>().join(",");
90+
let disp_vec = bs58::decode("E81iAUr7RPDUksAFtZxn7curbUVRy1Gps6sr6JnQALHx")
91+
.into_vec()
92+
.expect("!!")
93+
.into_iter()
94+
.map(|c| c.to_string())
95+
.collect::<Vec<String>>()
96+
.join(",");
9297
println!("RESULT: {}", disp_vec);
9398
let context = get_context("alice.near".to_string(), to_yocto("1"), 10u64.pow(14), true);
9499
testing_env!(context);
95100
let contract = SwitchboardFeedParser::default();
96101
if let Some(result) = contract.aggregator_read(SwitchboarIx {
97-
address: bs58::decode("testNEARtoUSD").into_vec().expect("WRONG VEC"),
98-
payer: bs58::decode("anynearpayer").into_vec().expect("WRONG VEC")
102+
address: bs58::decode("testNEARtoUSD").into_vec().expect("WRONG VEC"),
103+
payer: bs58::decode("anynearpayer").into_vec().expect("WRONG VEC"),
99104
}) {
100-
assert_eq!(result.result.mantissa, i128::from(1234000));
101-
assert_eq!(result.result.scale, 6);
105+
assert_eq!(result.result.mantissa, i128::from(1234000));
106+
assert_eq!(result.result.scale, 6);
102107
} else {
103108
panic!("NEAR/USD mock returned None")
104109
}
105110
}
106111
#[test]
107112
#[should_panic(expected = r#"InvalidAggregator"#)]
108113
fn missing_aggregator_read() {
109-
let disp_vec = bs58::decode("E81iAUr7RPDUksAFtZxn7curbUVRy1Gps6sr6JnQALHx").into_vec().expect("!!").into_iter().map(|c| c.to_string()).collect::<Vec<String>>().join(",");
114+
let disp_vec = bs58::decode("E81iAUr7RPDUksAFtZxn7curbUVRy1Gps6sr6JnQALHx")
115+
.into_vec()
116+
.expect("!!")
117+
.into_iter()
118+
.map(|c| c.to_string())
119+
.collect::<Vec<String>>()
120+
.join(",");
110121
println!("RESULT: {}", disp_vec);
111122
let context = get_context("alice.near".to_string(), to_yocto("1"), 10u64.pow(14), true);
112123
testing_env!(context);
113124
let contract = SwitchboardFeedParser::default();
114125
contract.aggregator_read(SwitchboarIx {
115-
address: bs58::decode("wrongAggregator").into_vec().expect("WRONG VEC"),
116-
payer: bs58::decode("anynearpayer").into_vec().expect("WRONG VEC")
126+
address: bs58::decode("wrongAggregator")
127+
.into_vec()
128+
.expect("WRONG VEC"),
129+
payer: bs58::decode("anynearpayer").into_vec().expect("WRONG VEC"),
117130
});
118131
}
119132
}

test.sh

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
cd mocks/
1+
./mocks/build.sh
22
./build.sh
3-
cd ..
43
cargo test --all

0 commit comments

Comments
 (0)