In Sway, asset operations are one of the core functionalities of smart contracts, allowing contracts to handle the deposit (deposit), withdrawal (withdraw), and balance inquiry (get_balance) of funds.
deposit
function is a payable function that allows users to deposit funds into the smart contract.deposit
function, we use the require
function to ensure that the incoming asset ID is the base asset (base asset) and that the deposit amount is greater than 0.withdraw
function allows users to withdraw funds from the smart contract.transfer
function to execute the outgoing operation, which takes the sender, asset ID, and amount as parameters.get_balance
function allows users to query the balance of the base asset in the smart contract.balance_of
function to get the balance corresponding to the contract ID and asset ID.In the provided code, we define a smart contract named MyContract
with three functions: deposit
, withdraw
, and get_balance
.
deposit
function allows users to deposit funds into the smart contract and ensures the validity of the operation.withdraw
function allows users to withdraw funds from the smart contract.get_balance
function allows users to query the balance of the base asset in the smart contract.This simple example is intended to show you how to use asset operations to build a basic fund management smart contract in Sway. We hope this tutorial helps you better understand asset operations in Sway.
All Examplespredicate; use std::{ tx::{ tx_witness_data, tx_witnesses_count, tx_id }, constants::ZERO_B256, b512::B512, ecr::ec_recover_address }; configurable { REQUIRED_SIGNATURES: u64 = 0, SIGNERS: [Address; 3] = [ Address::from(0x0000000000000000000000000000000000000000000000000000000000000000), Address::from(0x0000000000000000000000000000000000000000000000000000000000000000), Address::from(0x0000000000000000000000000000000000000000000000000000000000000000) ] } fn verify_signature(i: u64) -> u64 { // Discard any out of bounds signatures if (i >= tx_witnesses_count()) { return 0; } let tx_hash = tx_id(); let mut j = 0; while j < 3 { let current_signature = tx_witness_data::(j); let current_address = ec_recover_address(current_signature, tx_hash).unwrap(); if current_address == SIGNERS[i] { return 1; } j += 1; } return 0; } fn main() -> bool { let mut valid_signatures = 0; // Verifiying each potential signature valid_signatures = verify_signature(0); valid_signatures = valid_signatures + verify_signature(1); valid_signatures = valid_signatures + verify_signature(2); if valid_signatures >= REQUIRED_SIGNATURES { return true; } return false; }