This file acts as the main entry point for your contract.
// Only run this as a WASM if the export-abi feature is not set.
#![cfg_attr(not(any(feature = "export-abi", test)), no_main)]
extern crate alloc;
mod erc20;
use alloy_primitives::{Address, U256};
use stylus_sdk::{msg, prelude::*};
use crate::erc20::{Erc20, Erc20Params, Erc20Error};
#[global_allocator]
static ALLOC: mini_alloc::MiniAlloc = mini_alloc::MiniAlloc::INIT;
struct StylusTokenParams;
impl Erc20Params for StylusTokenParams {
const NAME: &'static str = "StylusToken";
const SYMBOL: &'static str = "STK";
const DECIMALS: u8 = 18;
}
sol_storage! {
#[entrypoint]
struct StylusToken {
#[borrow]
Erc20<StylusTokenParams> erc20;
}
}
#[external]
#[inherit(Erc20<StylusTokenParams>)]
impl StylusToken {
pub fn mint(&mut self, value: U256) -> Result<(), Erc20Error> {
self.erc20.mint(msg::sender(), value)?;
Ok(())
}
pub fn mint_to(&mut self, to: Address, value: U256) -> Result<(), Erc20Error> {
self.erc20.mint(to, value)?;
Ok(())
}
pub fn burn(&mut self, value: U256) -> Result<(), Erc20Error> {
self.erc20.burn(msg::sender(), value)?;
Ok(())
}
}
Continuing from the Explanation of the Code section:
Explanation of the Code
Storage Definition: The sol_storage! macro defines the contract’s storage, mapping addresses to balances and allowances, keeping track of the total supply, and including a PhantomData field to allow for generics.
Events and Errors: The sol! macro declares events such as Transfer and Approval, and errors like InsufficientBalance and InsufficientAllowance, which are used to signal important state changes and conditions.
Internal Methods:
_transfer: Handles the logic for transferring tokens between accounts, updating balances, and emitting the Transfer event.
mint: Increases the balance of a specified address and the total supply, emitting a Transfer event from the zero address.
burn: Decreases the balance of a specified address and the total supply, emitting a Transfer event to the zero address.
External Methods:
name, symbol, decimals: Return the immutable token name, symbol, and decimals as specified by the Erc20Params trait.
total_supply: Returns the total supply of the token.
balance_of: Returns the balance of a specified address.
transfer: Transfers tokens from the sender’s account to another address, updating balances and emitting the Transfer event.
transfer_from: Transfers tokens from one address to another using an allowance, updating balances, decreasing the allowance, and emitting the Transfer event.
approve: Approves another address to spend a specified amount of tokens on behalf of the sender, updating allowances and emitting the Approval event.
allowance: Returns the remaining number of tokens that a spender is allowed to spend on behalf of the owner.