w3-kitDocs

Solidity vs Rust: Syntax Comparison

9 min readRaad05

This guide compares smart contract syntax and patterns between Solidity and Rust.

Rust examples in this guide target Anchor on Solana unless explicitly labeled as Native Solana.


Table of Contents

  1. Types
  2. Functions
  3. Error Handling
  4. Events & Logs
  5. Storage Patterns
  6. Common Operations
  7. Deploy & Test Commands

Types

Basic Types

OperationSolidityRust
Unsigned Integeruint256 x = 10;let x: u64 = 10;
Signed Integerint256 x = -10;let x: i64 = -10;
Booleanbool isActive = true;let is_active: bool = true;
Stringstring memory text = "hello";let text: String = "hello".to_string();
Addressaddress wallet = 0x123...;let pubkey: Pubkey = Pubkey::from_str("...")?;
Bytesbytes32 hash;let hash: [u8; 32] = [0; 32];

Complex Types

Solidity - Structs:

struct User {
    address wallet;
    uint256 balance;
    bool active;
}

Rust - Structs:

#[derive(Debug, Clone)]
pub struct User {
    pub wallet: Pubkey,
    pub balance: u64,
    pub active: bool,
}

Solidity - Arrays & Mappings:

uint256[] public balances;
mapping(address => uint256) public userBalances;
mapping(address => mapping(address => uint256)) public allowances;

Rust - Vectors (in-memory) & PDA Accounts (mapping equivalent):

// In-memory collection inside a single instruction (not persistent state)
let mut balances: Vec<u64> = Vec::new();

// Mapping-like persistent state on Solana uses PDA-derived accounts.
#[account]
pub struct UserBalance {
    pub owner: Pubkey,
    pub balance: u64,
}

#[derive(Accounts)]
pub struct UpsertUserBalance<'info> {
    #[account(
        init_if_needed,
        payer = signer,
        space = 8 + 32 + 8,
        seeds = [b"user-balance", signer.key().as_ref()],
        bump
    )]
    pub user_balance: Account<'info, UserBalance>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

Functions

Function Declaration

Solidity:

// Public function
function transfer(address to, uint256 amount) public returns (bool) {
    require(balances[msg.sender] >= amount, "Insufficient balance");
    balances[msg.sender] -= amount;
    balances[to] += amount;
    return true;
}

// View function (read-only)
function getBalance(address user) public view returns (uint256) {
    return balances[user];
}

// Internal function
function _validateAmount(uint256 amount) internal pure {
    require(amount > 0, "Amount must be positive");
}

Rust (Anchor on Solana):

pub fn transfer_sol(ctx: Context<TransferSol>, amount: u64) -> Result<()> {
    require!(amount > 0, CustomError::InvalidAmount);

    let from = &ctx.accounts.from;
    let to = &ctx.accounts.to;

    require!(
        **from.to_account_info().lamports.borrow() >= amount,
        CustomError::InsufficientBalance
    );

    **from.to_account_info().try_borrow_mut_lamports()? -= amount;
    **to.to_account_info().try_borrow_mut_lamports()? += amount;

    Ok(())
}

#[derive(Accounts)]
pub struct TransferSol<'info> {
    #[account(mut)]
    pub from: Signer<'info>,
    #[account(mut)]
    pub to: SystemAccount<'info>,
}

// Helper function
fn validate_amount(amount: u64) -> Result<()> {
    if amount == 0 {
        return err!(CustomError::InvalidAmount);
    }
    Ok(())
}

#[error_code]
pub enum CustomError {
    #[msg("Amount must be positive")]
    InvalidAmount,
    #[msg("Insufficient balance")]
    InsufficientBalance,
}

Function Visibility

VisibilitySolidityRust
Publicpublic - callable from anywhereFunctions exported from module
Internalinternal - only within contractFunctions marked with pub(crate)
Privateprivate - only in the contractFunctions without pub
Externalexternal - only from outsideN/A (use public)

Error Handling

Solidity Error Handling

// Using require
require(amount > 0, "Amount must be positive");

// Using assert
assert(balance >= amount);

// Using revert
if (amount > balance) {
    revert("Insufficient balance");
}

// Custom errors (Solidity 0.8.4+)
error InsufficientBalance(uint256 available, uint256 required);

function withdraw(uint256 amount) public {
    if (amount > balance) {
        revert InsufficientBalance(balance, amount);
    }
}

Rust Error Handling (Anchor)

// Using custom errors
#[error_code]
pub enum TokenError {
    #[msg("Insufficient balance")]
    InsufficientBalance,
    #[msg("Amount must be positive")]
    InvalidAmount,
    #[msg("Unauthorized")]
    Unauthorized,
}

fn validate_amount(amount: u64) -> Result<()> {
    require!(amount > 0, TokenError::InvalidAmount);
    Ok(())
}

// Using require! and the ? operator
pub fn withdraw(ctx: Context<Withdraw>, amount: u64) -> Result<()> {
    validate_amount(amount)?; // Early return on error

    let vault = &mut ctx.accounts.vault;
    require!(vault.balance >= amount, TokenError::InsufficientBalance);

    vault.balance -= amount;
    Ok(())
}

Events & Logs

Solidity Events

// Event declaration
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);

// Emitting events
function transfer(address to, uint256 amount) public {
    balances[msg.sender] -= amount;
    balances[to] += amount;
    emit Transfer(msg.sender, to, amount);
}

function approve(address spender, uint256 amount) public {
    allowances[msg.sender][spender] = amount;
    emit Approval(msg.sender, spender, amount);
}

Rust Logging (Anchor and Native Solana)

// Native Solana logging
msg!("Transfer initiated from {:?} to {:?}", from, to);

// Anchor events
#[event]
pub struct TransferEvent {
    pub from: Pubkey,
    pub to: Pubkey,
    pub amount: u64,
}

// In instruction handler
emit!(TransferEvent {
    from: ctx.accounts.from.key(),
    to: ctx.accounts.to.key(),
    amount: 100,
});

// Or using direct logging
msg!("Transfer: from={}, to={}, amount={}", from, to, 100);

Storage Patterns

Solidity State Variables

// Contract storage
contract Token {
    mapping(address => uint256) public balances;
    mapping(address => mapping(address => uint256)) public allowances;
    uint256 public totalSupply;
    address public owner;

    constructor() {
        owner = msg.sender;
        totalSupply = 1000000 * 10**18;
        balances[msg.sender] = totalSupply;
    }
}

Rust Account Data (Solana)

// Using Anchor framework
use anchor_lang::prelude::*;

#[account]
pub struct TokenAccount {
    pub mint: Pubkey,
    pub owner: Pubkey,
    pub balance: u64,
    pub delegate: Option<Pubkey>,
    pub delegated_amount: u64,
    pub is_frozen: bool,
}

// Initializing account
pub fn initialize_account(
    ctx: Context<InitializeAccount>,
) -> Result<()> {
    let account = &mut ctx.accounts.token_account;
    account.mint = ctx.accounts.mint.key();
    account.owner = ctx.accounts.owner.key();
    account.balance = 0;
    Ok(())
}

// Custom PDA (Program Derived Address)
#[account]
pub struct Vault {
    pub authority: Pubkey,
    pub bump: u8,
}

// Creating PDA
let (vault_pda, bump) = Pubkey::find_program_address(
    &[b"vault", authority.as_ref()],
    &program_id,
);

Storage Cost Comparison

AspectSolidityRust (Solana)
Cost ModelGas per operationCompute + account storage allocation
Storage PaymentOne-time deploymentOne-time rent-exempt deposit (refundable on account close)
Data PersistencePermanent (contract owner pays)Persistent while account stays allocated
Mutable StateImplicit in contract storage slotsMust pass writable accounts

Common Operations

Token Transfer

Solidity (ERC-20):

function transfer(address to, uint256 amount) public returns (bool) {
    require(balances[msg.sender] >= amount, "Insufficient balance");

    balances[msg.sender] -= amount;
    balances[to] += amount;

    emit Transfer(msg.sender, to, amount);
    return true;
}

Rust (SPL Token via CPI):

use anchor_spl::token::{self, Token, TokenAccount, Transfer};

pub fn transfer_tokens(
    ctx: Context<TransferTokens>,
    amount: u64,
) -> Result<()> {
    require!(amount > 0, TokenError::InvalidAmount);

    token::transfer(
        CpiContext::new(
            ctx.accounts.token_program.to_account_info(),
            Transfer {
                from: ctx.accounts.from.to_account_info(),
                to: ctx.accounts.to.to_account_info(),
                authority: ctx.accounts.authority.to_account_info(),
            },
        ),
        amount,
    )?;

    emit!(TransferEvent {
        from: ctx.accounts.from.key(),
        to: ctx.accounts.to.key(),
        amount,
    });

    Ok(())
}

#[derive(Accounts)]
pub struct TransferTokens<'info> {
    #[account(mut)]
    pub from: Account<'info, TokenAccount>,
    #[account(mut)]
    pub to: Account<'info, TokenAccount>,
    pub authority: Signer<'info>,
    pub token_program: Program<'info, Token>,
}

Check Balance

Solidity:

function balanceOf(address account) public view returns (uint256) {
    return balances[account];
}

// Usage
uint256 myBalance = token.balanceOf(msg.sender);

Rust:

pub fn get_balance(ctx: Context<GetBalance>) -> Result<u64> {
    Ok(ctx.accounts.token_account.amount)
}

Approval & TransferFrom

Solidity:

function approve(address spender, uint256 amount) public returns (bool) {
    allowances[msg.sender][spender] = amount;
    emit Approval(msg.sender, spender, amount);
    return true;
}

function transferFrom(
    address from,
    address to,
    uint256 amount
) public returns (bool) {
    require(balances[from] >= amount, "Insufficient balance");
    require(allowances[from][msg.sender] >= amount, "Allowance exceeded");

    balances[from] -= amount;
    balances[to] += amount;
    allowances[from][msg.sender] -= amount;

    emit Transfer(from, to, amount);
    return true;
}

Rust (SPL Token via CPI):

use anchor_spl::token::{self, Approve, Token, TokenAccount, Transfer};

pub fn approve_delegate(
    ctx: Context<ApproveDelegate>,
    amount: u64,
) -> Result<()> {
    token::approve(
        CpiContext::new(
            ctx.accounts.token_program.to_account_info(),
            Approve {
                to: ctx.accounts.token_account.to_account_info(),
                delegate: ctx.accounts.delegate.to_account_info(),
                authority: ctx.accounts.owner.to_account_info(),
            },
        ),
        amount,
    )?;

    Ok(())
}

pub fn delegated_transfer(
    ctx: Context<DelegatedTransfer>,
    amount: u64,
) -> Result<()> {
    // The delegate (spender) is the signer, transferring from the owner's account
    token::transfer(
        CpiContext::new(
            ctx.accounts.token_program.to_account_info(),
            Transfer {
                from: ctx.accounts.from.to_account_info(),
                to: ctx.accounts.to.to_account_info(),
                authority: ctx.accounts.delegate.to_account_info(),
            },
        ),
        amount,
    )?;

    Ok(())
}

Deploy & Test Commands

Solidity (Hardhat)

1. Setup:

npm install --save-dev hardhat
npx hardhat init
npm install @openzeppelin/contracts

2. Compile:

npx hardhat compile

3. Deploy:

npx hardhat run scripts/deploy.js --network localhost

4. Test:

npx hardhat test
npx hardhat test test/Token.test.js --grep "transfer"

5. Deploy to Testnet:

npx hardhat run scripts/deploy.js --network sepolia

Example Test:

describe("Token", function () {
  it("Should transfer tokens", async function () {
    const { token, addr1, addr2 } = await loadFixture(deployToken);

    await token.transfer(addr1.address, 100);
    expect(await token.balanceOf(addr1.address)).to.equal(100);
  });
});

Rust (Anchor on Solana)

1. Setup:

cargo install anchor-cli
anchor init my_program
cd my_program

2. Build:

anchor build

3. Deploy (Local):

solana config set --url localhost
solana-test-validator
anchor deploy

4. Test:

anchor test
anchor test --skip-local-validator

5. Deploy to Devnet:

solana config set --url devnet
anchor deploy

Example Test (TypeScript/Mocha, standard Anchor flow):

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { expect } from "chai";
import { MyProgram } from "../target/types/my_program";

describe("my_program", () => {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);

  const program = anchor.workspace.MyProgram as Program<MyProgram>;

  it("executes transfer instruction", async () => {
    const tx = await program.methods
      .transfer(new anchor.BN(100))
      .accounts({
        from: provider.wallet.publicKey,
        to: provider.wallet.publicKey,
      })
      .rpc();

    expect(tx).to.be.a("string");
  });
});

Key Deployment Differences

AspectSolidityRust (Solana)
Compilationsolc compilercargo build
Bytecode FormatEVM opcodesSBF (eBPF-derived)
StorageContract stateAccount data
UpgradesProxy patternNative upgrade authority (BPF Loader Upgradeable), anchor upgrade
Testing EnvironmentHardhat, TruffleAnchor, solana-test-validator, Surfpool
Local TestingHardhat nodesolana-test-validator, Surfpool
Network TokensTestnet ETH from faucetDevnet SOL from airdrop

Quick Reference Table

TaskSolidityRust
Check balancebalances[addr]account.amount
Transferbalances[from] -= amountModify account state
Emit eventemit Transfer(...)emit!(Event {...})
Require conditionrequire(cond, msg)require!(cond, err_msg)
Get callermsg.senderctx.accounts.signer.key()
Access timeblock.timestampClock::get()?.unix_timestamp
Revertrevert("msg")return Err(Error)
StorageState variablesAccount data

Resources