1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use super::VmApiImpl;
use elrond_wasm::{
    api::{Handle, LogApi, LogApiImpl},
    types::heap::ArgBuffer,
};

extern "C" {
    fn writeLog(pointer: *const u8, length: i32, topicPtr: *const u8, numTopics: i32);

    fn writeEventLog(
        numTopics: i32,
        topicLengthsOffset: *const u8,
        topicOffset: *const u8,
        dataOffset: *const u8,
        dataLength: i32,
    );

    fn managedWriteLog(topicsHandle: i32, dataHandle: i32);
}

const LEGACY_TOPIC_LENGTH: usize = 32;

impl LogApi for VmApiImpl {
    type LogApiImpl = VmApiImpl;

    #[inline]
    fn log_api_impl() -> Self::LogApiImpl {
        VmApiImpl {}
    }
}

/// Interface to only be used by code generated by the macros.
/// The smart contract code doesn't have access to these methods directly.
impl LogApiImpl for VmApiImpl {
    fn write_event_log(&self, topics_buffer: &ArgBuffer, data: &[u8]) {
        unsafe {
            writeEventLog(
                topics_buffer.num_args() as i32,
                topics_buffer.arg_lengths_bytes_ptr(),
                topics_buffer.arg_data_ptr(),
                data.as_ptr(),
                data.len() as i32,
            );
        }
    }

    fn write_legacy_log(&self, topics: &[[u8; 32]], data: &[u8]) {
        let mut topics_raw = [0u8; LEGACY_TOPIC_LENGTH * 10]; // hopefully we never have more than 10 topics
        for i in 0..topics.len() {
            topics_raw[LEGACY_TOPIC_LENGTH * i..LEGACY_TOPIC_LENGTH * (i + 1)]
                .copy_from_slice(&topics[i]);
        }
        unsafe {
            writeLog(
                data.as_ptr(),
                data.len() as i32,
                topics_raw.as_ptr(),
                topics.len() as i32,
            );
        }
    }

    fn managed_write_log(&self, topics_handle: Handle, data_handle: Handle) {
        unsafe {
            managedWriteLog(topics_handle, data_handle);
        }
    }
}