Address
304 North Cardinal St.
Dorchester Center, MA 02124
Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM
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.
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.
Let’s examine the key components of the EscrowTrade
smart contract that enables secure P2P transactions on Tethermalls.
// 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
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:
AWAITING_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:
AWAITING_DEPOSIT
APPROVED
before transferring tokenssafeTransferFrom
for secure ERC20 transferssolidity복사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:
releaseFunds
function can only be called by the buyerAPPROVED
state_releaseFunds
function calculates and separates the feefeeOwner
COMPLETED
and relevant events are emittedsolidity복사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:
disputeArises
function to change the trade status to DISPUTED
disputedTransactionToSeller
disputedTransactionToBuyer
This structure provides a fair mediation process when disputes occur.
Let’s examine the step-by-step process of how Tethermalls’ escrow system actually works:
createTrade
function, setting a unique trade ID, buyer and seller addresses, token address, and transaction amountAWAITING_DEPOSIT
TradeCreated
event is emittedapprove
function of the ERC20 token contract to allow the escrow contract to transfer tokensdeposit
functionAPPROVED
Deposited
event is emittedreleaseFunds
functionCOMPLETED
FundsReleased
and FeePaid
events are emitteddisputeArises
functionDISPUTED
disputedTransactionToSeller
or disputedTransactionToBuyer
As evident from the code, Tethermalls’ escrow system incorporates several security measures:
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:
releaseFunds
function to approve transaction completiondisputedTransactionToSeller
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.”
All functions check conditions before changing state and change state before external calls, preventing reentrancy attacks.
Each function can only be called by specific roles (buyer, seller, arbiter, owner).
The SafeERC20
library is used to prevent issues during token transfers.
A clear state system tracks each stage of the transaction and prevents operations in incorrect states.
All important actions emit events that are permanently recorded on the blockchain and can be tracked externally.
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:
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.