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

solana: fix lamport beneficiaries #109

Merged
merged 5 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions solana/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.anchor
.env
.validator_pid
**/*.rs.bk
/artifacts-*
/cfg/**/*.json
Expand Down
5 changes: 5 additions & 0 deletions solana/programs/matching-engine/src/composite/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,11 @@ pub struct ExecuteOrder<'info> {
address = active_auction.info.as_ref().unwrap().initial_offer_token,
)]
pub initial_offer_token: UncheckedAccount<'info>,

/// CHECK: Must be the owner of initial offer token account. If the initial offer token account
/// does not exist anymore, we will attempt to perform this check.
#[account(mut)]
pub initial_participant: UncheckedAccount<'info>,
}

#[derive(Accounts)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub fn handle_execute_fast_order_cctp(
let super::PreparedOrderExecution {
user_amount: amount,
fill,
beneficiary,
} = super::prepare_order_execution(super::PrepareFastExecution {
execute_order: &mut ctx.accounts.execute_order,
custodian: &ctx.accounts.custodian,
Expand Down Expand Up @@ -187,7 +188,7 @@ pub fn handle_execute_fast_order_cctp(
token_program.to_account_info(),
token::CloseAccount {
account: auction_custody_token.to_account_info(),
destination: payer.to_account_info(),
destination: beneficiary.unwrap_or(payer.to_account_info()),
authority: custodian.to_account_info(),
},
&[Custodian::SIGNER_SEEDS],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub fn execute_fast_order_local(ctx: Context<ExecuteFastOrderLocal>) -> Result<(
let super::PreparedOrderExecution {
user_amount: amount,
fill,
beneficiary,
} = super::prepare_order_execution(super::PrepareFastExecution {
execute_order: &mut ctx.accounts.execute_order,
custodian,
Expand Down Expand Up @@ -108,7 +109,7 @@ pub fn execute_fast_order_local(ctx: Context<ExecuteFastOrderLocal>) -> Result<(
token_program.to_account_info(),
token::CloseAccount {
account: auction_custody_token.to_account_info(),
destination: payer.to_account_info(),
destination: beneficiary.unwrap_or(payer.to_account_info()),
authority: custodian.to_account_info(),
},
&[Custodian::SIGNER_SEEDS],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,38 +23,36 @@ struct PrepareFastExecution<'ctx, 'info> {
token_program: &'ctx Program<'info, token::Token>,
}

struct PreparedOrderExecution {
struct PreparedOrderExecution<'info> {
pub user_amount: u64,
pub fill: Fill,
pub beneficiary: Option<AccountInfo<'info>>,
}

fn prepare_order_execution(accounts: PrepareFastExecution) -> Result<PreparedOrderExecution> {
fn prepare_order_execution<'info>(
accounts: PrepareFastExecution<'_, 'info>,
) -> Result<PreparedOrderExecution<'info>> {
let PrepareFastExecution {
execute_order,
custodian,
token_program,
} = accounts;

let ExecuteOrder {
fast_vaa,
active_auction,
executor_token,
initial_offer_token,
} = execute_order;

let ActiveAuction {
auction,
custody_token,
config,
best_offer_token,
} = active_auction;
let auction = &mut execute_order.active_auction.auction;
Copy link
Contributor

Choose a reason for hiding this comment

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

Look at all those references.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

🐔

let fast_vaa = &execute_order.fast_vaa;
let custody_token = &execute_order.active_auction.custody_token;
let config = &execute_order.active_auction.config;
let executor_token = &execute_order.executor_token;
let best_offer_token = &execute_order.active_auction.best_offer_token;
let initial_offer_token = &execute_order.initial_offer_token;
let initial_participant = &execute_order.initial_participant;

let vaa = fast_vaa.load_unchecked();
let order = LiquidityLayerMessage::try_from(vaa.payload())
.unwrap()
.to_fast_market_order_unchecked();

let (user_amount, new_status) = {
let (user_amount, new_status, beneficiary) = {
let auction_info = auction.info.as_ref().unwrap();

let current_slot = Clock::get().unwrap().slot;
Expand Down Expand Up @@ -98,9 +96,25 @@ fn prepare_order_execution(accounts: PrepareFastExecution) -> Result<PreparedOrd
deposit_and_fee = deposit_and_fee.saturating_sub(penalty);
}

let mut beneficiary = None;

// If the initial offer token account doesn't exist anymore, we have nowhere to send the
// init auction fee. The executor will get these funds instead.
if !initial_offer_token.data_is_empty() {
// Deserialize to token account to find owner. We know this is a legitimate token
// account, so it is safe to borrow and unwrap here.
{
let mut acc_data: &[_] = &initial_offer_token.data.borrow();
let token_data = token::TokenAccount::try_deserialize(&mut acc_data).unwrap();
require_keys_eq!(
token_data.owner,
initial_participant.key(),
ErrorCode::ConstraintTokenOwner
);

beneficiary.replace(initial_participant.to_account_info());
}

if best_offer_token.key() != initial_offer_token.key() {
// Pay the auction initiator their fee.
token::transfer(
Expand Down Expand Up @@ -218,6 +232,7 @@ fn prepare_order_execution(accounts: PrepareFastExecution) -> Result<PreparedOrd
slot: current_slot,
execute_penalty: if penalized { Some(penalty) } else { None },
},
beneficiary,
)
};

Expand All @@ -235,5 +250,6 @@ fn prepare_order_execution(accounts: PrepareFastExecution) -> Result<PreparedOrd
.try_into()
.map_err(|_| MatchingEngineError::RedeemerMessageTooLarge)?,
},
beneficiary,
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ fn handle_settle_auction_none_cctp(
ctx: Context<SettleAuctionNoneCctp>,
destination_cctp_domain: u32,
) -> Result<()> {
let prepared_by = &ctx.accounts.prepared.by;
let prepared_custody_token = &ctx.accounts.prepared.custody_token;
let custodian = &ctx.accounts.custodian;
let token_program = &ctx.accounts.token_program;
Expand Down Expand Up @@ -206,7 +207,7 @@ fn handle_settle_auction_none_cctp(
token_program.to_account_info(),
token::CloseAccount {
account: prepared_custody_token.to_account_info(),
destination: payer.to_account_info(),
destination: prepared_by.to_account_info(),
authority: custodian.to_account_info(),
},
&[Custodian::SIGNER_SEEDS],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub struct SettleAuctionNoneLocal<'info> {
}

pub fn settle_auction_none_local(ctx: Context<SettleAuctionNoneLocal>) -> Result<()> {
let prepared_by = &ctx.accounts.prepared.by;
let prepared_custody_token = &ctx.accounts.prepared.custody_token;
let custodian = &ctx.accounts.custodian;
let token_program = &ctx.accounts.token_program;
Expand Down Expand Up @@ -124,7 +125,7 @@ pub fn settle_auction_none_local(ctx: Context<SettleAuctionNoneLocal>) -> Result
token_program.to_account_info(),
token::CloseAccount {
account: prepared_custody_token.to_account_info(),
destination: payer.to_account_info(),
destination: prepared_by.to_account_info(),
authority: custodian.to_account_info(),
},
&[Custodian::SIGNER_SEEDS],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ fn handle_place_market_order_cctp(
token_program.to_account_info(),
token::CloseAccount {
account: prepared_custody_token.to_account_info(),
destination: payer.to_account_info(),
destination: ctx.accounts.prepared_by.to_account_info(),
authority: custodian.to_account_info(),
},
&[Custodian::SIGNER_SEEDS],
Expand Down
14 changes: 14 additions & 0 deletions solana/target/idl/matching_engine.json
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,13 @@
{
"name": "initial_offer_token",
"writable": true
},
{
"name": "initial_participant",
"docs": [
"does not exist anymore, we will attempt to perform this check."
],
"writable": true
}
]
},
Expand Down Expand Up @@ -831,6 +838,13 @@
{
"name": "initial_offer_token",
"writable": true
},
{
"name": "initial_participant",
"docs": [
"does not exist anymore, we will attempt to perform this check."
],
"writable": true
}
]
},
Expand Down
14 changes: 14 additions & 0 deletions solana/target/types/matching_engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,13 @@ export type MatchingEngine = {
{
"name": "initialOfferToken",
"writable": true
},
{
"name": "initialParticipant",
"docs": [
"does not exist anymore, we will attempt to perform this check."
],
"writable": true
}
]
},
Expand Down Expand Up @@ -837,6 +844,13 @@ export type MatchingEngine = {
{
"name": "initialOfferToken",
"writable": true
},
{
"name": "initialParticipant",
"docs": [
"does not exist anymore, we will attempt to perform this check."
],
"writable": true
}
]
},
Expand Down
29 changes: 24 additions & 5 deletions solana/ts/src/matchingEngine/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1704,26 +1704,29 @@ export class MatchingEngineProgram {
auctionConfig?: PublicKey;
bestOfferToken?: PublicKey;
initialOfferToken?: PublicKey;
initialParticipant?: PublicKey;
},
opts: {
targetChain?: wormholeSdk.ChainId;
} = {},
) {
const connection = this.program.provider.connection;

const { payer, fastVaa, auctionConfig, bestOfferToken } = accounts;

let { auction, executorToken, initialOfferToken } = accounts;
let { auction, executorToken, initialOfferToken, initialParticipant } = accounts;
let { targetChain } = opts;

executorToken ??= splToken.getAssociatedTokenAddressSync(this.mint, payer);

let fastVaaAccount: VaaAccount | undefined;
if (auction === undefined) {
fastVaaAccount = await VaaAccount.fetch(this.program.provider.connection, fastVaa);
fastVaaAccount = await VaaAccount.fetch(connection, fastVaa);
auction = this.auctionAddress(fastVaaAccount.digest());
}

if (targetChain === undefined) {
fastVaaAccount ??= await VaaAccount.fetch(this.program.provider.connection, fastVaa);
fastVaaAccount ??= await VaaAccount.fetch(connection, fastVaa);

const { fastMarketOrder } = LiquidityLayerMessage.decode(fastVaaAccount.payload());
if (fastMarketOrder === undefined) {
Expand All @@ -1742,6 +1745,11 @@ export class MatchingEngineProgram {
initialOfferToken = info.initialOfferToken;
}

if (initialParticipant === undefined) {
const token = await splToken.getAccount(connection, initialOfferToken);
initialParticipant = token.owner;
}

const {
custodian,
routerEndpoint: toRouterEndpoint,
Expand Down Expand Up @@ -1781,6 +1789,7 @@ export class MatchingEngineProgram {
),
executorToken,
initialOfferToken,
initialParticipant,
},
toRouterEndpoint: this.routerEndpointComposite(toRouterEndpoint),
custodian: this.checkedCustodianComposite(custodian),
Expand Down Expand Up @@ -1818,21 +1827,25 @@ export class MatchingEngineProgram {
auctionConfig?: PublicKey;
bestOfferToken?: PublicKey;
initialOfferToken?: PublicKey;
initialParticipant?: PublicKey;
toRouterEndpoint?: PublicKey;
},
opts: {
sourceChain?: wormholeSdk.ChainId;
} = {},
) {
const connection = this.program.provider.connection;

const { payer, fastVaa, auctionConfig, bestOfferToken } = accounts;

let { auction, executorToken, toRouterEndpoint, initialOfferToken } = accounts;
let { auction, executorToken, toRouterEndpoint, initialOfferToken, initialParticipant } =
accounts;
let { sourceChain } = opts;
executorToken ??= splToken.getAssociatedTokenAddressSync(this.mint, payer);
toRouterEndpoint ??= this.routerEndpointAddress(wormholeSdk.CHAIN_ID_SOLANA);

if (auction === undefined) {
const vaaAccount = await VaaAccount.fetch(this.program.provider.connection, fastVaa);
const vaaAccount = await VaaAccount.fetch(connection, fastVaa);
auction = this.auctionAddress(vaaAccount.digest());
}

Expand All @@ -1852,6 +1865,11 @@ export class MatchingEngineProgram {
initialOfferToken ??= auctionInfo.initialOfferToken;
}

if (initialParticipant === undefined) {
const token = await splToken.getAccount(connection, initialOfferToken);
initialParticipant = token.owner;
}

const {
custodian,
coreMessage,
Expand Down Expand Up @@ -1879,6 +1897,7 @@ export class MatchingEngineProgram {
),
executorToken,
initialOfferToken,
initialParticipant,
},
toRouterEndpoint: this.routerEndpointComposite(toRouterEndpoint),
wormhole: {
Expand Down
1 change: 1 addition & 0 deletions solana/ts/tests/01__matchingEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2544,6 +2544,7 @@ describe("Matching Engine", function () {
const ix = await engine.executeFastOrderCctpIx({
payer: liquidator.publicKey,
fastVaa,
initialParticipant: payer.publicKey,
});

const computeIx = ComputeBudgetProgram.setComputeUnitLimit({
Expand Down