ink_primitives/sol/utils.rs
1// Copyright (C) ink! contributors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use alloy_sol_types::private::next_multiple_of_32;
16use ink_prelude::vec::Vec;
17
18/// Appends the given bytes to a topic (i.e. indexed event parameter) preimage where the
19/// append bytes must be padded to a non-zero multiple of 32 bytes (e.g. for a `string` or
20/// `bytes` member of a collection type).
21///
22/// # References
23///
24/// - <https://docs.soliditylang.org/en/latest/abi-spec.html#events>
25/// - <https://docs.soliditylang.org/en/latest/abi-spec.html#indexed-event-encoding>
26pub fn append_non_empty_member_topic_bytes(bytes: &[u8], preimage: &mut Vec<u8>) {
27 preimage.extend(bytes);
28 let size = non_zero_multiple_of_32(bytes.len());
29 if bytes.len() < size {
30 preimage.extend(core::iter::repeat_n(0u8, size - bytes.len()));
31 }
32}
33
34/// Same as `alloy_sol_types::utils::next_multiple_of_32` but returns `32` when n is zero.
35pub fn non_zero_multiple_of_32(n: usize) -> usize {
36 if n == 0 {
37 return 32;
38 }
39 next_multiple_of_32(n)
40}