# Gas Tank

The Gas Tank is MakaPay's unified gas management system that allows merchants to fund payment settlements across all supported blockchains from a single USDT balance on MakaChain.

***

## How It Works

### The Problem

Traditional multi-chain payment acceptance requires:

* ETH on Ethereum for gas
* MATIC on Polygon for gas
* BNB on BSC for gas
* Managing multiple wallets and balances

This leads to:

* **Idle capital** sitting unused on each chain
* **Complexity** managing multiple native tokens
* **Risk** of settlements failing due to insufficient gas

### The Solution

MakaPay's Gas Tank:

* **Single deposit** of USDT on MakaChain
* **Automatic deduction** when payments are settled
* **Works across** Ethereum, Polygon, BSC, and MakaChain

```
┌─────────────────────────────────────────────┐
│         Your Gas Tank (MakaChain)           │
│         Balance: 50.00 USDT                 │
└─────────────────────────────────────────────┘
                     │
    ┌────────────────┼────────────────┐
    ▼                ▼                ▼
┌─────────┐    ┌─────────┐    ┌─────────┐
│Ethereum │    │ Polygon │    │   BSC   │
│Settlement│   │Settlement│   │Settlement│
│Gas: $2.50│   │Gas: $0.03│   │Gas: $0.10│
└─────────┘    └─────────┘    └─────────┘
```

***

## Understanding Fee Modes

MakaPay offers three distinct ways to handle fees. Understanding these is essential for choosing the right setup for your business.

### Mode 1: Gas Tank Mode (Default)

**Settings**: `gasless: false`, `payerCoversFee: false`

This is the premium merchant experience. You deposit USDT into your Gas Tank, and all fees are deducted from there.

```
You want: $100 USDT
Customer sends: $100 USDT (exact amount)
You receive: $100 USDT (exact amount)
Gas Tank pays: ~$1.13 (platform + processing + gas fees)
```

**Best for:**

* E-commerce with fixed prices
* Premium customer experience
* High-volume merchants who want predictable receipts

***

### Mode 2: Gasless Mode

**Settings**: `gasless: true`, `payerCoversFee: false`

Despite the name, "gasless" actually means **"Gas Tank-less"**—fees are deducted directly from the payment amount on-chain, so you don't need a Gas Tank balance.

```
You want: $100 USDT
Customer sends: $100 USDT
Fees deducted on-chain: ~$1.13
You receive: $98.87 USDT (less than requested)
Gas Tank pays: $0
```

**Best for:**

* Merchants who don't want to manage deposits
* Testing the platform
* Low-margin situations where you pass costs through

#### Important: Stablecoin Requirement

**Gasless mode only works with stablecoins** (USDT, USDC, DAI, BUSD, TUSD, USDP). This is because the gas fee calculation assumes the token is worth $1 USD.

**Supported stablecoins:**

* USDT (Tether)
* USDC (USD Coin)
* DAI (Dai Stablecoin)
* BUSD (Binance USD)
* TUSD (TrueUSD)
* USDP (Pax Dollar)

**What happens with non-stablecoins?**

If you attempt to create a gasless payment with a non-stablecoin token (e.g., WETH, WBTC), MakaPay automatically corrects this to use Gas Tank mode (`gasless: false`) instead. This prevents incorrect fee calculations.

```
Request: { token: WETH, gasless: true }
         ↓
Auto-corrected to: gasless: false
         ↓
Uses Gas Tank for fees (requires deposit)
```

**Why this matters:**

Gasless mode calculates fees assuming `1 token = $1 USD`. For non-stablecoins, this would be wildly incorrect:

```
Example: Gas costs $5 USD
- With USDT: Fee = 5 USDT = $5 ✅ CORRECT
- With WETH ($3000): Fee = 5 WETH = $15,000 ❌ WRONG!
```

**To use non-stablecoin tokens:**

1. Deposit USDT to your Gas Tank
2. Create payments with `gasless: false` (default)
3. Gas Tank will cover the fees in USD equivalent

***

### Mode 3: Payer Covers Fee

**Settings**: `payerCoversFee: true` (automatically enables gasless)

The fee is added on top of your requested amount. The customer pays more, but you receive exactly what you asked for.

```
You want: $100 USDT
Fees calculated: ~$1.13
Customer sends: $101.13 USDT (amount + fees)
Fees deducted on-chain: $1.13
You receive: $100 USDT (exact amount)
Gas Tank pays: $0
```

**Best for:**

* Invoicing and B2B payments
* Transparent fee handling
* When customers expect to pay transaction fees

***

### Fee Mode Comparison

| Mode                   | Customer Sends | You Receive | Gas Tank Used | Who Pays Fees      |
| ---------------------- | -------------- | ----------- | ------------- | ------------------ |
| **Gas Tank** (default) | $100           | $100        | Yes (\~$1.13) | You (from deposit) |
| **Gasless**            | $100           | \~$98.87    | No            | You (from payment) |
| **Payer Covers Fee**   | \~$101.13      | $100        | No            | Customer           |

***

## When Gas Tank Is Used

The Gas Tank is used when **both conditions are true**:

1. `gasless: false` (default)
2. `payerCoversFee: false` (default)

### Fee Deduction Breakdown

When a payment is settled, the following are deducted from your Gas Tank:

| Fee Component      | Description                                      |
| ------------------ | ------------------------------------------------ |
| **Platform Fee**   | Percentage based on your merchant type (0% - 1%) |
| **Processing Fee** | Fixed $0.10 per transaction                      |
| **Gas Fee**        | Blockchain gas cost in USD equivalent            |

### Example: $100 Payment on Polygon (Direct Merchant, 1%)

```
Payment received: $100 USDT
Customer sent to: 0x... (payment wallet address)

Settlement:
├── Platform Fee (1%):    $1.00 → Deducted from Gas Tank
├── Processing Fee:       $0.10 → Deducted from Gas Tank
├── Gas Fee (Polygon):    $0.03 → Deducted from Gas Tank
└── Total Gas Tank Deduction: $1.13

Merchant receives: $100.00 USDT (full amount)
```

### When Gas Tank Is NOT Used

Gas Tank is bypassed when:

* `gasless: true` - Fees taken from payment amount on-chain
* `payerCoversFee: true` - Fees added on top, taken on-chain

***

## Handling Payment Errors

One of the most powerful features of the Gas Tank is enabling merchants to **recover funds from problematic payments**. This includes underpayments, overpayments, wrong tokens, and wrong networks.

### How Payment Addresses Work

MakaPay uses undeployed smart contracts (CREATE2) to receive payments. Each payment address is computed based on:

* Merchant address
* Expected payment amount
* Fee amount (fixed at payment creation time)
* Token and chain parameters

Since the fee amount is **fixed at address computation time**, certain payment errors cannot be processed through the normal settlement flow.

***

### Underpayments

**Scenario**: You request $100 USDT, but the payer only sends $1.

```
Expected payment: $100 USDT
Fixed fee: $1.13
Computed payment address: 0x1234...

Payer sends: $1.00 USDT

Problem:
├── Payment received: $1.00
├── Expected fee: $1.13
├── Cannot deduct $1.13 from $1.00
└── Result: Funds stuck in payment address
```

**Recovery with Gas Tank:**

The merchant can withdraw these stuck funds by having a Gas Tank balance. The Gas Tank covers the gas cost for the withdrawal transaction.

```
Recovery Flow:

┌─────────────────────────────┐
│  Payment Address (0x1234)   │
│  Contains: $1.00 USDT       │
│  (Payer sent too little)    │
└─────────────┬───────────────┘
              │ Withdrawal Request
              ▼
┌─────────────────────────────┐
│      Your Gas Tank          │
│  Covers gas for withdrawal  │
│  ~$0.03 (Polygon)           │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│    Merchant Wallet          │
│  Receives: $1.00 USDT       │
│  (No platform/processing    │
│   fees charged)             │
└─────────────────────────────┘
```

**Key points:**

* No platform fee or processing fee charged (payment didn't complete)
* Only the actual gas cost for the withdrawal is deducted
* Works across all supported chains

***

### Wrong Network

**Scenario**: You request $100 USDT on Ethereum, but the payer sends it on Polygon.

Because payment addresses are computed deterministically, the same address exists on all EVM chains. If a payer sends to the right address but on the wrong network, the funds land in an undeployed contract on that chain.

```
Expected: $100 USDT on Ethereum (Chain ID: 1)
Payer sent: $100 USDT on Polygon (Chain ID: 137)

Result:
├── Ethereum address: Empty (no payment)
├── Polygon address: Contains $100 USDT
└── Payment shows as "unpaid" on Ethereum
```

**Recovery with Gas Tank:**

The merchant can recover funds from the wrong network using their Gas Tank balance:

1. Navigate to the payment in your dashboard
2. Request recovery from the incorrect chain (Polygon)
3. Gas Tank covers the withdrawal gas on Polygon
4. Funds sent to your wallet

```
Wrong Network Recovery:

┌─────────────────────────────┐
│  Payment Address (Polygon)  │
│  Contains: $100 USDT        │
│  (Should be on Ethereum)    │
└─────────────┬───────────────┘
              │ Recovery Request
              ▼
┌─────────────────────────────┐
│      Your Gas Tank          │
│  Covers Polygon gas         │
│  ~$0.03                     │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│    Merchant Wallet          │
│  Receives: $100 USDT        │
│  (on Polygon)               │
└─────────────────────────────┘
```

***

### Wrong Token

**Scenario**: You request $100 USDT, but the payer sends USDC instead.

The payment address can receive any ERC20 token, not just the expected one. If a payer sends the wrong token, it will be held at the payment address.

```
Expected: $100 USDT
Payer sent: $100 USDC

Result:
├── USDT balance: $0 (payment incomplete)
├── USDC balance: $100 (wrong token)
└── Payment shows as "unpaid"
```

**Recovery with Gas Tank:**

The merchant can recover the wrong token using their Gas Tank:

1. Navigate to the payment in your dashboard
2. Request recovery of the incorrect token (USDC)
3. Gas Tank covers the withdrawal gas
4. Wrong token sent to your wallet

```
Wrong Token Recovery:

┌─────────────────────────────┐
│  Payment Address            │
│  USDT: $0 (expected)        │
│  USDC: $100 (sent by payer) │
└─────────────┬───────────────┘
              │ Recovery Request
              ▼
┌─────────────────────────────┐
│      Your Gas Tank          │
│  Covers gas for withdrawal  │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│    Merchant Wallet          │
│  Receives: $100 USDC        │
└─────────────────────────────┘
```

***

### Overpayments

**Scenario**: You request $100 USDT, but the payer sends $150.

Unlike the error cases above, overpayments **are processed normally**. The important detail is that fees are only calculated based on the **original expected amount**, not the overpaid amount.

```
Expected payment: $100 USDT
Calculated fee: $1.13 (based on $100)
Payer sends: $150 USDT

Settlement:
├── Fee deducted: $1.13 (NOT recalculated for $150)
├── Merchant receives: $148.87
└── Extra $48.87 included (no extra fees)
```

This protects merchants from unexpected fee increases when customers overpay.

***

### Summary: Why Gas Tank Matters for Recovery

| Scenario          | Without Gas Tank           | With Gas Tank          |
| ----------------- | -------------------------- | ---------------------- |
| **Underpayment**  | Funds stuck forever        | Recover instantly      |
| **Wrong Network** | Funds stuck on wrong chain | Recover from any chain |
| **Wrong Token**   | Wrong token stuck          | Recover any token      |
| **Overpayment**   | Works normally             | Works normally         |

The Gas Tank is your safety net for handling real-world payment errors that inevitably occur.

***

## Depositing to Gas Tank

### Step 1: Get Your Deposit Address

1. Navigate to **Dashboard > Gas Tank**
2. Click **Deposit** or **Get Deposit Address**
3. A unique deposit address is generated for you

### Step 2: Send USDT

Send USDT to your deposit address on **MakaChain**:

* Network: MakaChain (Chain ID: 777178)
* Token: USDT (`0x30C28E393E0732335235685B345c95E6465Ad8A5`)
* RPC: `https://rpc.makachain.io`

### Step 3: Automatic Credit

Once confirmed:

* Your Gas Tank balance updates automatically
* No manual claiming required
* Funds available immediately for settlements

### How Deposits Work (Technical)

1. A deterministic address is computed using CREATE2
2. You send USDT to this pre-computed address
3. MakaPay deploys a PaymentWallet at that exact address
4. The wallet forwards USDT to the GasTank contract
5. GasTank credits your user balance

```solidity
// GasTank.sol
function onPaymentReceived(
    string calldata orderId,    // "userId_timestamp"
    address token,
    uint256 amountReceived,
    uint256 originalAmount,
    bool isPaymentComplete
) external {
    // Parse userId from orderId
    string memory parsedUserId = parseUserId(orderId);

    // Credit user balance
    userBalances[parsedUserId] += amountReceived;

    emit Deposited(parsedUserId, amountReceived);
}
```

***

## Gas Tank Contract

The GasTank is a smart contract deployed on MakaChain that manages merchant balances.

### Contract Address

| Network           | Address                                      |
| ----------------- | -------------------------------------------- |
| MakaChain Mainnet | `0xE94EB77a80BddD3a1c1813ed17894af0a3837d2C` |
| MakaChain Testnet | `0xE94EB77a80BddD3a1c1813ed17894af0a3837d2C` |

### Key Functions

#### `getBalance(userId)`

Returns the current USDT balance for a user.

```solidity
function getBalance(string calldata userId) external view returns (uint256)
```

#### `deductGas(userId, amount)`

Deducts USDT from a user's balance (called during settlement).

```solidity
function deductGas(string calldata userId, uint256 usdtAmount) external onlyOwner
```

#### `batchDeductGas(userIds, amounts)`

Efficiently deducts from multiple users in a single transaction.

```solidity
function batchDeductGas(
    string[] calldata userIds,
    uint256[] calldata amounts
) external onlyOwner
```

### Events

```solidity
event Deposited(string indexed userId, uint256 amount);
event GasDeducted(string indexed userId, uint256 amount);
event Withdrawn(string indexed userId, uint256 amount, address recipient);
```

***

## Balance Management

### Checking Your Balance

**Dashboard**: Gas Tank page shows current balance

**API**:

```bash
curl https://app.makapay.io/api/balance \
  -H "x-api-key: YOUR_API_KEY"
```

Response:

```json
{
  "balance": "45.320000"
}
```

### Recommended Balance

| Monthly Payments | Recommended Balance |
| ---------------- | ------------------- |
| 1-50             | $10 - $20           |
| 50-200           | $20 - $50           |
| 200-500          | $50 - $100          |
| 500+             | $100+               |

### Low Balance Handling

When your Gas Tank runs low:

1. **Warning**: Dashboard shows low balance alert at $5
2. **Awaiting Gas**: Payments show "Awaiting Gas" status
3. **Auto-Resume**: Settlement resumes after you deposit
4. **No Lost Payments**: Payments are never lost, just delayed

***

## Withdrawing from Gas Tank

### Withdrawing Unused Balance

You can withdraw your Gas Tank balance directly from the dashboard at any time.

**Steps:**

1. Navigate to **Dashboard > Gas Tank**
2. Click the **Withdraw** button next to your balance
3. Enter the amount you want to withdraw
4. Enter the recipient wallet address (any EVM address on MakaChain)
5. Confirm the withdrawal

The withdrawal is processed immediately and sent to your specified address on MakaChain.

**Note**: In most cases, you don't need to withdraw—the balance is automatically used for settlements and recovery operations. Withdrawing is useful if you want to move funds elsewhere or close your account.

***

## Security

### Deposit Address Security

* Each user has unique deposit addresses
* Addresses are deterministic (CREATE2)
* Nonce validation prevents replay attacks

### Balance Security

* Balances stored in audited smart contract
* Only MakaPay operator can deduct for settlements
* Emergency withdrawal function for edge cases

### Best Practices

* Only deposit what you need for 1-2 weeks
* Monitor balance regularly
* Set up low balance alerts


---

# 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://docs.makapay.io/guides/gas-tank.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.
