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
523 changes: 176 additions & 347 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 6 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,17 @@ keywords = [
"swap"
]
documentation = ""
exclude = [".github/**"]
exclude = [".github/**", "examples/",]
version = "0.1.0"
edition = "2024"

autoexamples = false

[dependencies]
thiserror = "2.0.16"
serde = {version="1.0.219", features=["derive"]}
starknet = "0.15.0"
starknet-contract = "0.15.0"
starknet-accounts = "0.15.0"
starknet-providers = "0.15.0"
starknet-core = "0.15.0"
tokio = { version = "1.0", features = ["full"] }
reqwest = { version = "0.12", features = ["json"] }
url = "2.5"
hex = "0.4"
serde_json = "1.0"
starknet = "0.17.0"
axum ={ version = "0.8.6", features = ["macros"] }
196 changes: 91 additions & 105 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,160 +1,146 @@
# AutoSwappr Rust SDK

A Rust implementation of the AutoSwappr SDK for interacting with the AutoSwappr smart contract on Starknet.

## Status

**Real Implementation** - This is a complete implementation with actual Starknet integration, real contract ABI, and full functionality.
A Rust SDK for interacting with the AutoSwappr contract on Starknet.

## Features

### Fully Implemented (Issues #1, #2, #3, #4)

- **Project Setup**: Complete Cargo configuration with proper metadata
- **Core Type Definitions**: All essential data structures and types
- **Real Starknet Integration**: Full blockchain integration with actual contract calls
- **Contract ABI**: Complete AutoSwappr contract ABI implementation
- **ERC20 Integration**: Full ERC20 token contract integration
- **Multi-Protocol Support**: Ekubo, AVNU, and Fibrous protocol support
- **Real Token Addresses**: Actual mainnet token addresses (STRK, ETH, USDC, USDT, WBTC)
- **Real Contract Address**: Actual AutoSwappr contract address
- **Error Handling**: Comprehensive error types and handling
- **Testing**: Unit tests for all core functionality
- **Documentation**: Complete API documentation and examples
- 🔄 Execute manual token swaps on Ekubo
- 🦀 Full Rust type safety
- ⚡ Async/await support with Tokio

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
autoswap-rust-sdk = "0.1.0"
autoswappr-sdk = "0.1.0"
tokio = { version = "1", features = ["full"] }
```

All other dependencies (like `starknet`, `axum`, etc.) are automatically included.

## AutoSwappr Contract Address

```
0x05582ad635c43b4c14dbfa53cbde0df32266164a0d1b36e5b510e5b34aeb364b
```

## Quick Start

```rust
use autoswap_rust_sdk::{SimpleAutoSwapprClient, SimpleConfig};
use autoswappr_sdk::{AutoSwappr, constant::{STRK, USDC}};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create configuration
let config = SimpleConfig {
contract_address: "0x05582ad635c43b4c14dbfa53cbde0df32266164a0d1b36e5b510e5b34aeb364b".to_string(),
rpc_url: "https://starknet-mainnet.public.blastapi.io/rpc/v0_7".to_string(),
account_address: "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef".to_string(),
private_key: "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef".to_string(),
};

// Create client
let client = SimpleAutoSwapprClient::new(config);

// Validate configuration
client.validate_config()?;

// Create swap data
let swap_data = client.create_swap_data(
"0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", // ETH
"0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8", // USDC
"1000000000000000000" // 1 ETH in wei
)?;

// Simulate swap (placeholder for actual execution)
let result = client.simulate_swap(&swap_data).await?;
println!("Swap result: {}", result);

Ok(())
async fn main() {
// Initialize the SDK
let mut swapper = AutoSwappr::config(
"https://starknet-mainnet.public.blastapi.io".to_string(),
"YOUR_ACCOUNT_ADDRESS".to_string(),
"YOUR_PRIVATE_KEY".to_string(),
"0x05582ad635c43b4c14dbfa53cbde0df32266164a0d1b36e5b510e5b34aeb364b".to_string(),
).unwrap();

// Execute swap (1 STRK to USDC)
let result = swapper.ekubo_manual_swap(*STRK, *USDC, 1).await;

match result {
Ok(response) => println!("Swap successful! Tx: {:?}", response.tx_hash),
Err(error) => println!("Swap failed: {}", error.message),
}
}
```

## API Reference

### SimpleAutoSwapprClient

The main client for interacting with AutoSwappr functionality.

#### Methods

- `new(config: SimpleConfig) -> Self` - Create a new client
- `validate_config() -> Result<(), SimpleError>` - Validate client configuration
- `create_swap_data(token_in: &str, token_out: &str, amount: &str) -> Result<SwapData, SimpleError>` - Create swap data
- `simulate_swap(swap_data: &SwapData) -> Result<String, SimpleError>` - Simulate a swap
### `AutoSwappr::config`

### SimpleConfig

Configuration for the AutoSwappr client.
Configure a new AutoSwappr instance.

```rust
pub struct SimpleConfig {
pub contract_address: String, // AutoSwappr contract address
pub rpc_url: String, // Starknet RPC URL
pub account_address: String, // Your account address
pub private_key: String, // Your private key
}
pub fn config(
rpc_url: String,
account_address: String,
private_key: String,
contract_address: String,
) -> Result<AutoSwappr, Json<ErrorResponse>>
```

### SwapData
### `ekubo_manual_swap`

Swap data structure containing all necessary information for a swap.
Execute a manual token swap.

```rust
pub struct SwapData {
pub token_in: String, // Input token address
pub token_out: String, // Output token address
pub amount: String, // Amount to swap (in wei)
pub caller: String, // Caller address
}
pub async fn ekubo_manual_swap(
&mut self,
token0: Felt,
token1: Felt,
swap_amount: u128,
) -> Result<Json<SuccessResponse>, Json<ErrorResponse>>
```

## Token Addresses
**Parameters:**

Common Starknet token addresses:
- `token0`: Source token address
- `token1`: Destination token address
- `swap_amount`: Amount to swap (in token units, not smallest denomination)

- **ETH**: `0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7`
- **USDC**: `0x053c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8`
- **USDT**: `0x068f5c6a61780768455de69077e07e89787839bf8166decfbf92b645209c0fb8`
- **STRK**: `0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d`
- **WBTC**: `0x03fe2b97c1fd336e750087d68b9b867997fd64a2661ff3ca5a7c771641e8e7ac`
**Returns:**

## Error Handling
- `Ok(SuccessResponse)`: Contains transaction hash on success
- `Err(ErrorResponse)`: Contains error message on failure

The SDK provides comprehensive error handling through the `SimpleError` enum:
## Available Token Addresses

```rust
pub enum SimpleError {
InvalidInput { details: String },
NetworkError { message: String },
ContractError { message: String },
Other { message: String },
}
```
use autoswappr_sdk::constant::{STRK, USDC, ETH};

## Testing
// STRK token
*STRK

Run the test suite:
// USDC token
*USDC

```bash
cargo test
// ETH token
*ETH
```

Run the example:
## Security Considerations

```bash
cargo run --example basic_usage
```
⚠️ **Never expose private keys in your code or version control**

## Development Status
1. Use environment variables for sensitive data
2. Keep private keys secure and encrypted
3. Test with small amounts first

This implementation covers the foundational aspects of Issues #1-#4 from the original roadmap:
## Example with Environment Variables

- **Issue #1**: Project setup and Cargo configuration
- **Issue #2**: Core type definitions and data structures
- **Issue #3**: Starknet integration (basic structure implemented, full integration pending)
- **Issue #4**: Contract ABI and interface implementation (structure ready, needs Starknet integration)
```rust
use std::env;

let rpc_url = env::var("STARKNET_RPC_URL").expect("STARKNET_RPC_URL not set");
let account_address = env::var("ACCOUNT_ADDRESS").expect("ACCOUNT_ADDRESS not set");
let private_key = env::var("PRIVATE_KEY").expect("PRIVATE_KEY not set");

let mut swapper = AutoSwappr::config(
rpc_url,
account_address,
private_key,
"0x05582ad635c43b4c14dbfa53cbde0df32266164a0d1b36e5b510e5b34aeb364b".to_string(),
).unwrap();
```

## Contributing

Contributions are welcome! Please see the [Issues](https://github.com/BlockheaderWeb3-Community/autoswap-rust-sdk/issues) for current development priorities.
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## Support

For support and questions, please open an issue on GitHub.

## License

Expand Down
8 changes: 4 additions & 4 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
contracts::{AutoSwapprContract, Erc20Contract},
types::connector::{AutoSwapprConfig, AutoSwapprError, ContractInfo, SwapData, Uint256},
types::connector::{AutoSwappr, AutoSwapprError, ContractInfo, SwapData, Uint256},
};
use starknet::{
accounts::{Account, ExecutionEncoding, SingleOwnerAccount},
Expand All @@ -18,12 +18,12 @@ pub struct AutoSwapprClient {
provider: Arc<JsonRpcClient<HttpTransport>>,
autoswappr_contract: AutoSwapprContract,
account: SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>,
config: AutoSwapprConfig,
config: AutoSwappr,
}

impl AutoSwapprClient {
/// Create a new AutoSwappr client with real Starknet integration
pub async fn new(config: AutoSwapprConfig) -> Result<Self, AutoSwapprError> {
pub async fn new(config: AutoSwappr) -> Result<Self, AutoSwapprError> {
// Parse RPC URL
let rpc_url = Url::parse(&config.rpc_url).map_err(|e| AutoSwapprError::InvalidInput {
details: format!("Invalid RPC URL: {}", e),
Expand Down Expand Up @@ -430,7 +430,7 @@ impl AutoSwapprClient {
mod tests {
use super::*;
use crate::types::connector::{
Amount, AutoSwapprConfig, PoolKey, SwapData, SwapParameters, Uint256,
Amount, AutoSwappr, PoolKey, SwapData, SwapParameters, Uint256,
};

fn create_test_config() -> AutoSwapprConfig {
Expand Down
Loading