# What are Smart Contracts?

##

<figure><img src="/files/191MLWJIUCVkKBMUUXau" alt=""><figcaption></figcaption></figure>

**A smart contract is a piece of programmed code deployed on the blockchain to automatically execute contract terms. It can automatically complete specific tasks, such as transferring money, recording transactions, or verifying information, based on preset conditions without the intervention of a third party. The core features of smart contracts are automated execution, transparency, trustworthiness, and immutability.**

**Simply put, a smart contract is like a "vending machine":**

* **You insert a coin (satisfy the conditions)**
* **The machine automatically pops up the product (executes the contract)**
* **No need for store clerk (intermediary) intervention**

#### Features of Smart Contracts

* [x] **Automatic execution:**

- **The contract terms are written in code. Once the set conditions are triggered, the contract runs automatically without human intervention.**

* [x] **Decentralization:**

- **The contract runs on a distributed blockchain network and is not controlled by a central organization.**

* [x] **Transparency:**

- **Everyone can view the contract content and execution process.**

* [x] **Tamper-proof:**

- **Once deployed to the blockchain, the content of the contract cannot be changed and the records are permanently saved.**

* [x] **High efficiency:**

- **Automated processes reduce manpower and time costs and avoid cumbersome processes.**

***

#### How do smart contracts work?

* [x] **Write a contract:**

**Use a specialized programming language (such as Solidity) to write a smart contract, define the trigger conditions and execution logic.**

* [x] **Deploy to the blockchain:**

**Publish the contract to the blockchain (such as Ethereum), and each contract has a unique address.**

* [x] **Trigger conditions:**

**When the preset conditions are met (such as receiving funds or an event occurs), the contract will be automatically executed.**

* [x] **Record results:**

**All execution results will be recorded on the blockchain, which is open, transparent, and cannot be tampered with.**

***

#### Application scenarios of smart contracts

**1.Financial services:**

* **Decentralized lending: Automatically issuing loans or processing mortgages.**
* **Insurance: Automatic claims triggered based on conditions.**
* **Payments: Smart contracts ensure that funds are paid on time.**

**2.Supply Chain:**

* **Record the entire process of goods from production to delivery to ensure transparency and traceability.**

**3.Digital Asset Management:**

* **Ensure uniqueness and ownership of assets in NFT and digital collectibles transactions.**

**4.Voting system:**

* **Transparent and secure online voting to prevent fraud.**

**5.Automatic dividends:**

* **According to the profit distribution rules, the smart contract automatically distributes dividends to shareholders.**

***

#### Advantages and Disadvantages of Smart Contracts

* **Advantages**
* **No trust required: The execution of the contract depends on the code, not the commitment of both parties.**
* **Reduce costs: Eliminate intermediaries, reduce disputes and transaction costs.**
* **Transparency and fairness: Contracts and execution records can be publicly reviewed.**
* **Global applicability: Blockchain-based smart contracts can be executed across borders.**

- [x] **Disadvantages**

* **Deployment immutability: cannot be modified after deployment, and execution cannot be backtracked.**
* **High technical threshold: requires super professional developers to write and deploy.**
* **Blockchain performance limitations: some blockchains (such as Ethereum) have slow transaction processing speeds and high fees.**

**Example explanation**

* [x] **Assume that the function of a smart contract is to automatically pay wages:**

- **Contract Terms:**

1. **On the 1st of each month, if the employee completes the work, a salary of 1,000 USDT will be paid.**
2. **If the work is not completed, no salary will be paid.**

* **Implementation method:**

1. **The company transfers the salary to the smart contract address.**
2. **The system checks the employee's work record.**
3. **If the conditions are met, the contract will automatically pay wages to the employee's address.**
4. **If the conditions are not met, the funds are returned to the company account.**

***

### Smart contract example in MEXC Web3

#### What is MEXC Web3 smart contract?

{% hint style="success" %}
MEXC Web3 is a decentralized finance (DeFi) platform based on blockchain technology that uses smart c**ontracts to provide users with functions such as profit distribution and invitation rewards.**
{% endhint %}

**The following are several examples of the core functions of the MEXC Web3** **smart contract:**

1. **Automatic distribution of MEXC Web3 Loop income**

* [x] **In the MEXC Web3 platform, users deposit funds into their wallets, and the smart contract automatically generates and distributes profits based on the deposit amount and time.**

**Rules:**

> If your wallet has 1,000 USDT, the smart contract will record the amount and time.
>
> Rewards will be automatically calculated according to the smart contract rules:> \
> (Rewards are distributed hourly)
>
> Daily: 4.5% return (e.g., if your wallet has 1,000 USDT, you will earn 45 USDT in one day).
>
> Daily: 5% return (e.g., if your wallet has 5,000 USDT, you will earn 250 USDT in one day).
>
> Daily: 8% return (e.g., if your wallet has 30,000 USDT, you will earn 2,400 USDT in one day).
>
> Daily: 10% return (e.g., if your wallet has 80,000 USDT, you will earn 8,000 USDT in one day).

* [x] **Smart contract example logic:**

<pre><code>//pragma solidity ^0.8.0;

/**
 * MEXC Web3 Smart Contract Example
 * This contract demonstrates how users can deposit funds and earn interest based on the holding period.
 */

contract MEXC Web3 {
    address public owner; // Owner of the contract

    struct Deposit {
        uint256 amount; // The deposited amount
        uint256 startTime; // Timestamp when the deposit was made
    }

    mapping(address => Deposit) public deposits; // Tracks deposits for each user

    constructor() {
        owner = msg.sender; // Set the contract owner
    }

    // Deposit funds into the contract
    function deposit() public payable {
        require(msg.value > 0, "Deposit amount must be greater than zero");
        require(deposits[msg.sender].amount == 0, "Existing deposit must be withdrawn first");

        deposits[msg.sender] = Deposit({
            amount: msg.value,
            startTime: block.timestamp
        });
    }

    // Calculate the interest based on the holding period
    function calculateInterest(address user) public view returns (uint256) {
        Deposit memory userDeposit = deposits[user];
        require(userDeposit.amount > 0, "No active deposit found");

        uint256 holdingPeriod = block.timestamp - userDeposit.startTime; // Calculate holding period in seconds
        uint256 interestRate;

        // Determine interest rate based on holding period
       if (holdingPeriod >= 80000) {
       interestRate = 8000; // 10% interest
       } else if (holdingPeriod >= 30000) {
       interestRate = 2400; // 8% interest
       } else if (holdingPeriod >= 5000) {
       interestRate = 250; // 5% interest
       } else if (holdingPeriod >= 1000) {
<strong>       interestRate = 45; // 4.5% interest
</strong>       } else {
       interestRate = 0; // No interest for less than 1 day
       }

return (userDeposit.amount * interestRate) / 1000; // Returns calculated interest
}

    // Withdraw deposited funds along with the earned interest
    function withdraw() public {
        Deposit memory userDeposit = deposits[msg.sender];
        require(userDeposit.amount > 0, "No deposit to withdraw");

        uint256 interest = calculateInterest(msg.sender); // Calculate the interest
        uint256 totalAmount = userDeposit.amount + interest; // Add interest to the principal amount

        // Reset the user's deposit
        delete deposits[msg.sender];

        // Transfer funds to the user
        payable(msg.sender).transfer(totalAmount);
    }

    // Check the deposit details of a user
    function getDepositDetails(address user) public view returns (uint256 amount, uint256 startTime) {
        Deposit memory userDeposit = deposits[user];
        return (userDeposit.amount, userDeposit.startTime);
    }
}

</code></pre>

{% hint style="success" %}
**Effect: Users only need to hold funds in their wallets, and the smart contract will ensure that the income is credited on time without any additional operations.**
{% endhint %}

2. **Invitation Rewards**

* [x] **MEXC Web3  invitation rewards are also completed through smart contracts. When a user invites a new user, the reward will be automatically distributed to the inviter’s account.**

**Rules:**

> For each new user referred, the referrer can earn multiple tiers of rewards.
>
> \
> Reward Structure:
>
> \
> Direct Referral (Level 1): 15% of the rewards.
>
> \
> Indirect Referral (Level 2): ​​8% of the rewards.
>
> \
> Indirect Referral (Level 3): 5% of the rewards.
>
> \
> Indirect Referral (Level 4): 2% of the rewards.

* [x] **Smart contract example logic:**

<figure><img src="https://3127960078-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FzvuqKZomFUK3nrXxCfJA%2Fuploads%2FSb4tqPP2U82e4yD6gT1B%2F%E6%98%AF%E7%9A%84.png?alt=media&#x26;token=1c6ea60e-9350-414f-8b39-56d3dd8461b1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3127960078-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FzvuqKZomFUK3nrXxCfJA%2Fuploads%2FI5lKPPQW0OAOf54jn5df%2F%E6%98%AF%E7%9A%841.png?alt=media&#x26;token=551cf62c-ccba-40dc-8ac5-551e8596e7ff" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
**Result: All invitation rewards are automatically distributed according to the rules without manual intervention from the platform.**
{% endhint %}

***

* **Summarize: Smart contracts automate contract terms through code and are an important application of blockchain technology. It has advantages such as automatic execution, high transparency and low cost, but in practical applications, attention should be paid to code security and blockchain performance issues.**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mexc-web3.gitbook.io/mexcweb3-docs/basics/what-are-smart-contracts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
