v0.1.0-pre.017

This commit is contained in:
2026-07-24 19:10:22 +02:00
parent 252fe51e34
commit 3e1d034633
1656 changed files with 315 additions and 198763 deletions

View File

@@ -0,0 +1,489 @@
// file: kb-lib/src/executor/spl/associated_token_account/builder.rs
// version: 4
//! Official ATA builders and conservative simulation-first plan validation.
macro_rules! parse_key {
($value:expr, $field:expr) => {
match $value.0.parse() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_pubkey_invalid",
format!("invalid ATA {} public key: {error}", $field),
));
},
}
};
}
pub(crate) fn executor_spl_ata_build_prepared_plan(
intent: &crate::ExSplAssociatedTokenAccountExecutionIntent,
) -> kb_core::Result<crate::ExApiPreparedExecutionPlan> {
if intent.intent_id.trim().is_empty() {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_intent_id_empty",
"ATA execution intent id must not be empty",
));
}
match validate_policy(intent) {
std::result::Result::Ok(()) => {},
std::result::Result::Err(error) => return std::result::Result::Err(error),
}
let fee_payer = parse_key!(&intent.fee_payer, "fee_payer");
let token_program_text = intent.operation.token_program().program_id();
let instruction = match &intent.operation {
crate::ExSplAssociatedTokenAccountOperation::Create {
wallet_owner,
mint,
token_program: _,
} => {
let wallet_owner = parse_key!(wallet_owner, "wallet_owner");
let mint = parse_key!(mint, "mint");
let token_program: solana_pubkey::Pubkey = match token_program_text.parse() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_token_program_invalid",
error.to_string(),
));
},
};
spl_associated_token_account_interface::instruction::create_associated_token_account(
&fee_payer,
&wallet_owner,
&mint,
&token_program,
)
},
crate::ExSplAssociatedTokenAccountOperation::CreateIdempotent {
wallet_owner,
mint,
token_program: _,
} => {
let wallet_owner = parse_key!(wallet_owner, "wallet_owner");
let mint = parse_key!(mint, "mint");
let token_program: solana_pubkey::Pubkey = match token_program_text.parse() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_token_program_invalid",
error.to_string(),
));
},
};
spl_associated_token_account_interface::instruction::create_associated_token_account_idempotent(
&fee_payer,
&wallet_owner,
&mint,
&token_program,
)
},
crate::ExSplAssociatedTokenAccountOperation::RecoverNested {
wallet_owner,
owner_mint,
nested_mint,
token_program: _,
} => {
let wallet_owner = parse_key!(wallet_owner, "wallet_owner");
let owner_mint = parse_key!(owner_mint, "owner_mint");
let nested_mint = parse_key!(nested_mint, "nested_mint");
let token_program: solana_pubkey::Pubkey = match token_program_text.parse() {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_token_program_invalid",
error.to_string(),
));
},
};
spl_associated_token_account_interface::instruction::recover_nested(
&wallet_owner,
&owner_mint,
&nested_mint,
&token_program,
)
},
};
let planned_instruction = planned_instruction(intent.operation.operation_code(), &instruction);
let required_signers = required_signers(&intent.fee_payer, &planned_instruction.accounts);
tracing::debug!(
target: crate::EX_SPL_ATA_TRACING_TARGET,
action = "build_prepared_plan",
intent_id = %intent.intent_id,
operation_code = intent.operation.operation_code(),
token_program_id = token_program_text,
account_occurrence_count = planned_instruction.accounts.len(),
required_signer_count = required_signers.len(),
max_rent_lamports = intent.max_rent_lamports,
dry_run = intent.policy.dry_run,
"built SPL Associated Token Account execution plan"
);
return std::result::Result::Ok(crate::ExApiPreparedExecutionPlan {
executor_name: "kb_executor_spl_associated_token_account".to_string(),
executor_version: env!("CARGO_PKG_VERSION").to_string(),
intent_id: intent.intent_id.clone(),
operation_code: intent.operation.operation_code().to_string(),
fee_payer: crate::MdPubkey(fee_payer.to_string()),
instructions: std::vec![planned_instruction],
required_signers,
policy: intent.policy.clone(),
requested_spend_lamports: intent.max_rent_lamports,
requested_compute_unit_price_micro_lamports: std::option::Option::None,
});
}
fn validate_policy(
intent: &crate::ExSplAssociatedTokenAccountExecutionIntent,
) -> kb_core::Result<()> {
if intent.policy.simulation != crate::ExApiExecutionSimulationPolicy::Required {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_simulation_required",
"ATA execution requires simulation before signing or sending",
));
}
if intent.operation.is_creation() && intent.max_rent_lamports == 0 {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_rent_limit_missing",
"ATA creation requires a positive rent spending ceiling",
));
}
if !intent.operation.is_creation() && intent.max_rent_lamports != 0 {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_recovery_rent_must_be_zero",
"RecoverNested must declare zero rent spending",
));
}
if intent.policy.cost_limit.max_spend_lamports
!= std::option::Option::Some(intent.max_rent_lamports)
{
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_spend_limit_mismatch",
"ATA policy max spend must equal the declared maximum rent lamports",
));
}
match intent.policy.cost_limit.max_fee_lamports {
std::option::Option::Some(value) if value > 0 => {},
std::option::Option::Some(_) | std::option::Option::None => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_fee_limit_missing",
"ATA execution requires a positive transaction fee ceiling",
));
},
}
let validation = &intent.policy.post_execution_validation;
if !validation.canonical_insert_required
|| !validation.core_extraction_required
|| !validation.decode_replay_required
|| !validation.materialization_required
{
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_post_validation_required",
"ATA execution requires canonical insertion, core extraction, decode replay and materialization validation",
));
}
return std::result::Result::Ok(());
}
fn planned_instruction(
operation_code: &str,
instruction: &solana_instruction::Instruction,
) -> crate::ExApiPlannedInstruction {
return crate::ExApiPlannedInstruction {
program_id: crate::MdProgramId(instruction.program_id.to_string()),
operation_code: operation_code.to_string(),
accounts: instruction
.accounts
.iter()
.map(|account| {
return crate::ExApiPlannedAccount {
pubkey: crate::MdPubkey(account.pubkey.to_string()),
is_signer: account.is_signer,
is_writable: account.is_writable,
};
})
.collect(),
data: instruction.data.clone(),
};
}
fn required_signers(
fee_payer: &crate::MdPubkey,
accounts: &[crate::ExApiPlannedAccount],
) -> std::vec::Vec<crate::ExApiRequiredSigner> {
let mut required = std::vec![crate::ExApiRequiredSigner {
pubkey: fee_payer.clone(),
role: "fee_payer".to_string(),
}];
for account in accounts.iter().filter(|account| return account.is_signer) {
if required.iter().any(|candidate| return candidate.pubkey == account.pubkey) {
continue;
}
required.push(crate::ExApiRequiredSigner {
pubkey: account.pubkey.clone(),
role: "wallet_owner".to_string(),
});
}
return required;
}
#[cfg(test)]
pub(crate) mod tests {
fn pubkey(value: &str) -> crate::MdPubkey {
return crate::MdPubkey(value.to_string());
}
fn intent(
operation: crate::ExSplAssociatedTokenAccountOperation,
max_rent_lamports: u64,
) -> crate::ExSplAssociatedTokenAccountExecutionIntent {
let fee_payer = pubkey(kb_program_ids::SYSTEM_PROGRAM_ID);
let wallet_owner = match &operation {
crate::ExSplAssociatedTokenAccountOperation::Create { wallet_owner, .. }
| crate::ExSplAssociatedTokenAccountOperation::CreateIdempotent {
wallet_owner, ..
}
| crate::ExSplAssociatedTokenAccountOperation::RecoverNested { wallet_owner, .. } => {
wallet_owner.clone()
},
};
let mut authorized_signers = std::vec![fee_payer.clone()];
if !authorized_signers.contains(&wallet_owner) {
authorized_signers.push(wallet_owner);
}
return crate::ExSplAssociatedTokenAccountExecutionIntent {
intent_id: "ata-intent-1".to_string(),
fee_payer,
max_rent_lamports,
policy: crate::ExApiExecutionPolicy {
simulation: crate::ExApiExecutionSimulationPolicy::Required,
cost_limit: crate::ExApiExecutionCostLimit {
max_spend_lamports: std::option::Option::Some(max_rent_lamports),
max_fee_lamports: std::option::Option::Some(10_000),
max_compute_unit_price_micro_lamports: std::option::Option::None,
},
authorized_signers,
dry_run: true,
post_execution_validation: crate::ExApiPostExecutionValidationPolicy {
canonical_insert_required: true,
core_extraction_required: true,
decode_replay_required: true,
materialization_required: true,
},
..crate::ExApiExecutionPolicy::default()
},
operation,
};
}
fn official_instruction(
intent: &crate::ExSplAssociatedTokenAccountExecutionIntent,
) -> solana_instruction::Instruction {
let fee_payer = intent
.fee_payer
.0
.parse()
.unwrap_or_else(|error| panic!("invalid fee payer fixture: {error}"));
let token_program = intent
.operation
.token_program()
.program_id()
.parse()
.unwrap_or_else(|error| panic!("invalid Token Program fixture: {error}"));
return match &intent.operation {
crate::ExSplAssociatedTokenAccountOperation::Create {
wallet_owner,
mint,
token_program: _,
} => {
let wallet_owner = wallet_owner
.0
.parse()
.unwrap_or_else(|error| panic!("invalid wallet fixture: {error}"));
let mint =
mint.0.parse().unwrap_or_else(|error| panic!("invalid mint fixture: {error}"));
spl_associated_token_account_interface::instruction::create_associated_token_account(
&fee_payer,
&wallet_owner,
&mint,
&token_program,
)
},
crate::ExSplAssociatedTokenAccountOperation::CreateIdempotent {
wallet_owner,
mint,
token_program: _,
} => {
let wallet_owner = wallet_owner
.0
.parse()
.unwrap_or_else(|error| panic!("invalid wallet fixture: {error}"));
let mint =
mint.0.parse().unwrap_or_else(|error| panic!("invalid mint fixture: {error}"));
spl_associated_token_account_interface::instruction::create_associated_token_account_idempotent(
&fee_payer,
&wallet_owner,
&mint,
&token_program,
)
},
crate::ExSplAssociatedTokenAccountOperation::RecoverNested {
wallet_owner,
owner_mint,
nested_mint,
token_program: _,
} => {
let wallet_owner = wallet_owner
.0
.parse()
.unwrap_or_else(|error| panic!("invalid wallet fixture: {error}"));
let owner_mint = owner_mint
.0
.parse()
.unwrap_or_else(|error| panic!("invalid owner mint fixture: {error}"));
let nested_mint = nested_mint
.0
.parse()
.unwrap_or_else(|error| panic!("invalid nested mint fixture: {error}"));
spl_associated_token_account_interface::instruction::recover_nested(
&wallet_owner,
&owner_mint,
&nested_mint,
&token_program,
)
},
};
}
fn assert_matches_official(intent: &crate::ExSplAssociatedTokenAccountExecutionIntent) {
let plan = crate::ExApiTypedInstructionExecutor::build_prepared_plan(
&crate::ExSplAssociatedTokenAccountExecutor,
intent,
)
.unwrap_or_else(|error| panic!("ATA plan failed: {error}"));
let official = official_instruction(intent);
assert_eq!(plan.instructions.len(), 1);
let actual = &plan.instructions[0];
assert_eq!(actual.program_id.0, official.program_id.to_string());
assert_eq!(actual.data, official.data);
assert_eq!(actual.accounts.len(), official.accounts.len());
for (actual_account, official_account) in
actual.accounts.iter().zip(official.accounts.iter())
{
assert_eq!(actual_account.pubkey.0, official_account.pubkey.to_string());
assert_eq!(actual_account.is_signer, official_account.is_signer);
assert_eq!(actual_account.is_writable, official_account.is_writable);
}
assert_eq!(plan.requested_spend_lamports, intent.max_rent_lamports);
assert_eq!(plan.policy.simulation, crate::ExApiExecutionSimulationPolicy::Required);
assert!(plan.policy.dry_run);
}
#[test]
fn every_variant_and_token_program_matches_the_official_builder() {
for token_program in [
crate::ExSplAssociatedTokenProgram::Classic,
crate::ExSplAssociatedTokenProgram::Token2022,
] {
for operation in [
crate::ExSplAssociatedTokenAccountOperation::Create {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
token_program,
},
crate::ExSplAssociatedTokenAccountOperation::CreateIdempotent {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
token_program,
},
] {
let intent = intent(operation, 2_100_000);
assert_matches_official(&intent);
}
let recovery = intent(
crate::ExSplAssociatedTokenAccountOperation::RecoverNested {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
owner_mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
nested_mint: pubkey(kb_program_ids::CONFIG_PROGRAM_ID),
token_program,
},
0,
);
assert_matches_official(&recovery);
}
}
#[test]
fn signer_set_is_unique_without_reordering_instruction_metas() {
let intent = intent(
crate::ExSplAssociatedTokenAccountOperation::RecoverNested {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
owner_mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
nested_mint: pubkey(kb_program_ids::CONFIG_PROGRAM_ID),
token_program: crate::ExSplAssociatedTokenProgram::Classic,
},
0,
);
let plan = crate::executor_spl_ata_build_prepared_plan(&intent)
.unwrap_or_else(|error| panic!("ATA recovery plan failed: {error}"));
assert_eq!(plan.required_signers.len(), 2);
assert_eq!(plan.required_signers[0].role, "fee_payer");
assert_eq!(plan.required_signers[1].role, "wallet_owner");
assert_eq!(plan.instructions[0].accounts[5].pubkey, plan.required_signers[1].pubkey);
assert!(plan.instructions[0].accounts[5].is_signer);
}
#[test]
fn conservative_policy_rejects_unsafe_cost_and_replay_shapes() {
let operation = crate::ExSplAssociatedTokenAccountOperation::Create {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
token_program: crate::ExSplAssociatedTokenProgram::Classic,
};
let mut intent = intent(operation, 2_100_000);
intent.policy.simulation = crate::ExApiExecutionSimulationPolicy::Optional;
let error = crate::executor_spl_ata_build_prepared_plan(&intent)
.expect_err("optional simulation must fail");
assert_eq!(error.code(), "execution_spl_ata_simulation_required");
intent.policy.simulation = crate::ExApiExecutionSimulationPolicy::Required;
intent.policy.cost_limit.max_spend_lamports = std::option::Option::Some(1);
let error = crate::executor_spl_ata_build_prepared_plan(&intent)
.expect_err("mismatched spend ceiling must fail");
assert_eq!(error.code(), "execution_spl_ata_spend_limit_mismatch");
intent.policy.cost_limit.max_spend_lamports = std::option::Option::Some(2_100_000);
intent.policy.post_execution_validation.materialization_required = false;
let error = crate::executor_spl_ata_build_prepared_plan(&intent)
.expect_err("incomplete replay validation must fail");
assert_eq!(error.code(), "execution_spl_ata_post_validation_required");
}
#[test]
fn recovery_requires_zero_rent_and_creation_requires_a_positive_ceiling() {
let create = intent(
crate::ExSplAssociatedTokenAccountOperation::Create {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
token_program: crate::ExSplAssociatedTokenProgram::Classic,
},
0,
);
let error = crate::executor_spl_ata_build_prepared_plan(&create)
.expect_err("zero creation ceiling must fail");
assert_eq!(error.code(), "execution_spl_ata_rent_limit_missing");
let recovery = intent(
crate::ExSplAssociatedTokenAccountOperation::RecoverNested {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
owner_mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
nested_mint: pubkey(kb_program_ids::CONFIG_PROGRAM_ID),
token_program: crate::ExSplAssociatedTokenProgram::Token2022,
},
1,
);
let error = crate::executor_spl_ata_build_prepared_plan(&recovery)
.expect_err("recovery rent spending must fail");
assert_eq!(error.code(), "execution_spl_ata_recovery_rent_must_be_zero");
}
}

View File

@@ -0,0 +1,7 @@
// file: kb-lib/src/executor/spl/associated_token_account/constants.rs
// version: 3
//! Local constants for the `kb_executor_spl_associated_token_account` crate. Program identifiers live in `kb_program_ids`.
/// Canonical tracing target for this crate.
pub(crate) const EX_SPL_ATA_TRACING_TARGET: &str = "kb-lib.executor.spl.associated_token_account";

View File

@@ -0,0 +1,282 @@
// file: kb-lib/src/executor/spl/associated_token_account/executor.rs
// version: 4
//! Exact ATA capability dispatch and typed plan construction.
/// SPL Associated Token Account executor implementation.
#[derive(Clone, Debug, Default)]
pub struct ExSplAssociatedTokenAccountExecutor;
impl crate::ExSplAssociatedTokenAccountExecutor {
fn exact_capability(
&self,
program_id: &crate::MdProgramId,
operation_code: &str,
) -> crate::ExApiExecutionCapability {
if program_id.0 != kb_program_ids::ASSOCIATED_TOKEN_PROGRAM_ID {
return crate::ExApiExecutionCapability::unsupported(
"execution_spl_ata_program_not_owned",
format!(
"program {} is not owned by kb_executor_spl_associated_token_account",
program_id.0
),
);
}
if crate::EX_SPL_ATA_SUPPORTED_OPERATION_CODES.contains(&operation_code) {
return crate::ExApiExecutionCapability::supported(operation_code);
}
return crate::ExApiExecutionCapability::unsupported(
"execution_spl_ata_operation_unsupported",
format!("SPL Associated Token Account operation {operation_code} is not implemented"),
);
}
}
impl crate::ExApiTypedInstructionExecutor for crate::ExSplAssociatedTokenAccountExecutor {
type Intent = crate::ExSplAssociatedTokenAccountExecutionIntent;
fn capability(
&self,
program_id: &crate::MdProgramId,
operation_code: &str,
) -> crate::ExApiExecutionCapability {
return self.exact_capability(program_id, operation_code);
}
fn build_prepared_plan(
&self,
intent: &Self::Intent,
) -> kb_core::Result<crate::ExApiPreparedExecutionPlan> {
let program_id = crate::MdProgramId(std::string::String::from(
kb_program_ids::ASSOCIATED_TOKEN_PROGRAM_ID,
));
return match self.exact_capability(&program_id, intent.operation.operation_code()) {
crate::ExApiExecutionCapability::Supported { operation_code: _ } => {
crate::executor_spl_ata_build_prepared_plan(intent)
},
crate::ExApiExecutionCapability::Unsupported { reason_code, reason } => {
std::result::Result::Err(kb_core::Error::new(reason_code, reason))
},
};
}
}
impl crate::ExApiInstructionExecutor for crate::ExSplAssociatedTokenAccountExecutor {
fn executor_name(&self) -> &'static str {
return "kb_executor_spl_associated_token_account";
}
fn executor_version(&self) -> &'static str {
return env!("CARGO_PKG_VERSION");
}
fn program_ids(&self) -> &'static [&'static str] {
return &[kb_program_ids::ASSOCIATED_TOKEN_PROGRAM_ID];
}
fn supports_request(
&self,
request: &crate::ExApiExecutionRequest,
) -> crate::ExApiExecutionSupport {
return match self.exact_capability(&request.program_id, &request.operation_code) {
crate::ExApiExecutionCapability::Supported { operation_code: _ } => {
crate::ExApiExecutionSupport::Yes
},
crate::ExApiExecutionCapability::Unsupported { reason_code: _, reason: _ } => {
crate::ExApiExecutionSupport::No
},
};
}
fn build_plan(
&self,
request: &crate::ExApiExecutionRequest,
) -> kb_core::Result<crate::ExApiExecutionPlan> {
match self.exact_capability(&request.program_id, &request.operation_code) {
crate::ExApiExecutionCapability::Supported { operation_code: _ } => {},
crate::ExApiExecutionCapability::Unsupported { reason_code, reason } => {
return std::result::Result::Err(kb_core::Error::new(reason_code, reason));
},
}
let intent = match serde_json::from_str::<crate::ExSplAssociatedTokenAccountExecutionIntent>(
&request.payload_json,
) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_intent_deserialize_failed",
error.to_string(),
));
},
};
if intent.operation.operation_code() != request.operation_code.as_str() {
return std::result::Result::Err(kb_core::Error::new(
"execution_operation_code_mismatch",
format!(
"request operation {} does not match typed intent operation {}",
request.operation_code,
intent.operation.operation_code()
),
));
}
let prepared =
match crate::ExApiTypedInstructionExecutor::build_prepared_plan(self, &intent) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let payload_value = match serde_json::to_value(&prepared) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_ata_plan_serialize_failed",
error.to_string(),
));
},
};
let payload_json = match crate::executor_api_serialize_payload_json(&payload_value) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
return std::result::Result::Ok(crate::ExApiExecutionPlan {
executor_name: std::string::String::from("kb_executor_spl_associated_token_account"),
instruction_count: prepared.instructions.len(),
payload_json,
});
}
}
#[cfg(test)]
mod tests {
fn pubkey(value: &str) -> crate::MdPubkey {
return crate::MdPubkey(value.to_string());
}
fn intent(
operation: crate::ExSplAssociatedTokenAccountOperation,
max_rent_lamports: u64,
) -> crate::ExSplAssociatedTokenAccountExecutionIntent {
let fee_payer = pubkey(kb_program_ids::SYSTEM_PROGRAM_ID);
let wallet_owner = match &operation {
crate::ExSplAssociatedTokenAccountOperation::Create { wallet_owner, .. }
| crate::ExSplAssociatedTokenAccountOperation::CreateIdempotent {
wallet_owner, ..
}
| crate::ExSplAssociatedTokenAccountOperation::RecoverNested { wallet_owner, .. } => {
wallet_owner.clone()
},
};
let mut authorized_signers = std::vec![fee_payer.clone()];
if !authorized_signers.contains(&wallet_owner) {
authorized_signers.push(wallet_owner);
}
return crate::ExSplAssociatedTokenAccountExecutionIntent {
intent_id: "ata-intent-1".to_string(),
fee_payer,
max_rent_lamports,
policy: crate::ExApiExecutionPolicy {
simulation: crate::ExApiExecutionSimulationPolicy::Required,
cost_limit: crate::ExApiExecutionCostLimit {
max_spend_lamports: std::option::Option::Some(max_rent_lamports),
max_fee_lamports: std::option::Option::Some(10_000),
max_compute_unit_price_micro_lamports: std::option::Option::None,
},
authorized_signers,
dry_run: true,
post_execution_validation: crate::ExApiPostExecutionValidationPolicy {
canonical_insert_required: true,
core_extraction_required: true,
decode_replay_required: true,
materialization_required: true,
},
..crate::ExApiExecutionPolicy::default()
},
operation,
};
}
fn request(program_id: &str, operation_code: &str) -> crate::ExApiExecutionRequest {
return crate::ExApiExecutionRequest {
program_id: crate::MdProgramId(program_id.to_string()),
operation_code: operation_code.to_string(),
payload_json: std::string::String::from("{}"),
};
}
#[test]
fn exact_capabilities_cover_every_published_current_variant() {
let executor = crate::ExSplAssociatedTokenAccountExecutor;
for operation_code in crate::EX_SPL_ATA_SUPPORTED_OPERATION_CODES {
let request = request(kb_program_ids::ASSOCIATED_TOKEN_PROGRAM_ID, operation_code);
assert_eq!(
crate::ExApiInstructionExecutor::supports_request(&executor, &request),
crate::ExApiExecutionSupport::Yes
);
}
for (program_id, operation_code) in [
(kb_program_ids::SYSTEM_PROGRAM_ID, crate::EX_SPL_ATA_CREATE_OPERATION),
(
kb_program_ids::ASSOCIATED_TOKEN_PROGRAM_ID,
"spl_associated_token_account.close",
),
] {
let request = request(program_id, operation_code);
assert_eq!(
crate::ExApiInstructionExecutor::supports_request(&executor, &request),
crate::ExApiExecutionSupport::No
);
}
}
#[test]
fn generic_request_roundtrips_one_typed_instruction() {
let pintent = intent(
crate::ExSplAssociatedTokenAccountOperation::CreateIdempotent {
wallet_owner: pubkey(kb_program_ids::STAKE_PROGRAM_ID),
mint: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
token_program: crate::ExSplAssociatedTokenProgram::Token2022,
},
2_100_000,
);
let payload_json = serde_json::to_string(&pintent)
.unwrap_or_else(|error| panic!("ATA intent serialization failed: {error}"));
let request = crate::ExApiExecutionRequest {
program_id: crate::MdProgramId(kb_program_ids::ASSOCIATED_TOKEN_PROGRAM_ID.to_string()),
operation_code: crate::EX_SPL_ATA_CREATE_IDEMPOTENT_OPERATION.to_string(),
payload_json,
};
let plan = crate::ExApiInstructionExecutor::build_plan(
&crate::ExSplAssociatedTokenAccountExecutor,
&request,
)
.unwrap_or_else(|error| panic!("generic ATA plan failed: {error}"));
assert_eq!(plan.instruction_count, 1);
let prepared =
serde_json::from_str::<crate::ExApiPreparedExecutionPlan>(&plan.payload_json)
.unwrap_or_else(|error| panic!("prepared ATA plan parsing failed: {error}"));
assert_eq!(prepared.operation_code, crate::EX_SPL_ATA_CREATE_IDEMPOTENT_OPERATION);
assert_eq!(prepared.instructions[0].data, std::vec![1]);
}
#[test]
fn machine_readable_matrix_matches_compiled_executor_capabilities() {
let matrix: serde_json::Value = serde_json::from_str(include_str!(
"../../../../../docs/SPL_ASSOCIATED_TOKEN_ACCOUNT_MATRIX.json"
))
.unwrap_or_else(|error| panic!("ATA matrix parsing failed: {error}"));
let instructions = matrix["instructions"]
.as_array()
.unwrap_or_else(|| panic!("ATA matrix instructions must be an array"));
let matrix_operations = instructions
.iter()
.map(|instruction| {
assert_eq!(instruction["executorSupport"]["status"], "supported");
return instruction["executorSupport"]["operationCode"]
.as_str()
.unwrap_or_else(|| panic!("ATA operation code must be a string"));
})
.collect::<std::vec::Vec<_>>();
assert_eq!(matrix_operations, crate::EX_SPL_ATA_SUPPORTED_OPERATION_CODES);
assert_eq!(matrix["surfaceEquality"]["matrixVariantCount"], 3);
assert_eq!(matrix["surfaceEquality"]["officialInterfaceVariantCount"], 3);
}
}

View File

@@ -0,0 +1,126 @@
// file: kb-lib/src/executor/spl/associated_token_account/intent.rs
// version: 2
//! Typed SPL Associated Token Account execution intents.
use ts_rs::TS; // rust-rules: derive-import
/// Stable operation code for strict ATA creation.
pub const EX_SPL_ATA_CREATE_OPERATION: &str = "spl_associated_token_account.create";
/// Stable operation code for idempotent ATA creation or reuse.
pub const EX_SPL_ATA_CREATE_IDEMPOTENT_OPERATION: &str =
"spl_associated_token_account.create_idempotent";
/// Stable operation code for nested ATA recovery.
pub const EX_SPL_ATA_RECOVER_NESTED_OPERATION: &str = "spl_associated_token_account.recover_nested";
/// Every current officially constructible ATA operation.
pub const EX_SPL_ATA_SUPPORTED_OPERATION_CODES: &[&str] = &[
EX_SPL_ATA_CREATE_OPERATION,
EX_SPL_ATA_CREATE_IDEMPOTENT_OPERATION,
EX_SPL_ATA_RECOVER_NESTED_OPERATION,
];
/// Exact Token Program targeted by ATA derivation and runtime CPIs.
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_lib/executor/spl/associated_token_account/intent/ExSplAssociatedTokenProgram.ts"
)]
pub enum ExSplAssociatedTokenProgram {
/// Classic SPL Token program.
Classic,
/// Token-2022 program without extension-specific executor semantics.
Token2022,
}
impl crate::ExSplAssociatedTokenProgram {
/// Returns the exact target Token Program ID.
pub fn program_id(&self) -> &'static str {
return match self {
Self::Classic => kb_program_ids::SPL_TOKEN_PROGRAM_ID,
Self::Token2022 => kb_program_ids::SPL_TOKEN2022_PROGRAM_ID,
};
}
}
/// One officially constructible ATA operation.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, TS)]
#[serde(tag = "operation", rename_all = "snake_case")]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_lib/executor/spl/associated_token_account/intent/ExSplAssociatedTokenAccountOperation.ts"
)]
pub enum ExSplAssociatedTokenAccountOperation {
/// Strictly create an absent canonical ATA.
Create {
/// Wallet owner used as the first PDA seed.
wallet_owner: crate::MdPubkey,
/// Mint used as the third PDA seed.
mint: crate::MdPubkey,
/// Token Program used as the second PDA seed and runtime CPI target.
token_program: crate::ExSplAssociatedTokenProgram,
},
/// Create an absent ATA or accept an existing compatible ATA.
CreateIdempotent {
/// Wallet owner used as the first PDA seed.
wallet_owner: crate::MdPubkey,
/// Mint used as the third PDA seed.
mint: crate::MdPubkey,
/// Token Program used as the second PDA seed and runtime CPI target.
token_program: crate::ExSplAssociatedTokenProgram,
},
/// Recover tokens and lamports from one canonical nested ATA.
RecoverNested {
/// Wallet owner that must sign the recovery.
wallet_owner: crate::MdPubkey,
/// Mint whose ATA currently owns the nested ATA.
owner_mint: crate::MdPubkey,
/// Mint held by the nested ATA and the wallet destination ATA.
nested_mint: crate::MdPubkey,
/// Token Program shared by all three derived ATA addresses.
token_program: crate::ExSplAssociatedTokenProgram,
},
}
impl crate::ExSplAssociatedTokenAccountOperation {
/// Returns the stable generic dispatch operation code.
pub fn operation_code(&self) -> &'static str {
return match self {
Self::Create { .. } => crate::EX_SPL_ATA_CREATE_OPERATION,
Self::CreateIdempotent { .. } => crate::EX_SPL_ATA_CREATE_IDEMPOTENT_OPERATION,
Self::RecoverNested { .. } => crate::EX_SPL_ATA_RECOVER_NESTED_OPERATION,
};
}
/// Returns the exact target Token Program.
pub fn token_program(&self) -> crate::ExSplAssociatedTokenProgram {
return match self {
Self::Create { token_program, .. }
| Self::CreateIdempotent { token_program, .. }
| Self::RecoverNested { token_program, .. } => *token_program,
};
}
pub(crate) fn is_creation(&self) -> bool {
return matches!(self, Self::Create { .. } | Self::CreateIdempotent { .. });
}
}
/// Complete typed intent accepted by the ATA executor.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, TS)]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_lib/executor/spl/associated_token_account/intent/ExSplAssociatedTokenAccountExecutionIntent.ts"
)]
pub struct ExSplAssociatedTokenAccountExecutionIntent {
/// Stable caller-provided identifier used for logs and replay correlation.
pub intent_id: std::string::String,
/// Transaction fee payer and Create/CreateIdempotent funding account.
pub fee_payer: crate::MdPubkey,
/// Maximum rent lamports the creation operation may spend; zero for RecoverNested.
pub max_rent_lamports: u64,
/// Conservative common execution policy.
pub policy: crate::ExApiExecutionPolicy,
/// Typed ATA operation and exact address inputs.
pub operation: crate::ExSplAssociatedTokenAccountOperation,
}