Skip to Content

Deposits, balances, and transfers

Focus: one XELIS vault contract that credits deposits and lets users withdraw their own balance.

Open in Playground 

deposit_vault.slx
const BALANCES_KEY: string = "balances" hook constructor() -> u64 { let storage: Storage = Storage::new() let balances: map<Address, u64> = {} storage.store(BALANCES_KEY, balances) return 0 } fn balances() -> map<Address, u64> { let storage: Storage = Storage::new() return storage.load(BALANCES_KEY).unwrap_or({}) } entry deposit_xel() -> u64 { let asset: Hash = get_xelis_asset() let amount: u64 = get_deposit_for_asset(asset).unwrap_or(0) require(amount > 0, "attach a XELIS deposit") let sender: Address = Transaction::current().unwrap().source() let ledger: map<Address, u64> = balances() let current: u64 = ledger.get(sender).unwrap_or(0) ledger.insert(sender, current + amount) let storage: Storage = Storage::new() storage.store(BALANCES_KEY, ledger) return current + amount } entry withdraw_xel(amount: u64) -> u64 { let asset: Hash = get_xelis_asset() let sender: Address = Transaction::current().unwrap().source() let ledger: map<Address, u64> = balances() let current: u64 = ledger.get(sender).unwrap_or(0) require(amount > 0 && current >= amount, "insufficient balance") let remaining: u64 = current - amount if remaining == 0 { ledger.shift_remove(sender) } else { ledger.insert(sender, remaining) } let storage: Storage = Storage::new() storage.store(BALANCES_KEY, ledger) require(transfer(sender, amount, asset), "transfer failed") return remaining }

How it works

  • BALANCES_KEY stores a map<Address, u64> ledger in persistent storage.
  • constructor() initializes the ledger so later entries can load the same shape.
  • balances() is a small helper that loads the ledger and falls back to an empty map.
  • deposit_xel() reads the attached XELIS deposit with get_deposit_for_asset, credits the sender, stores the ledger, and returns the new balance.
  • withdraw_xel(amount) checks the sender’s recorded balance, updates or removes the ledger entry, transfers XELIS back with transfer, and returns the remaining balance.
Last updated on