Logging

In Sway, logging is an essential feature that allows smart contracts to record information during their execution. These logs can be used for debugging, auditing, or monitoring the behavior of smart contracts.

In the provided code, we define a smart contract named MyContract with a function called test_func that accepts a string of length 4 as a parameter.

  • We use the use statement to import the std::logging module, which provides logging functionality.
  • In the test_func function, we call the log function and pass the incoming string as the log message.

The test_func function of this smart contract will record the incoming string as a log message when executed. This simple example is intended to show you how to use logging in Sway to record the behavior of smart contracts. We hope this tutorial helps you better understand the logging feature in Sway.

All Examples
contract;

use std::{
    hash::Hash,
    auth::msg_sender
};

// StorageMap
// - basic (insert, read, update, remove)
// - nested

abi MyContract {
    #[storage(read, write)]
    fn basic_examples();

    #[storage(read, write)]
    fn nested_examples();
}

storage {
    balance_of: StorageMap = StorageMap {},
    allowance: StorageMap<(Identity, Identity), u64> = StorageMap {},
}

const ADDR: b256 = 0x1000000000000000000000000000000000000000000000000000000000000000;

impl MyContract for Contract {
    #[storage(read, write)]
    fn basic_examples() {
        let sender = msg_sender().unwrap();

        // Insert
        storage.balance_of.insert(sender, 123);
        // Read
        let bal = storage.balance_of.get(sender).try_read().unwrap_or(0);
        // Update
        storage.balance_of.insert(sender, bal + 1);
        // Remove
        storage.balance_of.remove(sender);
    }

    #[storage(read, write)]
    fn nested_examples() {
        let sender = msg_sender().unwrap();
        let spender = Identity::Address(Address::from(ADDR));

        // Read
        let val = storage.allowance.get((sender, spender)).try_read().unwrap_or(0);
        // Insert / update
        storage.allowance.insert((sender, spender), val + 1);
        // Remove
        storage.allowance.remove((sender, spender));
    }
}