Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 34 additions & 61 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,12 @@ env:

jobs:
test:
name: Rust Unit Tests
name: Rust Tests & Coverage
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
Expand All @@ -34,33 +38,9 @@ jobs:
run: make check
- name: Run clippy
run: make lint
- name: Run tests
run: make test
- name: Build
run: make build

integration-test:
name: Integration Tests
runs-on: ubuntu-latest
needs: test
timeout-minutes: 30
permissions:
contents: read
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: llvm-tools-preview

- name: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
cache-on-failure: true


- name: Setup Solana CLI
uses: ./.github/actions/setup-solana

Expand All @@ -70,10 +50,11 @@ jobs:
- name: Install cargo-llvm-cov for coverage
run: cargo install cargo-llvm-cov

- name: Initialize coverage
- name: Initialize coverage with unit tests
run: |
echo "🧪 Initializing coverage instrumentation..."
echo "🧪 Running unit tests with coverage instrumentation..."
cargo llvm-cov clean --workspace
cargo llvm-cov test --no-report --workspace --lib

- name: Setup test environment
run: |
Expand Down Expand Up @@ -169,7 +150,7 @@ jobs:
path: coverage/
retention-days: 30

- name: Post coverage comment on PR
- name: Update PR description with coverage badge
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
Expand All @@ -187,46 +168,38 @@ jobs:
console.log('Error reading coverage:', error);
}

const comment = `## 📊 Rust Coverage Report

**Coverage:** ${coverage}%
// Determine badge color
let color = 'red';
if (parseFloat(coverage) >= 80) color = 'green';
else if (parseFloat(coverage) >= 60) color = 'yellow';

<details>
<summary>View detailed report</summary>
// Get current PR
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
});

Coverage artifacts have been uploaded to this workflow run.
[View Artifacts](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }})
// Create coverage badge section
const coverageBadge = `![Coverage](https://img.shields.io/badge/coverage-${coverage}%25-${color})`;
const coverageSection = `\n\n## 📊 Test Coverage\n${coverageBadge}\n\n**Coverage: ${coverage}%**\n\n[View Detailed Coverage Report](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})`;

</details>`;
// Update PR body
let newBody = pr.body || '';

// Remove existing coverage section if present
newBody = newBody.replace(/\n## 📊 Test Coverage[\s\S]*?(?=\n## |\n$|$)/g, '');

// Add new coverage section
newBody += coverageSection;

// Find existing comment
const { data: comments } = await github.rest.issues.listComments({
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
pull_number: context.issue.number,
body: newBody
});

const botComment = comments.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('## 📊 Rust Coverage Report')
);

if (botComment) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: botComment.id,
body: comment
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: comment
});
}

- name: Cleanup test environment
uses: ./.github/actions/cleanup-test-env

Expand Down
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,7 @@ test-ledger/

# Docs
sdks/ts/docs-html/
sdks/ts/docs-md/
sdks/ts/docs-md/

# AI
.claude/helpers/
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,4 @@ tempfile = "3.2"
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
mockito = "1.2.0"
serial_test = "3.2.0"
redis-test = "0.12.0"
141 changes: 139 additions & 2 deletions crates/lib/src/admin/token_util.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use crate::{
error::KoraError,
signer::{KoraSigner, Signer},
state::{get_all_signers, get_config, get_request_signer_with_signer_key},
state::{get_all_signers, get_request_signer_with_signer_key},
token::token::TokenType,
transaction::TransactionUtil,
CacheUtil,
};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_message::{Message, VersionedMessage};
Expand All @@ -18,6 +17,15 @@ use spl_associated_token_account::{
};
use std::{str::FromStr, sync::Arc};

#[cfg(not(test))]
use {crate::cache::CacheUtil, crate::state::get_config};

#[cfg(test)]
use {
crate::tests::config_mock::mock_state::get_config,
crate::tests::redis_cache_mock::MockCacheUtil as CacheUtil,
};

/*
This funciton is tested via the makefile, as it's a CLI command and requires a validator running.
*/
Expand Down Expand Up @@ -261,3 +269,132 @@ pub async fn find_missing_atas(

Ok(atas_to_create)
}

#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{
common::{
create_mock_rpc_client_account_not_found, create_mock_spl_mint_account,
create_mock_token_account, setup_or_get_test_signer, RpcMockBuilder,
},
config_mock::{ConfigMockBuilder, ValidationConfigBuilder},
};
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
};

#[tokio::test]
async fn test_find_missing_atas_no_spl_tokens() {
let _m = ConfigMockBuilder::new()
.with_validation(
ValidationConfigBuilder::new().with_allowed_spl_paid_tokens(vec![]).build(),
)
.build_and_setup();

let rpc_client = create_mock_rpc_client_account_not_found();
let payment_address = Pubkey::new_unique();

let result = find_missing_atas(&rpc_client, &payment_address).await.unwrap();

assert!(result.is_empty(), "Should return empty vec when no SPL tokens configured");
}

#[tokio::test]
async fn test_find_missing_atas_with_spl_tokens() {
let allowed_spl_tokens = [Pubkey::new_unique(), Pubkey::new_unique()];

let _m = ConfigMockBuilder::new()
.with_validation(
ValidationConfigBuilder::new()
.with_allowed_spl_paid_tokens(
allowed_spl_tokens.iter().map(|p| p.to_string()).collect(),
)
.build(),
)
.build_and_setup();

let cache_ctx = CacheUtil::get_account_context();
cache_ctx.checkpoint(); // Clear any previous expectations

let payment_address = Pubkey::new_unique();
let rpc_client = create_mock_rpc_client_account_not_found();

// First call: Found in cache (Ok)
// Second call: ATA account not found (Err)
// Third call: mint account found (Ok)
let responses = Arc::new(Mutex::new(VecDeque::from([
Ok(create_mock_token_account(&Pubkey::new_unique(), &Pubkey::new_unique())),
Err(KoraError::RpcError("ATA not found".to_string())),
Ok(create_mock_spl_mint_account(6)),
])));

let responses_clone = responses.clone();
cache_ctx
.expect()
.times(3)
.returning(move |_, _, _| responses_clone.lock().unwrap().pop_front().unwrap());

let result = find_missing_atas(&rpc_client, &payment_address).await;

assert!(result.is_ok(), "Should handle SPL tokens with proper mocking");
let atas = result.unwrap();
assert_eq!(atas.len(), 1, "Should return 1 missing ATAs");
}

#[tokio::test]
async fn test_create_atas_for_signer_calls_rpc_correctly() {
let _m = ConfigMockBuilder::new().build_and_setup();

let _ = setup_or_get_test_signer();

let address = Pubkey::new_unique();
let mint1 = Pubkey::new_unique();
let mint2 = Pubkey::new_unique();

let atas_to_create = vec![
ATAToCreate {
mint: mint1,
ata: spl_associated_token_account::get_associated_token_address(&address, &mint1),
token_program: spl_token::id(),
},
ATAToCreate {
mint: mint2,
ata: spl_associated_token_account::get_associated_token_address(&address, &mint2),
token_program: spl_token::id(),
},
];

let rpc_client = RpcMockBuilder::new().with_blockhash().with_send_transaction().build();

let result = create_atas_for_signer(
&rpc_client,
&get_request_signer_with_signer_key(None).unwrap(),
&address,
&atas_to_create,
Some(1000),
Some(100_000),
2,
)
.await;

// Should fail with signature validation error since mock signature doesn't match real transaction
match result {
Ok(_) => {
panic!("Expected signature validation error, but got success");
}
Err(e) => {
let error_msg = format!("{e:?}");
// Check if it's a signature validation error (the mocked signature doesn't match the real transaction signature)
assert!(
error_msg.contains("signature")
|| error_msg.contains("Signature")
|| error_msg.contains("invalid")
|| error_msg.contains("mismatch"),
"Expected signature validation error, got: {error_msg}"
);
}
}
}
}
Loading
Loading