Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: token bridge cpi event #695

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions programs/svm-spoke/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,9 @@ pub struct ClaimedRelayerRefund {
pub struct EmergencyDeletedRootBundle {
pub root_bundle_id: u32,
}

#[event]
pub struct BridgedToHubPool {
pub amount: u64,
pub mint: Pubkey,
}
18 changes: 12 additions & 6 deletions programs/svm-spoke/src/instructions/token_bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use anchor_spl::token_interface::{Mint, TokenAccount, TokenInterface};

use crate::{
error::CustomError,
event::BridgedToHubPool,
message_transmitter::program::MessageTransmitter,
token_messenger_minter::{
self, cpi::accounts::DepositForBurn, program::TokenMessengerMinter,
Expand All @@ -11,7 +12,8 @@ use crate::{
State, TransferLiability,
};

#[derive(Accounts)]
#[event_cpi]
#[derive(Accounts, Clone)]
pub struct BridgeTokensToHubPool<'info> {
pub signer: Signer<'info>,

Expand Down Expand Up @@ -61,7 +63,7 @@ pub struct BridgeTokensToHubPool<'info> {

/// CHECK: EventAuthority is checked in CCTP. Seeds must be \["__event_authority"\] (CCTP Token Messenger Minter
/// program).
pub event_authority: UncheckedAccount<'info>,
pub cctp_event_authority: UncheckedAccount<'info>,

#[account(mut)]
pub message_sent_event_data: Signer<'info>,
Expand All @@ -79,7 +81,7 @@ impl<'info> BridgeTokensToHubPool<'info> {
pub fn bridge_tokens_to_hub_pool(
&mut self,
amount: u64,
bumps: &BridgeTokensToHubPoolBumps,
ctx: Context<BridgeTokensToHubPool<'info>>,
) -> Result<()> {
if amount > self.transfer_liability.pending_to_hub_pool {
return err!(CustomError::ExceededPendingBridgeAmount);
Expand All @@ -106,11 +108,12 @@ impl<'info> BridgeTokensToHubPool<'info> {
token_messenger_minter_program: self.token_messenger_minter_program.to_account_info(),
token_program: self.token_program.to_account_info(),
system_program: self.system_program.to_account_info(),
event_authority: self.event_authority.to_account_info(),
event_authority: self.cctp_event_authority.to_account_info(),
program: self.token_messenger_minter_program.to_account_info(),
};
let state_seed_bytes = self.state.seed.to_le_bytes();
let state_seeds: &[&[&[u8]]] = &[&[b"state", state_seed_bytes.as_ref(), &[bumps.state]]];
let state_seeds: &[&[&[u8]]] =
&[&[b"state", state_seed_bytes.as_ref(), &[ctx.bumps.state]]];
let cpi_ctx = CpiContext::new_with_signer(cpi_program, cpi_accounts, state_seeds);
let params = DepositForBurnParams {
amount,
Expand All @@ -119,7 +122,10 @@ impl<'info> BridgeTokensToHubPool<'info> {
};
token_messenger_minter::cpi::deposit_for_burn(cpi_ctx, params)?;

// TODO: emit event on bridged tokens.
emit_cpi!(BridgedToHubPool {
amount,
mint: self.mint.key()
});

Ok(())
}
Expand Down
13 changes: 10 additions & 3 deletions programs/svm-spoke/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,18 @@ pub mod svm_spoke {
proof,
)
}
pub fn bridge_tokens_to_hub_pool(
ctx: Context<BridgeTokensToHubPool>,
pub fn bridge_tokens_to_hub_pool<'info>(
ctx: Context<'_, '_, '_, 'info, BridgeTokensToHubPool<'info>>,
amount: u64,
) -> Result<()> {
ctx.accounts.bridge_tokens_to_hub_pool(amount, &ctx.bumps)?;
let context = Context {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Workaround to be able to pass the context required by emit_cpi!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be more consistent with other instructions to use free functions and pass ctx as parameter.

program_id: ctx.program_id,
accounts: &mut ctx.accounts.clone(),
remaining_accounts: ctx.remaining_accounts,
bumps: ctx.bumps,
};

ctx.accounts.bridge_tokens_to_hub_pool(amount, context)?;

Ok(())
}
Expand Down
32 changes: 31 additions & 1 deletion test/svm/SvmSpoke.TokenBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
relayerRefundHashFn,
findProgramAddress,
loadExecuteRelayerRefundLeafParams,
readProgramEvents,
} from "./utils";
import { assert } from "chai";
import { decodeMessageSentData } from "./cctpHelpers";
Expand Down Expand Up @@ -129,7 +130,7 @@ describe("svm_spoke.token_bridge", () => {
tokenMessengerMinterProgram: tokenMessengerMinterProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
systemProgram: web3.SystemProgram.programId,
eventAuthority,
cctpEventAuthority: eventAuthority,
};
});

Expand Down Expand Up @@ -301,4 +302,33 @@ describe("svm_spoke.token_bridge", () => {
);
}
});

it("Test BridgedToHubPool event", async () => {
const simpleBridgeAmount = 500_000;

// Initialize the bridge with a specific amount.
await initializeBridgeToHubPool(simpleBridgeAmount);

const initialVaultBalance = (await connection.getTokenAccountBalance(vault)).value.amount;
assert.strictEqual(initialVaultBalance, initialMintAmount.toString());

// Create a new Keypair for the message event data.
const simpleBridgeMessageSentEventData = web3.Keypair.generate();

// Perform the bridge operation.
await program.methods
.bridgeTokensToHubPool(new BN(simpleBridgeAmount))
.accounts({ ...bridgeTokensToHubPoolAccounts, messageSentEventData: simpleBridgeMessageSentEventData.publicKey })
.signers([simpleBridgeMessageSentEventData])
.rpc();

// Wait for the event to be emitted.
await new Promise((resolve) => setTimeout(resolve, 500));

const events = await readProgramEvents(connection, program);
const event = events.find((event) => event.name === "bridgedToHubPool").data;
assert.isNotNull(event, "BridgedToHubPool event should be emitted");
assert.strictEqual(event.amount.toString(), simpleBridgeAmount.toString(), "Invalid amount");
assert.strictEqual(event.mint.toString(), mint.toString(), "Invalid mint");
});
});
Loading