Skip to content

Implementation

justSid26 edited this page Apr 21, 2026 · 6 revisions

Implementation

Repository Link

🔗 https://github.com/JustSid26/SmartContract


Project Setup

Prerequisites

Prerequisite Installation
Rust + Cargo curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Node.js + npm https://nodejs.org/en (LTS)
Git Pre-installed on macOS/Linux; git-scm.com for Windows

Step 1 — Clone the Repository

git clone https://github.com/JustSid26/SmartContract
cd SmartContract

Step 2 — Start the Backend (Rust)

cd backend
cargo run

Expected output:

Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.45s
Running `target/debug/backend`
Server running at http://0.0.0.0:3000

⚠️ Make sure port 3000 is not in use before running.


Step 3 — Install Frontend Dependencies

Open a new terminal and from the project root:

cd frontend
npm install

Step 4 — Start the Frontend (Next.js)

npm run dev -- -p 3001

Expected output:

▲ Next.js 16.1.6 (Turbopack)
- Local: http://localhost:3001

⚠️ Make sure port 3001 is not in use. The backend must still be running on port 3000.


Step 5 — Test via CLI

# Test with valid contract
cd contracts/counter_contract
curl -F "file=@artifacts/counter_contract.wasm" http://localhost:3000/api/validate

# Test with invalid contract
curl -F "file=@artifacts/invalid.wasm" http://localhost:3000/api/validate

Code Structure

SmartContract/
├── backend/                  # Rust HTTP server
│   ├── src/
│   │   └── main.rs           # Server entry point, routes, validation logic
│   ├── Cargo.toml            # Rust dependencies
│   └── target/               # Build artifacts (generated)
│
├── contracts/
│   └── counter_contract/
│       └── artifacts/
│           ├── counter_contract.wasm   # Valid CosmWasm contract (test fixture)
│           └── invalid.wasm            # Invalid WASM binary (test fixture)
│
├── frontend/                 # Next.js application
│   ├── app/                  # Next.js App Router
│   │   ├── page.tsx          # Main UI page
│   │   └── layout.tsx        # Root layout
│   ├── lib/                  # Utility functions
│   ├── public/               # Static assets
│   ├── package.json          # Node dependencies
│   └── next.config.js        # Next.js configuration
│
├── docs/
│   ├── SmartContract.png     # Architecture diagram
│   ├── ts-logo.webp          # TypeScript logo
│   ├── react-logo.webp       # React logo
│   └── rust-logo.webp        # Rust logo
│
├── .gitignore
└── README.md

Key Code Snippets

Backend — Rust HTTP Server (backend/src/main.rs)

The server receives a multipart file upload and passes the bytes to the validator:

// POST /api/validate endpoint handler
async fn validate_contract(mut payload: Multipart) -> impl Responder {
    while let Some(field) = payload.next().await {
        let mut field = field.unwrap();
        let mut bytes = Vec::new();

        while let Some(chunk) = field.next().await {
            bytes.extend_from_slice(&chunk.unwrap());
        }

        let result = validate_wasm(&bytes);
        return HttpResponse::Ok().json(result);
    }

    HttpResponse::BadRequest().json(json!({ "error": "No file provided" }))
}

Explanation: The handler streams the multipart body, collects all byte chunks, then calls validate_wasm() and returns the result as JSON.


Backend — Validation Logic

fn validate_wasm(bytes: &[u8]) -> ValidationResult {
    // Check WASM magic number: \0asm
    if bytes.len() < 8 || &bytes[0..4] != b"\0asm" {
        return ValidationResult {
            valid: false,
            message: "Not a valid WASM binary".to_string(),
            size_bytes: bytes.len(),
        };
    }

    // CosmWasm compliance check (interface requirements)
    match check_cosmwasm_compliance(bytes) {
        Ok(_) => ValidationResult {
            valid: true,
            message: "WASM contract passed CosmWasm validation".to_string(),
            size_bytes: bytes.len(),
        },
        Err(e) => ValidationResult {
            valid: false,
            message: e.to_string(),
            size_bytes: bytes.len(),
        },
    }
}

Explanation: Checks the binary magic bytes first, then delegates to CosmWasm compliance checking. Returns a typed ValidationResult struct.


Frontend — File Upload & Validation (frontend/app/page.tsx)

const handleValidate = async (file: File) => {
  const formData = new FormData();
  formData.append("file", file);

  const response = await fetch("http://localhost:3000/api/validate", {
    method: "POST",
    body: formData,
  });

  const result = await response.json();
  setValidationResult(result);  // { valid, message, size_bytes }
};

Explanation: Builds a FormData object with the selected file, POSTs it to the Rust backend, and stores the parsed JSON response in component state for rendering.


Integration Details

  • The frontend communicates with the backend via a direct fetch call to http://localhost:3000/api/validate. In production, this would be proxied through next.config.js rewrites.
  • The Rust backend uses CORS headers to allow requests from the frontend origin (port 3001).
  • The CLI workflow bypasses the frontend entirely, hitting the backend API directly with curl.
  • Both .wasm test files in contracts/counter_contract/artifacts/ are committed to the repo so the validator can be tested immediately after cloning.

Solidity Support, Wallet Connection, and Deployment

Solidity Contract Support

The platform also supports Solidity contract workflows in addition to CosmWasm validation. Users can select the Solidity mode from the frontend validator interface and upload .sol files. The frontend sends the selected file to the backend validation API through the same user flow. For Solidity responses, the backend can return compiled artifacts such as ABI and bytecode. This enables a continuous path from validation to deployment readiness inside one interface.

Wallet Connection Workflow

For Solidity and EVM-compatible deployment, wallet integration is handled through MetaMask. The UI provides a wallet connect button that requests account access from the browser wallet provider. Connected account state is retained in frontend context so deploy actions can use the active address. If no wallet is detected, the UI prevents deployment and prompts the user with a clear error. For CosmWasm workflows, Keplr wallet integration is used with explicit testnet chain configuration.

Contract Deployment Flow

After successful validation, users can trigger deployment from the file result row in the UI. For Solidity, deployment uses the returned bytecode and sends a transaction via eth_sendTransaction. The app then polls transaction receipt status until a contract address is available. When deployment succeeds, the deployed contract address is displayed in the interface. For CosmWasm, deployment follows upload and instantiate steps through SigningCosmWasmClient. This design keeps validation, wallet authorization, and deployment in one cohesive experience.

Operational Notes

Deployment actions are intentionally available only for contracts that pass validation first. This gating reduces accidental deployment of malformed or unverified contract artifacts. Wallet-related failures are reported to the user to support quick recovery and retries. Using this combined flow improves developer productivity during local testing and demos.

Clone this wiki locally