Skip to content

Commit

Permalink
feat: getting rid of json serialization and near_sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksuss committed Mar 24, 2024
1 parent 3abccc8 commit 1e44a5e
Show file tree
Hide file tree
Showing 26 changed files with 2,078 additions and 1,060 deletions.
1,276 changes: 536 additions & 740 deletions Cargo.lock

Large diffs are not rendered by default.

9 changes: 3 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ members = [

[workspace.dependencies]
anyhow = "1"
aurora-engine-types = "1"
aurora-engine-types = { git = "https://github.com/aurora-is-near/aurora-engine", rev = "fbe7f33", default-features = false }
ethabi = "18"
near-sdk = "4.1"
near-sdk = "5"
near-plugins = { git = "https://github.com/aurora-is-near/near-plugins", tag = "v0.2.0" }
once_cell = "1"
serde = { version = "1", features = ["derive"] }
near-workspaces = "0.9"
near-workspaces = "0.10"
tokio = { version = "1", features = ["macros"] }

[profile.release]
Expand All @@ -36,6 +36,3 @@ lto = true
debug = false
panic = "abort"
overflow-checks = true

[patch.crates-io]
parity-secp256k1 = { git = 'https://github.com/paritytech/rust-secp256k1', rev = "d05fd8e" }
24 changes: 18 additions & 6 deletions Makefile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,33 @@ args = [
"--all-targets"
]

[tasks.build-contracts]
[tasks.build-forwarder]
command = "cargo"
env = { "RUSTFLAGS" = "-C link-arg=-s" }
args = [
"build",
"--target",
"${TARGET}",
"--release",
"--workspace",
"--exclude",
"aurora-forwarder-tests",
"--exclude",
"aurora-forwarder-factory"
"--package",
"aurora-forwarder"
]

[tasks.build-fees]
command = "cargo"
env = { "RUSTFLAGS" = "-C link-arg=-s" }
args = [
"build",
"--target",
"${TARGET}",
"--release",
"--package",
"aurora-forward-fees",
]

[tasks.build-contracts]
dependencies = ["build-forwarder", "build-fees"]

[tasks.optimize-contracts]
dependencies = ["download-wasm-opt"]
script = '''
Expand Down
1 change: 1 addition & 0 deletions factory/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ nursery = "deny"
pedantic = "deny"

[dependencies]
aurora-engine-types.workspace = true
forwarder-utils = { path = "../utils" }
near-sdk.workspace = true
43 changes: 31 additions & 12 deletions factory/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
use aurora_engine_types::types::Address;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::serde::{Deserialize, Serialize};
use near_sdk::serde_json::json;
use near_sdk::{
assert_self, env, ext_contract, near_bindgen, AccountId, Balance, Gas, PanicOnDefault, Promise,
assert_self, env, ext_contract, near_bindgen, AccountId, Gas, NearToken, PanicOnDefault,
Promise,
};

const FORWARDER_WASM: &[u8] = include_bytes!("../../res/aurora-forwarder.wasm");
const INIT_BALANCE: Balance = 1_530_000_000_000_000_000_000_000;
const STORAGE_BALANCE_BOUND: Balance = 1_250_000_000_000_000_000_000;
const FORWARDER_NEW_GAS: Gas = Gas(1_000_000_000_000);
const INIT_BALANCE: NearToken = NearToken::from_millinear(450);
const STORAGE_BALANCE_BOUND: NearToken = NearToken::from_yoctonear(1_250_000_000_000_000_000_000);
const FORWARDER_NEW_GAS: Gas = Gas::from_tgas(5);
const MAX_NUM_CONTRACTS: usize = 8;

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
#[borsh(crate = "near_sdk::borsh")]
pub struct AuroraForwarderFactory {
owner: AccountId,
fees_contract_id: AccountId,
Expand All @@ -22,6 +24,7 @@ pub struct AuroraForwarderFactory {
impl AuroraForwarderFactory {
#[init]
#[must_use]
#[allow(clippy::use_self)]
pub fn new(fees_contract_id: AccountId) -> Self {
Self {
owner: env::predecessor_account_id(),
Expand Down Expand Up @@ -55,18 +58,25 @@ impl AuroraForwarderFactory {
&params.target_network,
&self.fees_contract_id,
);
let args = near_sdk::serde_json::to_vec(&json!({
"target_address": params.target_address,
"target_network": params.target_network,
"fees_contract_id": &self.fees_contract_id,
"wnear_contract_id": params.wnear_contract_id,
}))
let args = borsh::to_vec(&ForwarderParameters {
target_address: Address::decode(params.target_address.trim_start_matches("0x"))
.unwrap(),
target_network: &params.target_network,
wnear_contract_id: &params.wnear_contract_id,
fees_contract_id: &self.fees_contract_id,
})
.expect("Couldn't create args");

let _ = Promise::new(forwarder_id.clone())
.create_account()
.transfer(INIT_BALANCE)
.deploy_contract(FORWARDER_WASM.to_vec())
.function_call("new".to_string(), args, 0, FORWARDER_NEW_GAS)
.function_call(
"new".to_string(),
args,
NearToken::from_near(0),
FORWARDER_NEW_GAS,
)
.then(
ext_token::ext(params.wnear_contract_id)
.with_attached_deposit(STORAGE_BALANCE_BOUND)
Expand Down Expand Up @@ -104,6 +114,15 @@ pub struct DeployParameters {
pub wnear_contract_id: AccountId,
}

#[derive(BorshSerialize)]
#[borsh(crate = "near_sdk::borsh")]
pub struct ForwarderParameters<'a> {
pub target_address: Address,
pub target_network: &'a AccountId,
pub wnear_contract_id: &'a AccountId,
pub fees_contract_id: &'a AccountId,
}

fn create_forwarder_id(
address: &str,
network: &AccountId,
Expand Down
1 change: 1 addition & 0 deletions fees/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ nursery = "deny"
pedantic = "deny"

[dependencies]
aurora-engine-types.workspace = true
near-sdk.workspace = true
28 changes: 17 additions & 11 deletions fees/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use aurora_engine_types::types::Address;
use near_sdk::borsh::{BorshDeserialize, BorshSerialize};
use near_sdk::json_types::{U128, U64};
use near_sdk::{env, near_bindgen, AccountId, IntoStorageKey, PanicOnDefault};
use std::collections::BTreeSet;
Expand All @@ -14,6 +15,7 @@ const DEFAULT_PERCENT: U64 = U64(500); // 5%

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
#[borsh(crate = "near_sdk::borsh")]
pub struct FeesCalculator {
percent: Option<U64>,
owner: AccountId,
Expand All @@ -29,6 +31,7 @@ impl FeesCalculator {
/// The constructor panics if the state already exists.
#[init]
#[must_use]
#[allow(clippy::use_self)]
pub fn new(tokens: Vec<AccountId>) -> Self {
Self {
percent: Some(DEFAULT_PERCENT),
Expand All @@ -43,12 +46,13 @@ impl FeesCalculator {
///
/// There is a safe unwrap because we return 0 if the percent is None.
#[must_use]
#[result_serializer(borsh)]
pub fn calculate_fees(
&self,
amount: U128,
token_id: &AccountId,
target_network: &AccountId,
target_address: String,
#[serializer(borsh)] amount: U128,
#[serializer(borsh)] token_id: &AccountId,
#[serializer(borsh)] target_network: &AccountId,
#[serializer(borsh)] target_address: Address,
) -> U128 {
let _ = (target_network, target_address);

Expand Down Expand Up @@ -118,6 +122,7 @@ impl FeesCalculator {
}

#[derive(BorshDeserialize, BorshSerialize)]
#[borsh(crate = "near_sdk::borsh")]
enum KeyPrefix {
SupportedTokens,
}
Expand Down Expand Up @@ -185,6 +190,7 @@ fn validate_decimal_part(percent: &str) -> Result<(), ParseError> {
#[cfg(test)]
mod tests {
use super::{parse_percent, FeesCalculator, ParseError};
use aurora_engine_types::types::Address;
use near_sdk::AccountId;

#[test]
Expand Down Expand Up @@ -216,19 +222,19 @@ mod tests {
#[test]
fn test_check_supported_tokens() {
let aurora = "aurora".parse().unwrap();
let target_address = "0xea2342".to_string();
let target_address = Address::default();
let usdt = "usdt.near".parse().unwrap();
let mut contract = FeesCalculator::new(vec![]);

assert_eq!(
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address.clone()),
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address),
0.into() // we don't support the `usdt.near` yet, so we get 0 here
);

contract.add_supported_token(usdt.clone());

assert_eq!(
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address.clone()),
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address),
50.into()
);

Expand All @@ -243,19 +249,19 @@ mod tests {
#[test]
fn test_check_set_fee() {
let aurora = "aurora".parse().unwrap();
let target_address = "0xea2342".to_string();
let target_address = Address::default();
let usdt: AccountId = "usdt.near".parse().unwrap();
let mut contract = FeesCalculator::new(vec![usdt.clone()]);

assert_eq!(
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address.clone()),
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address),
50.into()
);

contract.set_fee_percent(Some("0".to_string()));

assert_eq!(
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address.clone()),
contract.calculate_fees(1000.into(), &usdt, &aurora, target_address),
0.into()
);

Expand Down
7 changes: 5 additions & 2 deletions forwarder/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,8 @@ pedantic = "deny"
as_conversions = "deny"

[dependencies]
forwarder-utils = {path = "../utils" }
near-sdk.workspace = true
arrayvec = { version = "0.7", default-features = false }
borsh = { version = "1", default-features = false, features = ["derive"] }
bs58 = { version = "0.5", default-features = false }
hex = { version = "0.4", default-features = false }
wee_alloc = { version = "0.4", default-features = false }
26 changes: 26 additions & 0 deletions forwarder/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq, Eq))]
pub enum ContractError {
ParseAccountError,
BorshDeserializeError,
BorshSerializeError,
OneYoctoAttachError,
PrivateCallError,
BadUtf8String,
BadNumber,
Other,
}

impl AsRef<[u8]> for ContractError {
fn as_ref(&self) -> &[u8] {
match self {
Self::ParseAccountError => b"ERR_PARS_ACCOUNT",
Self::BorshDeserializeError => b"ERR_BORCH_DESERIALIZE",
Self::BorshSerializeError => b"ERR_BORCH_SERIALIZE",
Self::OneYoctoAttachError => b"ERR_ONE_YOCTO_ATACH",
Self::PrivateCallError => b"ERR_PRIVATE_CALL",
Self::BadUtf8String => b"ERR_BAD_UTF8_STRING",
Self::BadNumber => b"ERR_BAD_NUMBER",
Self::Other => b"ERR_OTHER",
}
}
}
Loading

0 comments on commit 1e44a5e

Please sign in to comment.