DEV Community

Cover image for The last seat pays the seller: one transaction that swaps, seats and pays on QIE mainnet
Edy Cu
Edy Cu

Posted on

The last seat pays the seller: one transaction that swaps, seats and pays on QIE mainnet

Every group that books something together has one person who fronts the money. Picture Rina booking the Thursday 5-a-side football pitch: she pays the court, shares the cost in the group chat, then spends a week chasing people. If half the group drops out, she is the one who is short, and getting refunds back depends on her.

Patungan is Indonesian for chipping in together. I built a contract that removes the person in the middle. Everyone pays their own seat into an escrow. The last seat pays the seller in that same transaction. If the deadline passes first, every member takes their money back.

It is live on QIE mainnet: 0x2f4646D52a5393E239f5b880411dC2CA2D945F31, with source verified on Blockscout.
Live app: patungan.edycu.dev · repo: github.com/edycutjong/patungan · no-wallet judge path: /judge

The 2:41 demo, recorded against the live mainnet contract:

This post is about the one transaction that makes it work, and the two walls I hit getting it onto mainnet.

The rule: whoever fills the pool pays the seller

The escrow logic is short. Every join ends in _seat. When the seat count reaches the target, the same call flips the pool to Paid and transfers the whole pot to the payee:

function _seat(uint256 id, Pool storage p, address member, uint16 n, uint256 amount) private {
    if (seatsOf[id][member] == 0) members[id].push(member);
    seatsOf[id][member] += n;
    paid[id][member] += amount;
    p.filled += n;
    p.held += uint128(amount);
    totalHeld += amount;
    if (p.filled == p.seats) {
        uint256 total = p.held;
        p.status = Status.Paid;
        p.held = 0;
        totalHeld -= total;
        emit PoolPaid(id, p.payee, total);
        qusdc.safeTransfer(p.payee, total); // the last seat pays the payee in the same transaction
    }
}
Enter fullscreen mode Exit fullscreen mode

There is no "release" button and no keeper. Nobody has to come back later to trigger the payout. The payee can be a .qie name from QIE's Zone naming contract. The contract resolves it when the pool is created and stores the owner address it found. If the name points somewhere other than the address the form showed, creation reverts with PayeeChanged.

The hard part: the member holds QIE, the seller wants a stablecoin

Pools are priced in QUSDC, so the seller knows exactly what they receive. But a member may hold only the native QIE token. Making them buy QUSDC on a DEX first, then approve, then join, is three steps before they can even take a seat.

So joinWithQIE takes native QIE, buys exactly the QUSDC the seats cost (n × price) on QIEDEX, seats the member, and returns the unspent QIE, all in one call. If that member takes the last seat, the payout above runs in the same transaction too.

The catch is that the QIEDEX router's source is not verified on the explorer. I am sending users' funds through a contract I cannot read. So the contract does not trust the router's quote. It checks it against the QIE Oracle:

function _swapIn(uint256 amount) private returns (uint256 qieSpent, uint256 oraclePrice) {
    uint256 fairQie;
    (fairQie, oraclePrice) = _fairQie(amount);
    uint256 ceiling = fairQie * (10_000 + maxDevBps) / 10_000;
    address[] memory path = _path();
    uint256 qieIn = router.getAmountsIn(amount, path)[0];
    if (qieIn > ceiling) revert PriceDeviation(fairQie, qieIn);
    if (msg.value < qieIn) revert ValueTooLow(qieIn, msg.value);

    uint256 nativeBefore = address(this).balance;
    uint256 qusdcBefore = qusdc.balanceOf(address(this));
    router.swapETHForExactTokens{value: Math.min(msg.value, ceiling)}(amount, path, address(this), block.timestamp);
    if (qusdc.balanceOf(address(this)) - qusdcBefore < amount) revert SwapShort();
    qieSpent = nativeBefore - address(this).balance;
    if (qieSpent > ceiling) revert PriceDeviation(fairQie, qieSpent);
}
Enter fullscreen mode Exit fullscreen mode

Each check is there because of a specific way an untrusted router could cheat. Each one has a test with a hostile mock router:

  • Before the swap: if the router's quote is above the Oracle's fair value plus the guard (1,500 bps on the deployed contract), the call reverts. A skewed pool cannot push a member more than 15% past the Oracle's fair value.
  • During the swap: the router is handed at most min(msg.value, ceiling). It cannot take more than the ceiling even if it ignores its own quote.
  • After the swap: the contract measures what actually happened from its own balances. Less QUSDC than one seat reverts SwapShort, and more QIE spent than the ceiling reverts PriceDeviation. A re-entrant router hits the nonReentrant guard.

The Oracle read also refuses a price of zero or below, and a round older than the deployed maximum age.

Opening up the real transaction

Pool #1 on mainnet had 2 seats at 0.25 QUSDC. The second seat was paid in QIE: tx 0x4bd5c37d…a7a0. I traced it with debug_traceTransaction over the public RPC (script/mainnet-trace.py, read-only). There are 18 calls inside it. Shortened:

B2 → Patungan       joinWithQIE(pool 1), value 1.7223790439 QIE
Patungan → Oracle   latestRoundData → 0.15516198 USDT per QIE
Patungan → QIEDEX   getAmountsIn(0.25 QUSDC) → 1.7053257861 QIE
Patungan → QIEDEX   swapETHForExactTokens(exact out 0.25 QUSDC)
QIEDEX → Patungan   0.0170532579 QIE unspent
Patungan → QUSDC    balanceOf(Patungan) → 0.50 QUSDC
Patungan → QUSDC    transfer 0.50 QUSDC → qkulk75527.qie (payee)
Patungan → B2       0.0170532579 QIE change
Enter fullscreen mode Exit fullscreen mode

At that Oracle price, the fair value of a 0.25 QUSDC seat was 1.6112 QIE. The swap cost +584 bps over fair value, against a 1,500 bps guard. The whole thing used 267,557 gas. The member's QIE went in, a seat was taken, the seller was paid, and the change went back, all in one transaction.

The refund path ran on mainnet too. Pool #2 filled 3 of its 6 seats before the deadline passed. One refundAll (0x7886eba2…0f0a, 155,766 gas) returned 0.25 QUSDC to each of the 3 members. refundAll skips anyone who already claimed, so nobody gets refunded twice.

Wall 1: the chain said no to Cancun

QIE mainnet (chain 1990) is EVM-compatible, but not at the latest hard fork, so the compiler's EVM target has to match the chain. Instead of guessing, I wrote script/mainnet-probe.sh. It sends tiny bytecode snippets to the public RPC through eth_call, one per opcode:

PUSH0  (0x5f, Shanghai): "0x2a"
MCOPY  (0x5e, Cancun)  : ... invalid opcode: opcode 0x5e not defined
TSTORE (0x5d, Cancun)  : ... invalid opcode: opcode 0x5d not defined
Enter fullscreen mode Exit fullscreen mode

So foundry.toml pins evm_version = "shanghai". On a smaller EVM chain, run a probe like this before you trust a compiler default. It is a cheap check, and it beats debugging a deploy that reverts on an opcode the chain does not have.

Wall 2: the worst bug was in the browser, not the contract

The contract ended up at 100% line and branch coverage. The bug that would actually have cost a user money was in the web app's join sheet.

Paying in QUSDC takes two steps: Approve, then Pay. Paying in QIE takes one. In a scripted browser run on a fork of mainnet, a test member opened the join sheet, closed it, and reopened it. A QIE quote requested by the closed sheet arrived late and re-bound the reopened sheet's "1 · Approve" button to joinWithQIE. After the run, the chain showed seatsOf(7, Dave) = 2 and an allowance of 0. The click labelled Approve had bought a seat.

A second one was simpler: without a lock, a double tap on Pay bought 2 seats.

Both are fixed. Every opening of the sheet gets a session number, and a read or wallet prompt from an older session can no longer write into, bind handlers on, or close the current one. The sheet also locks before the wallet prompt. The evidence folder keeps the failing Playwright runs (the old sheet code, and the code with the lock removed: double tap bought 2 seats) next to the passing run on the current code. If your contract is airtight, look at the code that decides which transaction gets sent.

The numbers, briefly

  • 74 forge tests: 50 on mocks (unit, fuzz, an invariant suite), and 24 that read live mainnet state for QUSDC, QIEDEX, Zone and the Oracle. 100% line, statement, branch and function coverage on src/.
  • 204 web unit tests at 100% coverage, plus 42 Playwright tests run against live mainnet reads.
  • A mutation check: 5 of 5 injected bugs caught.
  • On a fork, 12 QIE joins paid a median of +564 bps over the Oracle's fair value (guard: 1,500).
  • All 20 go-live transactions succeeded. QIE blocks took about 3.6 s on average (3,596 ms from Blockscout stats).

Reproduce it without any keys: forge test -vv forks QIE mainnet through the public RPC.

Honest limits

  • No real users yet. The only mainnet pools are my two demo pools. Every member wallet in them is mine and is labelled "builder wallet" in the app. The PAID pool paid my own name, qkulk75527.qie, not a real seller.
  • Gas and slippage figures not marked mainnet were measured on a fork.
  • Distinct wallets are not distinct people. Any usage count I publish counts wallets.
  • QUSDC's issuer holds a VAULT_ROLE and can burn escrowed tokens. If that happens a pool cannot make everyone whole. Patungan then refuses new joins (an Insolvent revert; isSolvent() exposes the check) while refunds stay open. It has no admin key of its own.
  • Refunds come back in QUSDC, even if you joined with QIE.

Try it

No wallet is needed to check any of this. The pool pages and /verify are read-only calls against the mainnet contract.

If you run a group that splits a booking every week, I would like to hear whether this matches how your group actually pays.

Top comments (0)