use nexus_sdk::{
solidity::{*, SafeMath},
contract_api::{ez::prelude::*, ez::ret},
require,
};
use nexus_sdk::solidity::uint256 as U256;
// State variables using Solidity-compatible Mappings
static BALANCES: Mapping<Address, U256> = Mapping::new(b"bal");
static OWNER: Mapping<&[u8], Address> = Mapping::new(b"owner");
// Initialize contract
nexus_fn! {
fn init(initial_value: U256) {
let sender = Blockchain::msg.sender();
OWNER.set(&b"val".as_slice(), sender.clone());
BALANCES.set(&sender, initial_value);
ret::u32(1)
}
}
// Public function with reentrancy protection
nexus_fn! {
fn transfer(to: Address, amount: U256) {
let _guard = ReentrancyGuard::new();
let sender = Blockchain::msg.sender();
let sender_bal = BALANCES.get(&sender);
require!(sender_bal >= amount, "Insufficient balance");
BALANCES.set(&sender, sender_bal.sub(amount));
let to_bal = BALANCES.get(&to);
BALANCES.set(&to, to_bal.add(amount));
emit("Transfer", &[]);
ret::u32(1)
}
}
// View function
nexus_fn! {
fn balanceOf(addr: Address) {
let bal = BALANCES.get(&addr);
let mut out = [0u8; 32];
bal.to_little_endian(&mut out);
ret::u256(&out)
}
}