use alloc::string::ToString;
use alloc::vec::Vec;
use miden_assembly::serde::Deserializable;
use miden_core::program::Program;
use miden_core::{Felt, Word};
use miden_protocol::account::AccountId;
use miden_protocol::crypto::rand::FeltRng;
use miden_protocol::errors::NoteError;
use miden_protocol::note::{
Note,
NoteAssets,
NoteAttachment,
NoteMetadata,
NoteRecipient,
NoteScript,
NoteStorage,
NoteType,
};
use miden_standards::note::{NetworkAccountTarget, NoteExecutionHint};
use miden_utils_sync::LazyLock;
use crate::EthAddress;
static B2AGG_SCRIPT: LazyLock<NoteScript> = LazyLock::new(|| {
let bytes = include_bytes!(concat!(env!("OUT_DIR"), "/assets/note_scripts/B2AGG.masb"));
let program = Program::read_from_bytes(bytes).expect("shipped B2AGG script is well-formed");
NoteScript::new(program)
});
pub struct B2AggNote;
impl B2AggNote {
pub const NUM_STORAGE_ITEMS: usize = 6;
pub fn script() -> NoteScript {
B2AGG_SCRIPT.clone()
}
pub fn script_root() -> Word {
B2AGG_SCRIPT.root()
}
pub fn create<R: FeltRng>(
destination_network: u32,
destination_address: EthAddress,
assets: NoteAssets,
target_account_id: AccountId,
sender_account_id: AccountId,
rng: &mut R,
) -> Result<Note, NoteError> {
let note_storage = build_note_storage(destination_network, destination_address)?;
let attachment = NoteAttachment::from(
NetworkAccountTarget::new(target_account_id, NoteExecutionHint::Always)
.map_err(|e| NoteError::other(e.to_string()))?,
);
let metadata =
NoteMetadata::new(sender_account_id, NoteType::Public).with_attachment(attachment);
let recipient = NoteRecipient::new(rng.draw_word(), Self::script(), note_storage);
Ok(Note::new(assets, metadata, recipient))
}
}
fn build_note_storage(
destination_network: u32,
destination_address: EthAddress,
) -> Result<NoteStorage, NoteError> {
let mut elements = Vec::with_capacity(6);
let destination_network = u32::from_le_bytes(destination_network.to_be_bytes());
elements.push(Felt::from(destination_network));
elements.extend(destination_address.to_elements());
NoteStorage::new(elements)
}