I got started with writing smart contracts 2 days ago so please bear with me. The function emit_event
emits an event. I want to call the function via a CPI form another program. I have written code for the CPI as well. When I do anchor test
, I'm getting the error
IdlError: Type not found: {"name":"revent","type":{"defined":"RoosterEvent"}}
I checked the generated IDL and it has the revent
type is present in there.
Following is my code for logger/lib.rs
. This has the exposed function.
use anchor_lang::prelude::*;
use borsh::{BorshDeserialize, BorshSerialize};
declare_id!("ENdMF5CR3qvWj2L6xZWofrYiYaQVV3dM94ghtbrvJ9QN");
#[program]
pub mod logger {
use super::*;
pub fn emit_event(_ctx: Context<SetRoosterEvent>, data: String, label: String) -> Result<()> {
let m_data = data;
let m_label = label;
emit!(RoosterEvent {
data: m_data.to_string(),
label: m_label.to_string(),
});
msg!("HAHA");
msg!(m_data.as_str());
msg!(m_label.as_str());
msg!("HAHA");
Ok(())
}
}
#[derive(Accounts, AnchorDeserialize, AnchorSerialize)]
pub struct SetRoosterEvent<'info> {
#[account(mut)]
pub event: Account<'info, TestEvent>,
}
#[account]
pub struct TestEvent {
pub revent: RoosterEvent,
}
#[event]
#[derive(Clone, Debug, Default)]
pub struct RoosterEvent {
pub data: String,
pub label: String,
}
Following is my consumer/lib.rs
that does the CPI call
use anchor_lang::prelude::*;
use logger::cpi::accounts::SetRoosterEvent;
use logger::program::Logger;
use logger::{self, TestEvent};
declare_id!("5M8M5VCtD3cDkqJJj3NmfgVwnrVj1t9NSpmdSB3XGKR6");
#[program]
pub mod consumer {
use super::*;
pub fn do_something(ctx: Context<DoSomething>) -> Result<()> {
let cpi_program = ctx.accounts.logger_program.to_account_info().clone();
let cpi_accounts = SetRoosterEvent {
event: ctx.accounts.event.to_account_info().clone(),
};
let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
logger::cpi::emit_event(cpi_ctx, "data".to_string(), "label".to_string())?;
Ok(())
}
}
#[derive(Accounts)]
pub struct DoSomething<'info> {
#[account(mut)]
pub event: Account<'info, TestEvent>,
pub logger_program: Program<'info, Logger>,
}
Following is my test file
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Logger } from "../target/types/logger";
import { Consumer } from "../target/types/consumer";
describe("logger", () => {
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);
const program = anchor.workspace.Logger as Program<Logger>;
const consumer = anchor.workspace.Consumer as Program<Consumer>;
it("Does CPI", async()=>{
await consumer.methods.doSomething().rpc();
})
});
Edit: Here's a gist of the code.