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

Macro for logging #142

Merged
merged 3 commits into from
Jun 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
60 changes: 20 additions & 40 deletions src/connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ impl EthConnectorContract {
!sdk::storage_has_key(&Self::get_contract_key(&EthConnectorStorageId::Contract)),
"ERR_CONTRACT_INITIALIZED"
);
#[cfg(feature = "log")]
sdk::log("[init contract]");
crate::log!("[init contract]");

let contract_data = Self::set_contract_data(SetContractDataCallArgs {
prover_account: args.prover_account,
Expand Down Expand Up @@ -180,26 +179,23 @@ impl EthConnectorContract {
pub fn deposit(&self) {
self.assert_not_paused(PAUSE_DEPOSIT);

#[cfg(feature = "log")]
sdk::log("[Deposit tokens]");
crate::log!("[Deposit tokens]");

// Get incoming deposit arguments
let raw_proof = sdk::read_input();
let proof: Proof = Proof::try_from_slice(&raw_proof).expect(ERR_FAILED_PARSE);
// Fetch event data from Proof
let event = DepositedEvent::from_log_entry_data(&proof.log_entry_data);

#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Deposit started: from {} to recipient {:?} with amount: {:?} and fee {:?}",
hex::encode(event.sender),
event.recipient,
event.amount.as_u128(),
event.fee.as_u128()
));

#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Event's address {}, custodian address {}",
hex::encode(&event.eth_custodian_address),
hex::encode(&self.contract.eth_custodian_address),
Expand All @@ -212,8 +208,7 @@ impl EthConnectorContract {
assert!(event.amount > event.fee, "ERR_NOT_ENOUGH_BALANCE_FOR_FEE");

// Verify proof data with cross-contract call to prover account
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Deposit verify_log_entry for prover: {}",
self.contract.prover_account,
));
Expand Down Expand Up @@ -304,17 +299,15 @@ impl EthConnectorContract {
sdk::assert_private_call();
let data: FinishDepositCallArgs =
FinishDepositCallArgs::try_from_slice(&sdk::read_input()).unwrap();
#[cfg(feature = "log")]
sdk::log(&format!("Finish deposit NEAR amount: {}", data.amount));
crate::log!(&format!("Finish deposit NEAR amount: {}", data.amount));
assert_eq!(sdk::promise_results_count(), 1);

// Check promise results
let data0: Vec<u8> = match sdk::promise_result(0) {
PromiseResult::Successful(x) => x,
_ => sdk::panic_utf8(b"ERR_PROMISE_INDEX"),
};
#[cfg(feature = "log")]
sdk::log("Check verification_success");
crate::log!("Check verification_success");
let verification_success = bool::try_from_slice(&data0).unwrap();
assert!(verification_success, "ERR_VERIFY_PROOF");

Expand Down Expand Up @@ -357,17 +350,15 @@ impl EthConnectorContract {

/// Record used proof as hash key
fn record_proof(&mut self, key: &str) {
#[cfg(feature = "log")]
sdk::log(&format!("Record proof: {}", key));
crate::log!(&format!("Record proof: {}", key));

assert!(!self.check_used_event(key), "ERR_PROOF_EXIST");
self.save_used_event(key);
}

/// Mint NEAR tokens
fn mint_near(&mut self, owner_id: AccountId, amount: Balance) {
#[cfg(feature = "log")]
sdk::log(&format!("Mint NEAR {} tokens for: {}", amount, owner_id));
crate::log!(&format!("Mint NEAR {} tokens for: {}", amount, owner_id));

if self.ft.accounts_get(&owner_id).is_none() {
self.ft.accounts_insert(&owner_id, 0);
Expand All @@ -377,8 +368,7 @@ impl EthConnectorContract {

/// Mint ETH tokens
fn mint_eth(&mut self, owner_id: EthAddress, amount: Balance) {
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Mint ETH {} tokens for: {}",
amount,
hex::encode(owner_id)
Expand All @@ -388,8 +378,7 @@ impl EthConnectorContract {

/// Burn ETH tokens
fn burn_eth(&mut self, address: EthAddress, amount: Balance) {
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Burn ETH {} tokens for: {}",
amount,
hex::encode(address)
Expand Down Expand Up @@ -424,24 +413,21 @@ impl EthConnectorContract {
pub fn ft_total_supply(&self) {
let total_supply = self.ft.ft_total_supply();
sdk::return_output(total_supply.to_string().as_bytes());
#[cfg(feature = "log")]
sdk::log(&format!("Total supply: {}", total_supply));
crate::log!(&format!("Total supply: {}", total_supply));
}

/// Return total supply of NEAR
pub fn ft_total_supply_near(&self) {
let total_supply = self.ft.ft_total_supply_near();
sdk::return_output(total_supply.to_string().as_bytes());
#[cfg(feature = "log")]
sdk::log(&format!("Total supply NEAR: {}", total_supply));
crate::log!(&format!("Total supply NEAR: {}", total_supply));
}

/// Return total supply of ETH
pub fn ft_total_supply_eth(&self) {
let total_supply = self.ft.ft_total_supply_eth();
sdk::return_output(total_supply.to_string().as_bytes());
#[cfg(feature = "log")]
sdk::log(&format!("Total supply ETH: {}", total_supply));
crate::log!(&format!("Total supply ETH: {}", total_supply));
}

/// Return balance of NEAR
Expand All @@ -451,8 +437,7 @@ impl EthConnectorContract {
);
let balance = self.ft.ft_balance_of(&args.account_id);
sdk::return_output(balance.to_string().as_bytes());
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Balance of NEAR [{}]: {}",
args.account_id, balance
));
Expand All @@ -463,8 +448,7 @@ impl EthConnectorContract {
let args =
BalanceOfEthCallArgs::try_from_slice(&sdk::read_input()).expect(ERR_FAILED_PARSE);
let balance = self.ft.internal_unwrap_balance_of_eth(args.address);
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Balance of ETH [{}]: {}",
hex::encode(args.address),
balance
Expand All @@ -481,8 +465,7 @@ impl EthConnectorContract {
self.ft
.ft_transfer(&args.receiver_id, args.amount, &args.memo);
self.save_ft_contract();
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Transfer amount {} to {} success with memo: {:?}",
args.amount, args.receiver_id, args.memo
));
Expand All @@ -498,8 +481,7 @@ impl EthConnectorContract {
let amount = self
.ft
.ft_resolve_transfer(&args.sender_id, &args.receiver_id, args.amount);
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Resolve transfer from {} to {} success",
args.sender_id, args.receiver_id
));
Expand All @@ -512,8 +494,7 @@ impl EthConnectorContract {
/// We starting early checking for message data to avoid `ft_on_transfer` call panics
/// But we don't check relayer exists. If relayer doesn't exist we simply not mint/burn the amount of the fee
pub fn ft_transfer_call(&mut self, args: TransferCallCallArgs) {
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Transfer call to {} amount {}",
args.receiver_id, args.amount,
));
Expand Down Expand Up @@ -574,8 +555,7 @@ impl EthConnectorContract {
/// ft_on_transfer callback function
#[allow(clippy::unnecessary_unwrap)]
pub fn ft_on_transfer(&mut self, engine: &Engine) {
#[cfg(feature = "log")]
sdk::log("Call ft_on_transfer");
crate::log!("Call ft_on_transfer");
let args = FtOnTransfer::try_from_slice(&sdk::read_input()).expect(ERR_FAILED_PARSE);
let predecessor_account_id = String::from_utf8(sdk::predecessor_account_id()).unwrap();
let current_account_id = String::from_utf8(sdk::current_account_id()).unwrap();
Expand Down
18 changes: 6 additions & 12 deletions src/fungible_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,7 @@ impl FungibleToken {
assert!(amount > 0, "The amount should be a positive number");
self.internal_withdraw(sender_id, amount);
self.internal_deposit(receiver_id, amount);
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Transfer {} from {} to {}",
amount, sender_id, receiver_id
));
Expand Down Expand Up @@ -285,8 +284,7 @@ impl FungibleToken {
receiver_balance
};
self.accounts_insert(receiver_id, receiver_balance - refund_amount);
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Decrease receiver {} balance to: {}",
receiver_id,
receiver_balance - refund_amount
Expand All @@ -295,17 +293,15 @@ impl FungibleToken {
return if let Some(sender_balance) = self.accounts_get(sender_id) {
let sender_balance = u128::try_from_slice(&sender_balance[..]).unwrap();
self.accounts_insert(sender_id, sender_balance + refund_amount);
#[cfg(feature = "log")]
sdk::log(&format!(
crate::log!(&format!(
"Refund amount {} from {} to {}",
refund_amount, receiver_id, sender_id
));
(amount - refund_amount, 0)
} else {
// Sender's account was deleted, so we need to burn tokens.
self.total_supply -= refund_amount;
#[cfg(feature = "log")]
sdk::log("The account of the sender was deleted");
crate::log!("The account of the sender was deleted");
(amount, refund_amount)
};
}
Expand Down Expand Up @@ -344,8 +340,7 @@ impl FungibleToken {
sdk::panic_utf8(b"ERR_FAILED_UNREGISTER_ACCOUNT_POSITIVE_BALANCE")
}
} else {
#[cfg(feature = "log")]
sdk::log(&format!("The account {} is not registered", &account_id));
crate::log!(&format!("The account {} is not registered", &account_id));
None
}
}
Expand Down Expand Up @@ -386,8 +381,7 @@ impl FungibleToken {
let predecessor_account_id = String::from_utf8(sdk::predecessor_account_id()).unwrap();
let account_id = account_id.unwrap_or(&predecessor_account_id);
if self.accounts_contains_key(account_id) {
#[cfg(feature = "log")]
sdk::log("The account is already registered, refunding the deposit");
crate::log!("The account is already registered, refunding the deposit");
if amount > 0 {
let promise0 = sdk::promise_batch_create(&sdk::predecessor_account_id());
sdk::promise_batch_action_transfer(promise0, amount);
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,8 +524,7 @@ mod contract {
#[cfg(feature = "integration-test")]
#[no_mangle]
pub extern "C" fn verify_log_entry() {
#[cfg(feature = "log")]
sdk::log("Call from verify_log_entry");
crate::log!("Call from verify_log_entry");
let data = true.try_to_vec().unwrap();
sdk::return_output(&data[..]);
}
Expand Down
31 changes: 18 additions & 13 deletions src/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use crate::engine::Engine;
use crate::log_entry::LogEntry;
use crate::precompiles::ecrecover;
use crate::types::{AccountId, EthAddress};
use alloc::{format, vec::Vec};
#[cfg(feature = "log")]
use alloc::format;
use alloc::vec::Vec;
use borsh::{BorshDeserialize, BorshSerialize};
use ethabi::{Bytes, Event, EventParam, Hash, Log, RawLog, Token};

Expand Down Expand Up @@ -159,13 +161,13 @@ fn encode_eip712(
Token::Address(H160::from(custodian_address)),
])),
]);
sdk::log(&format!(
crate::log!(&format!(
"Domain_separator encoded: {}",
hex::encode(domain_separator_encoded.clone())
));

let domain_separator = sdk::keccak(&domain_separator_encoded);
sdk::log(&format!(
crate::log!(&format!(
"Domain_separator hash: {}",
hex::encode(domain_separator)
));
Expand All @@ -188,13 +190,13 @@ fn encode_eip712(
Token::Address(H160::from(custodian_address)),
])),
]);
sdk::log(&format!(
crate::log!(&format!(
"WithdrawFromEVM struct encoded: {}",
hex::encode(withdraw_from_evm_struct_encoded.clone()),
));

let withdraw_from_evm_struct_hash = sdk::keccak(&withdraw_from_evm_struct_encoded);
sdk::log(&format!(
crate::log!(&format!(
"WithdrawFromEVM struct hash: {}",
hex::encode(withdraw_from_evm_struct_hash)
));
Expand All @@ -204,13 +206,16 @@ fn encode_eip712(
Token::FixedBytes(domain_separator.as_bytes().to_vec()),
Token::FixedBytes(withdraw_from_evm_struct_hash.as_bytes().to_vec()),
]);
sdk::log(&format!(
crate::log!(&format!(
"digest_encoded: {}",
hex::encode(digest_encoded.clone())
));

// clippy doesn't like this `let` binding if the logging feature is disabled
// because the log line is not really there in that case
#[allow(clippy::let_and_return)]
let digest = sdk::keccak(&digest_encoded);
sdk::log(&format!("digest: {}", hex::encode(digest)));
crate::log!(&format!("digest: {}", hex::encode(&digest)));
digest
}

Expand All @@ -229,9 +234,9 @@ pub fn verify_withdraw_eip712(
WITHDRAW_FROM_EVM_TYPEHASH,
);
let withdraw_msg_signer = ecrecover(res, &eip712_signature[..]).unwrap();
sdk::log(&format!("sender: {}", hex::encode(sender)));
sdk::log(&format!("ecrecover: {}", hex::encode(withdraw_msg_signer)));
sdk::log(&format!(
crate::log!(&format!("sender: {}", hex::encode(sender)));
crate::log!(&format!("ecrecover: {}", hex::encode(withdraw_msg_signer)));
crate::log!(&format!(
"ecrecover: {}",
H160::from(sender) == withdraw_msg_signer
));
Expand All @@ -254,9 +259,9 @@ pub fn verify_transfer_eip712(
TRANSFER_FROM_EVM_TO_NEAR_TYPEHASH,
);
let withdraw_msg_signer = ecrecover(res, &eip712_signature[..]).unwrap();
sdk::log(&format!("sender: {}", hex::encode(sender)));
sdk::log(&format!("ecrecover: {}", hex::encode(withdraw_msg_signer)));
sdk::log(&format!(
crate::log!(&format!("sender: {}", hex::encode(sender)));
crate::log!(&format!("ecrecover: {}", hex::encode(withdraw_msg_signer)));
crate::log!(&format!(
"ecrecover: {}",
H160::from(sender) == withdraw_msg_signer
));
Expand Down
8 changes: 8 additions & 0 deletions src/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,14 @@ pub fn log(data: &str) {
log_utf8(data.as_bytes())
}

#[macro_export]
macro_rules! log {
($e: expr) => {
#[cfg(feature = "log")]
$crate::sdk::log($e)
};
}

#[allow(unused)]
pub fn prepaid_gas() -> u64 {
unsafe { exports::prepaid_gas() }
Expand Down