peptide-escrow
A buyer deposits payment for a peptide batch into this Souk's PeptideEscrow contract. A warehouse inspects the delivery, and the Amin (this Souk's AI agent) checks the lab certificate against the standard that buyer and vendor agreed. The Amin then releases the payment to the vendor or refunds the buyer.
Roles: buyer, vendor, warehouse, organizer. To try it, tell your AI agent "create a Souk from peptide-escrow", or run:
python3 ~/souk.py create --template peptide-escrow --name "My Souk"
Everything below is public. A Souk's program can't hide its rules from its members.
Guide
## Peptide escrow
A buyer deposits payment for a peptide batch into this Souk's PeptideEscrow contract. A warehouse inspects the delivery, and the Amin (this Souk's AI agent) checks the lab certificate against the standard that buyer and vendor agreed. The Amin then releases the payment to the vendor or refunds the buyer.
If listed, this Souk accepts `souk_join` as `buyer` only, regardless of requested roles. Joining grants no funds or additional powers; all existing role, evidence and payment requirements still apply.
**Roles**
- `buyer`: opens and funds the order on chain, then submits it.
- `vendor`: ships the batch and is paid on release.
- `warehouse`: inspects the delivery and reports evidence.
- `organizer`: brings people in and takes no part in an order.
The creator is an organizer and holds no other role. An organizer can invite with any roles, `souk_invite(souk_id, email_or_person, roles)`; any other member gives only roles they hold themselves. The vendor and warehouse must already be members before the buyer submits the order.
**Before you start**
- You sign on chain with a wallet of your own; Souk never holds it. On a test deployment (Dev or Staging) the chain is a test chain, ID 31337, at `https://<test-host>/api/dev/chain`; `curl -s https://<test-host>/api/dev/faucet -H 'Content-Type: application/json' -d '{"address":"<your wallet>"}'` sends test ETH and 10,000 TestUSD. The examples use Foundry's `cast` (`cast wallet new` makes a key); any EVM wallet works.
- The buyer and vendor link their wallets here, since the program knows them on chain only by those. Sign the text `Link this wallet to <your person ID> in Souk <souk_id>` (your person ID is `person` in `souk_list`) with `cast wallet sign --private-key <key> "<the text>"`, then send `souk_send(souk_id, kind="wallet", text='{"signature":"0x…"}')`. The reply names the wallet linked. A wallet links to one member. The warehouse can be named by person ID instead of a wallet.
- The contract address and token are `address` and `token` in the `ChainDeployed` row of `souk_inbox`. Amounts are in TestUSD with 6 decimals. Each on-chain step is one `cast send <address> "<function>" <arguments> --rpc-url <rpc> --private-key <key>`.
**Buyer**
1. Agree a release standard with the vendor, for example `{"lab_host":"lab.example.com","purity":98}`. `lab_host` is the hostname the certificate must come from. Every other key is a criterion: `purity` and `fill` are minimums, `endotoxin` is a maximum, `{"min":…,"max":…,"unit":…}` gives explicit bounds, and any other value must match exactly.
2. On chain, `approve(address,uint256)` the token for the contract, then call `open(bytes32,address,uint256,uint64,bytes32)`: order id, the vendor's wallet, amount, deadline and `ruleHash`. Here `ruleHash` is the keccak256 of `json.dumps(standard, sort_keys=True, separators=(",",":"))`, and `deadline` is a future Unix time on the chain's clock.
3. With no thread: `souk_send(souk_id, text='{"order_id":"0x…","vendor":"<vendor person-id or linked wallet>","warehouse":"<warehouse person-id or linked wallet>","amount":2000000,"deadline":1794268800,"release_standard":{"lab_host":"lab.example.com","purity":98},"batch":"BPC-1A2B","certificate":"https://lab.example.com/coa/BPC-1A2B"}')`. Every field except `certificate` is required by the program. The Amin needs `certificate`, so include it. An order ID is read in lowercase, so one order has one thread however you case it.
4. If the order cannot open, the reply names the failed check: wallet ownership, funding, release standard, amount, deadline, vendor, warehouse, or an already-open order. Ownership is checked first, so only the linked payer receives details about the other checks. Correct the named field and resend, or use the existing thread. If the message is not an order the program can read, the Amin explains what is missing in your private help thread. Otherwise a thread opens for you, the vendor and the warehouse, and its first post states the batch, amount, deadline and release standard. When it settles, the thread gets the post `Order 0x…: released.` or `refunded.`, with whether the certificate passed; the evidence stays private.
5. Release must happen before the deadline. After the deadline, anyone can call `refund` on the contract. A day after the deadline the Souk reads the contract once: if the order has been refunded by then, the thread gets the post `Order 0x…: refunded.` and closes. A refund made after that read is reported when the next inspection tries to settle the order.
**Warehouse**
1. In the thread, send your inspection with photos: `souk_send(souk_id, thread_id="<thread-id>", text="Inspection at <time>, order 0x…, batch BPC-1A2B: label matches, seal intact, no damage. Certificate: <url>", files=[{"path":"seal.png"}])`. Each of your messages starts an inspection.
2. The Amin may ask each member once per order, across all inspections. If the Amin sends you a question card, answer it with `souk_answer`. Your answers also start an inspection.
3. Messages from the buyer and vendor don't start an inspection; the Amin reads them the next time one starts. An answer to the Amin's question card does start one, whoever gives it.
4. The Amin fetches the certificate (it must be `https://<lab_host>/…`) and records a finding. It releases the payment only when that finding is qualified and the certificate it cites passes the standard, and refunds only when the finding is disqualified. The finding cites the certificate the Amin read last when recording it, so a later read can't replace it; the certificate's order and batch must match this order's, ignoring case and outer spaces. An unresolved finding leaves the order pending, and the thread gets a notice when the inspection ends without settling. If a release or refund landed on chain but its receipt never came back, the next inspection reports what landed instead of sending again, so a warehouse message or answer closes the order. On a test deployment (Dev or Staging), a test stand-in certificate is at `https://<test-host>/api/dev/peptide-coa/<batch>?order_id=<order_id>`, with `lab_host` set to its hostname. A batch containing `FAIL` fails.
**Vendor**
- Link the wallet the buyer pays to (see above). You can send evidence in the thread. On release, `amount` goes to that wallet.
**What stays private:** No other member sees your messages. Thread members see only the program's posts, and question cards addressed to them. The Amin is told not to quote one participant's message to the others.
**Money:** The payment is TestUSD held in the contract. The Souk signer releases or refunds it. There are no Souk credits.
The Amin is an AI that follows this Souk's published rules (`souk_program` shows them). Replies can take a few minutes.
**Program changes:** The creator can change anything after this Souk's notice, one day
unless its creator chose otherwise at launch (`souk_program` shows it), including access to old sealed data and Souk-wide value. Read the
current and pending bundles with `souk_program`; your inbox announces the effective
time. If you disagree, stop taking part and settle during the notice using this program's
actions; the host provides no additional exit path. Being offline for the whole
notice is not protected. Before anyone else joins, changes are immediate.
Rules (the program the host runs)
"""Buyer deposit, warehouse inspection, then guarded release or refund."""
import json
import souk_governance as governance
from souk import (
WORKSPACE_TOOLS,
Answer,
Invite,
JoinRequest,
Message,
RunFinished,
RunInterrupted,
Timer,
ToolDone,
admit,
allow,
call,
deny,
modify,
open_thread,
post,
reply,
run,
set_timer,
store,
)
from souk_budget import ask_refusal
REVISION_NOTICE = 86400
KITS = ("chain", "budget", "governance")
# Follow-up questions the Amin may put to each member in one order.
ASKS_PER_MEMBER = 1
CONTRACT = "PeptideEscrow"
# Anvil's ID: Dev and Staging run this disposable test chain for the Souks that name it.
CHAIN_ID = 31337
LINK_HOW = (
"To link your wallet, sign this text with it (EIP-191, as `cast wallet sign` does) and "
'send {"signature": "0x…"} with kind "wallet": '
)
# An organizer brings people in and takes no part in an order.
ROLES = ("buyer", "vendor", "warehouse", "organizer")
CREATOR_ROLES = ("organizer",)
# The public refund only opens at the deadline, so a read at the deadline would miss it.
REFUND_READ_AFTER = 86400
def identifier(value):
"""One spelling of an order or batch ID: its case and padding mean nothing."""
return value.strip().casefold() if isinstance(value, str) else value
def parse_order(text):
try:
order = json.loads(text)
fields = (
"order_id",
"vendor",
"amount",
"deadline",
"release_standard",
"batch",
"warehouse",
)
if (
isinstance(order, dict)
and all(k in order for k in fields)
and all(
isinstance(order[k], str) and order[k].strip()
for k in ("order_id", "batch", "vendor", "warehouse")
)
):
# The batch keeps its spelling for posts; comparisons go through identifier().
return order | dict(
order_id=identifier(order["order_id"]), batch=order["batch"].strip()
)
return None
except ValueError:
return None
def wallet_text(souk, person):
"""What a member signs with their wallet to link it to themselves in this Souk."""
return f"Link this wallet to {person} in Souk {souk}"
def wallets(s):
"""{person: address}: the wallet each member last linked here."""
return {
r["wallet_of"]: r["wallet"]
for r in s.resident_fields("wallet_of", "wallet")
if "wallet_of" in r
}
def wallet_member(s, address):
"""The member who linked this wallet, if anyone has."""
person = next(
(p for p, w in wallets(s).items() if address and w.lower() == address.lower()),
None,
)
return s.member(person)
def link_wallet(e):
"""kind "wallet" carries {"signature": ...}, the wallet's signature of wallet_text."""
try:
body = json.loads(e.text)
except ValueError:
body = None
signature = body.get("signature") if isinstance(body, dict) else None
text = wallet_text(e.souk, e.sender.person)
if not isinstance(signature, str):
return [reply(e.sender, LINK_HOW + text)]
return [call("chain.recover", text=text, signature=signature)]
def wallet_linked(e, s):
sender = s.message(e.cause).sender
text = wallet_text(e.souk, sender.person)
if e.state != "done" or e.args.get("text") != text:
return [
reply(
sender,
"No wallet was linked: that isn't a signature of the text. "
+ LINK_HOW
+ text,
)
]
address = e.result["address"]
holder = wallet_member(s, address)
if holder and holder.person != sender.person:
return [reply(sender, f"{address} is already linked to another member here.")]
return [
store(dict(wallet_of=sender.person, wallet=address), resident=True),
reply(sender, f"Linked {address} to you in this Souk."),
]
def cited_lab(t):
"""The certificate the release finding rests on: a later read can't replace it."""
cited = (t.record("release") or {}).get("certificate")
if cited:
return next(
(
lab
for lab in reversed(t.tool_results("lab.coa"))
if lab.get("certificate") == cited
),
None,
)
return t.tool_fact("lab.coa")
def on_event(e, s):
if isinstance(e, JoinRequest):
return [admit(e.requester, ("buyer",))]
if isinstance(e, RunInterrupted) and e.thread:
# the failure itself stays in the event log
t = s.thread(e.thread)
if t.flag("settled"):
return []
return [
post(
t.id,
f"Order {t.data['order_id']}: the Amin stopped before finishing this "
"inspection, so the order stays pending. The warehouse can send more "
"evidence to start another; after the deadline anyone can refund it on "
"the contract.",
)
]
if isinstance(e, Invite):
# An organizer admits with any role; anyone else gives only roles they hold.
if "organizer" in e.sender.roles or set(e.roles) <= set(e.sender.roles):
return [admit(e.invitee, e.roles)]
return [reply(e.sender, "You can only invite with roles you hold.")]
if isinstance(e, Message) and e.thread is None and e.kind == "wallet":
return link_wallet(e)
if isinstance(e, ToolDone) and e.tool == "chain.recover" and e.origin == "program":
return wallet_linked(e, s)
if isinstance(e, ToolDone) and e.state != "done":
return []
if isinstance(e, Message) and e.thread is None and "buyer" in e.sender.roles:
order = parse_order(e.text)
if not order:
# Not an order: the host's help thread lets the Amin answer.
return []
return [
call(
"escrow.read",
order_id=order["order_id"],
release_standard=order["release_standard"],
)
]
if (
isinstance(e, ToolDone)
and e.tool == "escrow.read"
and e.thread is None
and e.origin == "program"
):
original = s.message(e.cause)
order = parse_order(original.text)
sender = original.sender
result = e.result
linked = wallets(s)
buyer = wallet_member(s, result.get("buyer"))
# The order names its vendor by person ID or wallet; the contract pays the wallet.
vendor = wallet_member(s, result.get("vendor"))
if not (
vendor
and "vendor" in vendor.roles
and order["vendor"].lower()
in {vendor.person.lower(), linked[vendor.person].lower()}
):
vendor = None
warehouse = next(
(
m
for m in s.members_with("warehouse")
if order["warehouse"] == m.person
or order["warehouse"].lower() == linked.get(m.person, "").lower()
),
None,
)
checks = [
(
buyer and buyer.person == sender.person,
"This order wasn't paid from a wallet you linked here. Check the order ID, "
"or link the wallet you paid from. "
+ LINK_HOW
+ wallet_text(e.souk, sender.person),
),
(result.get("funded"), "This order is not funded."),
(
result.get("rule_hash")
and result.get("rule_hash") == result.get("standard_hash"),
"The release standard does not match the funded order.",
),
(
result.get("amount") == order["amount"],
"The amount does not match the funded order.",
),
(
result.get("deadline") == order["deadline"],
"The deadline does not match the funded order.",
),
(
vendor,
"The vendor ID or wallet does not match a joined vendor who linked the order's "
"vendor wallet.",
),
(
warehouse,
"The warehouse ID or wallet does not match a joined warehouse.",
),
(
not s.thread_for(order["order_id"]),
"This order already has a thread; use that thread.",
),
]
for matches, problem in checks:
if not matches:
return [reply(sender, problem)]
return [
open_thread(
Message(
sender,
original.text,
souk=e.souk,
at=e.at,
id=e.cause,
),
members=[sender, vendor, warehouse],
data=order | {"warehouse": warehouse.person},
key=order["order_id"],
),
# The buyer's message stays theirs, and these terms are what the order is held to.
post(
"new",
f"Order {order['order_id']}: batch {order['batch']}, amount "
f"{order['amount']}, deadline {order['deadline']}, release standard "
f"{json.dumps(order['release_standard'], sort_keys=True)}.",
),
set_timer(
at=order["deadline"] + REFUND_READ_AFTER, name="deadline", thread="new"
),
]
t = s.thread(e.thread) if e.thread else None
if t is None:
return []
if isinstance(e, Timer) and e.name == "deadline" and not t.flag("settled"):
# One read: a public refund after it waits for the next inspection to report it.
return [call("escrow.read", order_id=t.data["order_id"])]
if (
isinstance(e, ToolDone)
and e.tool == "escrow.read"
and e.origin == "program"
and e.result.get("state") == "refunded"
and not t.flag("settled")
):
return [
t.set_flag("settled"),
post(
t.id,
f"Order {t.data['order_id']}: refunded. The contract shows the buyer "
"was refunded, so this order is closed.",
),
]
# The warehouse's evidence starts an inspection, and so does anyone's answer to the Amin's
# question: it asked the buyer or vendor because the finding waits on what they say.
if not t.flag("settled") and (
(isinstance(e, Message) and e.sender.person == t.data["warehouse"])
or isinstance(e, Answer)
):
return [
store(e),
run(
"prompts/inspect.md",
see=["thread"],
tools=[
"lab.coa",
"ask",
"record",
"escrow.release",
"escrow.refund",
*WORKSPACE_TOOLS,
],
),
]
if (
isinstance(e, RunFinished)
and e.prompt == "prompts/inspect.md"
and not t.flag("settled")
):
return [
post(
t.id,
f"Order {t.data['order_id']}: this inspection ended without a settlement, "
"so the order stays pending. An answer to a question card from the Amin, or "
"more evidence from the warehouse, starts another; after the deadline anyone "
"can refund it on the contract.",
)
]
if isinstance(e, ToolDone) and e.tool in ("escrow.release", "escrow.refund"):
return [
t.set_flag("settled"),
post(
t.id,
f"Order {e.result['order']}: {e.result['state']}. "
+ settled_because(t, e),
),
]
if isinstance(e, Message) and t.flag("settled"):
return [
store(e),
reply(
e.sender,
f"Order {t.data['order_id']} is settled, so nothing more can change it.",
),
]
if isinstance(e, Message) or (isinstance(e, Answer) and not t.flag("settled")):
return [store(e)]
return []
def settled_because(t, e):
# Rendered from the certificate's verdict, never from the Amin's reason or evidence.
batch = t.data["batch"]
if e.result["state"] != ("released" if e.tool == "escrow.release" else "refunded"):
# The contract had already settled the other way, say by the public refund.
return "The contract had already settled this order, so this finding didn't decide it."
if e.tool == "escrow.release":
return (
f"The certificate for batch {batch} passed the agreed standard, and the funds "
"went to the vendor's linked wallet."
)
if cited_lab(t)["passes"]:
return (
f"The certificate for batch {batch} passed the agreed standard, but the "
"Amin disqualified the order on evidence that stays private."
)
return f"The certificate for batch {batch} did not pass the agreed standard."
def before_tool(c, s):
if c.tool == "revise":
return governance.creator(c)
if c.origin == "agent" and c.tool == "ask":
reason = ask_refusal(c, s, ASKS_PER_MEMBER)
if reason:
return deny(reason)
if (
c.tool in ("escrow.release", "escrow.refund", "record", "ask")
and s.thread(c.thread)
and s.thread(c.thread).flag("settled")
):
return deny("This order is already settled; nothing more can change it.")
if c.tool == "record" and c.args.get("finding") == "release":
# The finding cites the certificate read last, so what it decided on stays named.
t = s.thread(c.thread)
lab = t and t.tool_fact("lab.coa")
if lab and c.args.get("certificate") != lab.get("certificate"):
return modify(**{**c.args, "certificate": lab.get("certificate")})
if c.tool in ("escrow.release", "escrow.refund"):
t = s.thread(c.thread)
finding, lab = t.record("release"), cited_lab(t)
if identifier(c.args.get("order_id")) != identifier(t.data["order_id"]):
return deny("Settlement must name this thread’s order.")
if finding is None or lab is None:
return deny("Check the lab result and record the release finding first.")
if identifier(lab.get("batch")) != identifier(t.data["batch"]) or (
identifier(lab.get("order")) != identifier(t.data["order_id"])
):
return deny("The certificate must match this order and batch.")
if c.tool == "escrow.release" and not (
finding["state"] == "qualified" and lab["passes"]
):
return deny("Release needs a qualified finding and a passing lab result.")
if c.tool == "escrow.refund" and finding["state"] != "disqualified":
return deny("Refund needs a disqualified finding.")
return allow()
What the Amin is told: prompts/inspect.md
Check the COA against the order's release standard and the warehouse evidence.
The certificate comes from the lab host that buyer and vendor committed to in the
order's on-chain terms, and the host has already verified that, so judge the
certificate's content, not the lab's identity or URL.
You may ask each member for missing evidence once per order across all inspections;
combine what you need in that question, then decide on what you have.
Record `release` as qualified, disqualified,
or unresolved, with reasons. Disqualify on a failed certificate or damage you can state
plainly; a photo that only looks odd after analysing its pixels is doubt, so that's
unresolved. Then release a qualified order or refund a disqualified order; leave an
unresolved order pending.
Each participant's messages are private to them: never quote one participant's
notes to another. If a settlement call is denied, read its reason and fix that.
This order's messages and files are already in your context. Use the workspace only for computation reading cannot do.
Each workspace call is slow; run code there rather than exploring.