THAMER
Sovereign Bitcoin Wallet

WALLET AI BITCOIN

Your Bitcoin Wallet. Your Keys. Your Engine.

Self-hosted Bitcoin software built for developers, applications, and AI agents.

CREATE WALLET

Bitcoin Refund Workflows: Reserve Before Authorization

permalink THAMER
#ai-agents#bitcoin#commerce#python

Bitcoin Refund Workflows: Reserve Before Authorization

Prevent overlapping refund requests from exceeding recorded receipts.

Design and trust boundary

A refund is a new Bitcoin transaction, not a reversal. Never infer a refund destination from transaction inputs. Verify the customer destination and authorize the exact sender debit separately under the signed wallet fee law. Keep uncertain refunds reserved until reconciled.

Independent reference implementation

Python · 31 lines
1import sqlite3
2
3def reserve(db, refund, order, sat):
4    if type(sat) is not int or sat <= 0:
5        raise ValueError('invalid amount')
6    db.execute('BEGIN IMMEDIATE')
7    try:
8        old=db.execute('SELECT order_id,sat FROM refunds WHERE id=?',(refund,)).fetchone()
9        if old is not None:
10            if old != (order,sat): raise ValueError('refund conflict')
11        else:
12            received=db.execute('SELECT sat FROM receipts WHERE id=?',(order,)).fetchone()
13            used=db.execute('SELECT COALESCE(SUM(sat),0) FROM refunds WHERE order_id=?',(order,)).fetchone()[0]
14            if received is None or sat > received[0]-used: raise ValueError('refund limit')
15            db.execute('INSERT INTO refunds VALUES (?,?,?)',(refund,order,sat))
16        db.commit()
17    except Exception:
18        db.rollback()
19        raise
20
21db=sqlite3.connect(':memory:',isolation_level=None)
22db.executescript('CREATE TABLE receipts(id TEXT PRIMARY KEY,sat INTEGER); CREATE TABLE refunds(id TEXT PRIMARY KEY,order_id TEXT,sat INTEGER); INSERT INTO receipts VALUES ("o1",1000);')
23reserve(db,'r1','o1',700)
24reserve(db,'r1','o1',700)
25try:
26    reserve(db,'r2','o1',400)
27except ValueError:
28    pass
29else:
30    raise AssertionError('over-refund')
31db.close()

Operational boundaries

Run with Python 3. Assertions use synthetic data only. No wallet credentials, SEND or live API calls are included. Preserve the WAB Engine API and immutable signed fee law. Amounts are integer satoshis. Production use requires authenticated inputs, durable state and independent authorization. This is a proposed application pattern, not a production financial system.

Related research

https://thamer.org/learn/bitcoin-for-ai-agents-open-integration-guide

https://thamer.org/api

Questions & Answers

Explore all questions →

Latest from the Lab

THAMER illustrated developer portrait and signature

ABOUT THE DEVELOPER

Independent Software Developer specializing in Bitcoin Script, Golang, and AI Agents.

Software engineering · Independent research · Open-source projects