Address
304 North Cardinal St.
Dorchester Center, MA 02124

Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM

The Technical Principles of Blockchain Escrow: How Smart Contracts Secure Your Transactions

In today’s blog post, we’ll dive deep into the technology powering Tethermalls’ secure transaction system. By analyzing our actual smart contract code, we’ll explore how blockchain escrow works and why it represents a revolutionary advancement in transaction security.

What is a Smart Contract?

At the heart of blockchain escrow is the smart contract – a self-executing contract with terms directly written into code. Unlike traditional contracts that require third-party enforcement, smart contracts automatically enforce agreements when predefined conditions are met.

Tethermalls’ smart contracts are deployed on both Ethereum and Tron blockchains, leveraging the security and transparency of these established networks.

Analysis of Tethermalls’ EscrowTrade Contract

Let’s examine the key components of the EscrowTrade smart contract that enables secure P2P transactions on Tethermalls.

1. State and Structure Definitions

// Transaction states
enum Status {
AWAITING_DEPOSIT, // Waiting for deposit
APPROVED, // Transaction approved (in progress)
DISPUTED, // Dispute occurred
COMPLETED, // Transaction completed
REFUNDED // Refund completed
}

struct Trade {
address buyer;
address seller;
address arbiter;
uint256 fee;
address feeOwner;
address tokenAddress;
uint256 amount;
Status status;
}

// Store trade information by trade ID
mapping(bytes32 => Trade) public trades;

This code defines possible states for a transaction and establishes a Trade struct that contains all necessary information for each transaction. Key points include:

Token address and amount specify which cryptocurrency is being traded and how much

Each trade has a unique identifier (bytes32 type tradeId)

Trades include buyer, seller, and arbiter (mediator)

The current state of each transaction is tracked

2. Trade Creation

solidity복사function createTrade(
    bytes32 _tradeId,
    address _buyer,
    address _seller,
    address _tokenAddress,
    uint256 _amount
) public {
    require(_tokenAddress != address(0), "Invalid token address");
    require(
        _seller != address(0) && _buyer != address(0),
        "Invalid addresses"
    );
    require(!tradeExists[_tradeId], "Trade ID already exists");

    // Token validation
    IERC20 token = IERC20(_tokenAddress);
    try token.balanceOf(address(this)) returns (uint256) {
        // Confirm it's a valid ERC20 contract
    } catch {
        revert("Invalid ERC20 token address");
    }

    Trade storage newTrade = trades[_tradeId];
    newTrade.buyer = _buyer;
    newTrade.seller = _seller;
    newTrade.arbiter = owner;
    newTrade.fee = feePercentage;
    newTrade.feeOwner = feeOwner;
    newTrade.amount = _amount;
    newTrade.tokenAddress = _tokenAddress;
    newTrade.status = Status.AWAITING_DEPOSIT;

    tradeExists[_tradeId] = true;

    allTradeIds.push(_tradeId);

    emit TradeCreated(_tradeId, _buyer, _seller);
}

This function creates a new trade with several safety mechanisms:

  • Validation checks to prevent invalid addresses or duplicate trade IDs
  • Safety mechanism to verify the token address is a real ERC20 token
  • Initialization of trade details and setting the initial state to AWAITING_DEPOSIT
  • Emission of an event to record the trade creation on the blockchain

3. Fund Deposit

solidity복사function deposit(bytes32 tradeId) public {
    Trade storage trade = trades[tradeId];

    // 1. Checks
    require(msg.sender == trade.buyer, "Only buyer can deposit");
    require(
        trade.status == Status.AWAITING_DEPOSIT,
        "Invalid status for deposit"
    );

    IERC20 token = IERC20(trade.tokenAddress);
    require(
        token.allowance(msg.sender, address(this)) >= trade.amount,
        "Insufficient allowance"
    );

    // Balance check
    require(
        token.balanceOf(msg.sender) >= trade.amount,
        "Insufficient token balance"
    );

    // 2. Effects + 3. Interactions
    // Change state first
    trade.status = Status.APPROVED;

    token.safeTransferFrom(
        msg.sender,
        address(this),
        trade.amount
    );

    emit Deposited(tradeId, msg.sender, trade.amount);
}

The most critical aspect at this stage is that funds are transferred directly to the smart contract address. From this moment, these funds cannot be arbitrarily accessed by anyone, including Tethermalls. The funds can only move according to the conditions programmed into the smart contract (buyer’s approval or dispute resolution mechanism).

This function is called when a buyer deposits funds into the smart contract:

  • It follows the Checks-Effects-Interactions pattern to protect against reentrancy attacks
  • Verifies that only the buyer can make deposits
  • Confirms the trade status is AWAITING_DEPOSIT
  • Checks that the buyer has sufficient tokens and allowance
  • Updates the state to APPROVED before transferring tokens
  • Uses safeTransferFrom for secure ERC20 transfers

4. Completing Transactions and Releasing Funds

solidity복사function _releaseFunds(bytes32 tradeId) private {
    Trade storage trade = trades[tradeId];
    uint256 fee = calculateFee(trade.amount, trade.fee);
    uint256 remainingAmount = trade.amount - fee;

    trade.status = Status.COMPLETED;

    IERC20 token = IERC20(trade.tokenAddress);

    token.safeTransfer(trade.feeOwner, fee);
    token.safeTransfer(trade.seller, remainingAmount);

    emit FeePaid(tradeId, trade.feeOwner, fee);
    emit FundsReleased(tradeId, trade.seller, remainingAmount, fee);
}

function releaseFunds(bytes32 tradeId) public {
    Trade storage trade = trades[tradeId];
    require(msg.sender == trade.buyer, "Not authorized");
    require(trade.status == Status.APPROVED, "Invalid status for release");

    _releaseFunds(tradeId);
}

The fund release functionality executes when a transaction is successfully completed:

  • The releaseFunds function can only be called by the buyer
  • The trade status must be in the APPROVED state
  • The internal _releaseFunds function calculates and separates the fee
  • Platform fee is sent to the feeOwner
  • The remaining amount is safely transferred to the seller
  • The state is changed to COMPLETED and relevant events are emitted

5. Dispute Resolution Mechanism

solidity복사function disputeArises(bytes32 tradeId)
    public
    onlyTradeBuyerOrSeller(tradeId)
{
    Trade storage trade = trades[tradeId];
    require(trade.status == Status.APPROVED, "Invalid status for dispute");

    trade.status = Status.DISPUTED;

    emit Disputed(tradeId, msg.sender);
}

function disputedTransactionToSeller(bytes32 tradeId) public {
    Trade storage trade = trades[tradeId];
    require(msg.sender == trade.arbiter, "Not authorized");
    require(trade.status == Status.DISPUTED, "Invalid status for release");

    _releaseFunds(tradeId);
}

function disputedTransactionToBuyer(bytes32 tradeId) public {
    Trade storage trade = trades[tradeId];
    require(msg.sender == trade.arbiter, "Not authorized");
    require(trade.status == Status.DISPUTED, "Invalid status for release");

    _refund(tradeId);
}

The dispute resolution process consists of three parts:

  1. Initiating a dispute: Either the buyer or seller calls the disputeArises function to change the trade status to DISPUTED
  2. Release to seller: If the arbiter decides to release funds to the seller, they call disputedTransactionToSeller
  3. Refund to buyer: If the arbiter decides to refund the buyer, they call disputedTransactionToBuyer

This structure provides a fair mediation process when disputes occur.

Real Flow of Tethermalls Escrow Transactions

Let’s examine the step-by-step process of how Tethermalls’ escrow system actually works:

1. Starting a Transaction

  1. A seller lists a product/service, and a buyer expresses interest
  2. The backend system calls the createTrade function, setting a unique trade ID, buyer and seller addresses, token address, and transaction amount
  3. The smart contract records the trade details and sets the status to AWAITING_DEPOSIT
  4. A TradeCreated event is emitted

2. Fund Deposit

  1. The buyer first calls the approve function of the ERC20 token contract to allow the escrow contract to transfer tokens
  2. The buyer calls the deposit function
  3. The smart contract verifies the buyer’s identity, trade status, token allowance, and balance
  4. The trade status is updated to APPROVED
  5. Tokens are transferred from the buyer’s wallet to the escrow contract
  6. A Deposited event is emitted

3. Product/Service Delivery

  1. The seller delivers the product or provides the service to the buyer
  2. This step occurs off-chain and is not directly recorded on the blockchain

4. Transaction Completion

Normal Completion:

  1. If the buyer is satisfied with the product/service, they call the releaseFunds function
  2. The smart contract verifies the buyer’s identity and trade status
  3. The fee is calculated, and funds are distributed (main amount to the seller, fee to the platform)
  4. The trade status is updated to COMPLETED
  5. FundsReleased and FeePaid events are emitted

In Case of Dispute:

  1. If a problem arises, either the buyer or seller calls the disputeArises function
  2. The trade status changes to DISPUTED
  3. The arbiter (platform administrator) reviews the dispute
  4. Based on the decision, the arbiter calls either disputedTransactionToSeller or disputedTransactionToBuyer
  5. Funds are transferred to either the seller or buyer, and relevant events are emitted

Security Advantages of Tethermalls Escrow

As evident from the code, Tethermalls’ escrow system incorporates several security measures:

1. Absolute Fund Security

The most important point is that once funds are deposited, no one, including Tethermalls, can access them outside of the programmed conditions. Looking at the smart contract code, deposited funds can only move in three ways:

  • The buyer calls the releaseFunds function to approve transaction completion
  • In case of a dispute, the arbiter calls either disputedTransactionToSeller or disputedTransactionToBuyer

Even Tethermalls operators cannot access the deposited funds without these function calls. This is because the code is immutably recorded on the blockchain and operates only according to the rules hardcoded in the smart contract. This is the core blockchain principle of “Code is Law.”

2. Checks-Effects-Interactions Pattern

All functions check conditions before changing state and change state before external calls, preventing reentrancy attacks.

3. Permission Restrictions

Each function can only be called by specific roles (buyer, seller, arbiter, owner).

4. Secure Token Transfers

The SafeERC20 library is used to prevent issues during token transfers.

5. State Management

A clear state system tracks each stage of the transaction and prevents operations in incorrect states.

6. Event Logging

All important actions emit events that are permanently recorded on the blockchain and can be tracked externally.

Conclusion

Tethermalls’ EscrowTrade smart contract represents an innovative solution that overcomes the limitations of traditional escrow services by leveraging blockchain technology. The core advantages of this system are:

  1. Absolute Fund Security: Once funds are deposited in the smart contract, no one, including Tethermalls, can access them outside of the programmed conditions. This is the most significant difference between traditional escrow services and Tethermalls.
  2. Code-Guaranteed Security: Funds move only according to predefined, immutable conditions. These conditions are hardcoded in the smart contract and cannot be arbitrarily changed, even by platform operators.
  3. Complete Transparency: All transactions and fund movements are permanently recorded on the blockchain and can be verified by anyone.
  4. Trustless Environment: Transaction parties don’t need to trust each other or the platform; they can trade safely through code execution.
  5. Fair Dispute Resolution: Only when a dispute arises does a mediator intervene, and even then, the mediator can only call predefined functions (refund to buyer or payment to seller).

Tethermalls’ smart contract is a real-world application of the core values of Web3 and blockchain technology: decentralization, transparency, and security. Through this technological foundation, Tethermalls provides users with a truly safe and trustworthy trading environment.


For more technical discussions and questions about our blockchain implementation, please contact our team through the official support channels listed on our website.

Leave a Reply

Your email address will not be published. Required fields are marked *