A commerce ecosystem on NEAR testnet that protects three paths — trade, delivery and AI co-pilot payments — with one wallet and one on-chain trust layer.
Buyers do not send money to an unknown seller before goods ship. Sellers know the buyer funded the deal. Logistics gets paid only when carrier pickup is TEE-verified; the seller releases on explicit buyer confirmation — or, if the buyer stays silent, when the on-chain inspection window elapses. The platform fee is disclosed before funding, and the platform relayer runs this pipeline with no wallet signatures in the happy path.
The ecosystem coordinates three protected paths for physical commerce:
- Protected trade — marketplace listings, NEP-413 wallet identity, and Trustcrow escrow (SWEEFT's escrow infrastructure on NEAR): fixed beneficiaries, inspection windows, refunds and dispute routes.
- Verified delivery & settlement — a signed carrier timeline, OutLayer Intel-TDX verification of the delivery report, then contract-gated payouts to logistics, seller and the platform treasury.
- Co-pilot commerce — NEAR AI Cloud turns natural language into proposals; a native-NEAR budget
contract enforces the user's allowance, and the agent's function-call key can invoke only
pay.
One wallet connects the whole ecosystem: marketplace listings → on-chain trust profile → escrow → verified logistics → settlement → reputation. Every reputation number is contract-derived and recomputable by anyone — the marketplace is discovery, the chain is the truth.
CONNECT WALLET → BROWSE / LIST → CHECK TRUST PROFILE → ESCROW
→ ACCEPT → FUND (native NEAR) → SHIP → TEE-VERIFY (AUTOMATIC)
→ SETTLE (seller + logistics + platform) → REPUTATION MOVES
Integrated NEAR & partner tools: NEAR contracts (Rust/near-sdk) for escrow and budgets · NEP-413 + Wallet Selector (Meteor/HERE/Nightly) for signing · OutLayer Intel-TDX for genuine delivery attestation · Sputnik DAO/Trezu for the review board and treasury · NEAR AI Cloud for the co-pilot · native-NEAR budget + scoped function-call keys for agent payments · NEAR testnet RPC and NearBlocks for public verification · near-workspaces and cargo-near for sandbox tests and reproducible builds · a key-authenticated Demo Carrier partner API for simulated, ed25519-signed tracking (not a real carrier integration).
Built at NEAR Hackathon (Nov 2026).
| Component | Status |
|---|---|
| Escrow + authorization + settlement | Real — Trustcrow, the Rust escrow contract on NEAR testnet (sweeft-eco.testnet) |
| Funding currency | Native NEAR — payable fund_escrow; no token mint, import, or registration |
| Wallet identity + authorization | Real — NEP-413 signature + on-chain access-key ownership verified server-side; every financial action traces to a signed transaction |
| Delivery verification | Real TEE + carrier signatures — OutLayer (Intel TDX) runs our published verifier; the carrier report must be ed25519-signed by the Demo Carrier service, whose public key is registered on-chain (set_carrier_pubkey), so callers cannot forge carrier data from public ids. The verifier additionally enforces shipment id, provider id, timeline and pickup-before-delivery. Carrier data itself remains simulated Demo Carrier |
| Verification & settlement automation | Real on-chain — the platform relayer (manage.py run_relayer) triggers permissionless TEE verification, the logistics payout, and the inspection-window release; the contract state machine gates every call and fixes every destination/amount |
| Carrier tracking data | SIMULATED — Demo Carrier; labelled SIMULATED DATA in the DB (simulated=True), API responses and UI |
| Platform fee | Real — 5% of seller amount, enforced by the contract, paid at completion |
| AI co-pilot payments | Real on-chain — scoped, revocable native-NEAR budget (budget.steepdata3968.testnet); the agent pays only within the user's deposited limit |
| Dispute arbitration pool | Disabled — no deployment with a review board exposes it (sockpuppet-votable, no slashing); disputes resolve ONLY through the board |
| Review board (Sputnik DAO) | Real, demo council — disputes resolve ONLY via council-approved on-chain proposals (2-of-3). On testnet all three council members are operated by this project; production would use independent members with hardware/multisig keys |
| Treasury (DAO multisig) | Real — platform fees accrue to the board account; spending requires a council-approved Transfer proposal |
| Fiat payouts / real carriers | Not implemented (out of MVP scope) |
Boundaries we state plainly: a carrier scan does not prove parcel contents; the buyer can confirm receipt early or report a problem at any time; a silent buyer's funds release only after the on-chain inspection window — and a reported problem freezes them into the review path.
Current deployment: escrow contract sweeft-eco.testnet,
review board sweeft-board.testnet (both keyless/immutable — deploy keys deleted), TEE project
steepdata3968.testnet/sweeft-verify, carrier key registered on-chain. Escrow ids are random
six-digit codes: SWFT-XXXXXX.
SWFT-995659 — 5kW Hybrid Solar Inverter Kit — completed the full lifecycle on this
deployment: signed-carrier TEE verification (the verifier rejects stale payloads via the signed
issued_at), logistics settled 0.001 NEAR, seller 0.01 NEAR, platform fee 0.0005 NEAR
to the board treasury, all payout flags true, and the terminal escrow left the active account
indexes:
SWFT-995659 step |
Tx (nearblocks.io/txns) |
|---|---|
create_escrow (seller) |
GZ2gZtsq87HBvYEiA6Ae5hF3cshw8GhN1hE5XkdbQP9r |
accept_escrow (buyer) |
7yq8yCmYiaEFhsSdgT1iiKex4mEbsvV2XoxKqZkL6E1F |
fund_escrow 0.0115 NEAR |
9P6hefQ2givF4pss9LGZ8sYrGrdfqgrirBwcCzEGR7NS |
assign_logistics_provider |
DZQ51HzwrUJPi9cGT83vFpcmqRVi48eXgzXQmL7ouWKK |
register_shipment |
4GYwzNWScpbHnAQLNggp9JCe6rprpnZ7npUHJkyoHaM7 |
| TEE verification (signed carrier payload) | 7x6oqLfqFNaCWhMjqj1DYSLTCze4cTo5wkVYA7D8iYAQ |
settle_logistics |
GVkTMuYRSkQj9bbpNk34hi6kjYNGiN1jzjuauotrRmAV |
confirm_receipt (buyer) |
5fzQWyYyTujqGVdaXf4R6jXkcCc6NWcroWrQF76aKWyu |
Earlier lifecycle SWFT-014021 proves the same state machine, and the co-pilot payment executed
during the demo run is Dt8oBwN3qQ2DWhj2vn8E9SV29yJ63WTCLRo4Pp86XhS4 (pay on
budget.steepdata3968.testnet, signed by the pay-scoped agent key).
Terminal-state coverage on the same deployment: reject_escrow (6D7wNr6zGqf3VWbYCua55vyPCw5PnpMm2PaeZ5pSooCz,
SWFT-747532), cancel_escrow (5VzEoAzUdiDaohS16vCu1sZu1PCNZmyjrY1yHB5jX2kt, SWFT-054544),
and buyer refund of an undispatched escrow after the dispatch deadline
(FVm51D6wCniXpPddTjriLZQ4dR4C8Yx3LVwb1Ju2Ejtd, SWFT-984999) — every terminal transition prunes the
active seller/buyer index, so the 50-escrow cap applies to active deals only.
The Django app-level E2E (/tmp harness, 36 checks: wallets → listings → purchase request → escrow →
TEE → settlement → disputes → AI co-pilot → pages) passes against this deployment, and the
near-workspaces sandbox test runs the same lifecycle locally with a stub OutLayer runner
(cargo test --test sandbox).
Deploy key deletion: Er5pEHC8Dx8vgSdTvrXKF685KjXTypS16aZH1qj5Wsso. The deployed WASM SHA-256 is
c4d0b2c4733fc846d69faee2d7b7058a8b612ea14e7212ca2b6d1a39cab3e284 — reproduce it with
cargo near build reproducible-wasm (pinned sourcescan/cargo-near:0.22.0-rust-1.99.1 image).
The OutLayer verification program (wasm32-wasip2) SHA-256 is
0b0358e0f93d1cc31e916822ab065bb57cbdd88072dc62eb824fe7a96bd0efa1 (upload tx
9mBMNUTYxEbnfcNkD9YrohqgUSSYTRpYq948s81PNsWr).
Board: sweeft-board.testnet — council 2-of-3
(steepdata3968 + seller.steepdata3968 + logistics.steepdata3968; a demo council operated by this
project on testnet). Disputes resolve only through council-approved resolve_review proposals; platform
fees accrue to the board treasury, and spending requires a council-approved Transfer proposal.
The escrow contract's get_gov_info shows arbiter/treasury = the DAO; the platform owner can appoint
the board but cannot resolve disputes — that power is gone by design.
contracts/sweeft/ Rust (near-sdk) escrow contract — funds & authorization source of truth
contracts/stub-outlayer/ Test-only OutLayer runner stub for the near-workspaces sandbox
contracts/near-budget/ Native-NEAR co-pilot budget (deposit / agent pay / withdraw)
wasi/sweeft-verify/ TEE verification program → wasm32-wasip2, published on OutLayer
sweeft/ Django modular monolith (product coordinator + projection)
apps/wallets/ NEP-413 challenge/verify, sessions
apps/escrow/ agreements, invitations, contract reads, settlement projection, relayer
apps/logistics/ partners, Demo Carrier, shipments, verification records
apps/market/ listings, purchase requests, trust profiles (/u/<wallet>/)
apps/ai/ provider-neutral AI (echo | openai_compat | anthropic) + co-pilot payments
templates/ static/ Django templates + HTMX + Alpine + Tailwind; wallet bundle
tools/web-bundle/ esbuild bundle of @near-wallet-selector (Meteor/HERE/Nightly)
tools/demo-carrier/ standalone Demo Carrier simulator — SIMULATED, partner-API only
scripts/ deploy + end-to-end scripts
Source-of-truth rule: the contract controls funds and permissions; Django coordinates the experience and keeps a searchable projection; carrier systems report events; OutLayer attests to the execution of the configured verification code; the buyer's confirmation remains a separate condition.
Escrows, marketplace prices, logistics fees, platform fees, and co-pilot budgets all use native NEAR. There is no project token to mint, import, or register.
- Already have testnet NEAR? Connect your wallet and go — the header chip shows your native balance.
- Fresh wallet? Click “Get test NEAR” in the header or dashboard to open the public NEAR testnet faucet. Any testnet wallet works.
New escrows pass token: "near" and fund with the payable fund_escrow method.
# 1. Django app (Python 3.10+)
cd sweeft
python3 -m venv .venv && source .venv/bin/activate # optional but recommended
python3 -m pip install -r requirements.txt
cp .env.example .env # testnet addresses + DEBUG=1, no secrets needed
python3 manage.py migrate
python3 manage.py seed_demo # optional: sample listings + Demo Carrier partner
python3 manage.py runserver 0.0.0.0:8000
# → http://localhost:8000Nothing secret is required to explore the app: wallet login, the marketplace, and on-chain escrow creation/funding/settlement with your own testnet wallet work without any server-side keys. Carrier TEE verification, the relayer loop and AI co-pilot payments light up only when their keys are set (each stays clearly marked as unconfigured otherwise).
Environment variables (.env, never commit real values):
| Variable | Meaning |
|---|---|
SWEEFT_CONTRACT |
deployed escrow account |
AI_BUDGET_CONTRACT |
native-NEAR co-pilot budget account |
OUTLAYER_CONTRACT / OUTLAYER_PROJECT |
OutLayer receiver + published verification project |
RELAYER_ENABLED / RELAYER_ACCOUNT / RELAYER_PRIVATE_KEY |
platform relayer (see below) |
NEAR_NETWORK, NEAR_RPC_URL, DJANGO_DEBUG, DJANGO_SECRET_KEY |
standard config |
The relayer (apps/escrow/relayer.py) drives the permissionless happy path on-chain: TEE
verification of the carrier report → logistics payout → inspection-window release. It calls only
methods whose destinations and amounts are fixed by the escrow, so the key can never redirect
funds. Fund a dedicated testnet account and set it in .env:
# in sweeft/.env
RELAYER_ENABLED=1
RELAYER_ACCOUNT=relayer.<your>.testnet
RELAYER_PRIVATE_KEY=ed25519:…
RELAYER_POLL_SECONDS=5 # optional
python3 manage.py run_relayer # loop; or --once for a single pass / cronWithout it, the escrow page keeps manual fallback buttons (wallet-signed) — the flow degrades gracefully. Testnet MVP only: on mainnet the key would live inside a TEE/KMS.
Scheduling: each pass drives a fast loop over non-terminal escrows in the local projection, plus a
full paged chain reconciliation every RELAYER_RECONCILE_SECONDS (default 300). The reconciliation
stores a high-water mark (the lowest creation index still non-terminal) and resumes from there —
new escrows only ever land past the end, so the scan does not walk the whole book every 5 minutes.
Every pass writes a heartbeat; /health/ returns 503 when the relayer is stale or has never
run, so uptime monitors can alert on paused settlement.
rustup target add wasm32-unknown-unknown wasm32-wasip2
cargo install cargo-near # or grab the prebuilt release
(cd contracts/sweeft && cargo near build non-reproducible-wasm --no-abi)
(cd contracts/near-budget && cargo near build non-reproducible-wasm --no-abi)
# deploy + init (see scripts/deploy_testnet.sh for the full flow)
near contract deploy <acct> use-file target/near/sweeft.wasm without-init-call ...
near contract call-function as-transaction <acct> new json-args '{...}' ...curl -fsSL https://raw.githubusercontent.com/out-layer/outlayer-cli/main/install.sh | sh
# (or: cargo install outlayer-cli)
outlayer login testnet
(cd wasi/sweeft-verify && cargo build --target wasm32-wasip2 --release)
outlayer upload wasi/sweeft-verify/target/wasm32-wasip2/release/sweeft-verify.wasm
outlayer deploy sweeft-verify <FastFS URL printed by upload>cd tools/web-bundle && npm install && npm run build # writes sweeft/static/js/sweeft-wallet.jsThe repo ships a Render blueprint: a Python web service plus a managed Postgres,
with WhiteNoise serving static files and migrations applied during the build. start.sh also runs
the relayer and standalone Demo Carrier loops beside the web process when their credentials are
configured, so the free-plan demo does not require separate paid workers.
- Push this repo to GitHub, then in Render choose New + → Blueprint and pick the repo.
- Apply — Render creates the database, generates
DJANGO_SECRET_KEY, and wiresDATABASE_URL, allowed hosts and TLS cookies. It prompts for thesync: falsesecrets (carrier signing key, carrier API key, co-pilot agent key and relayer key); paste them fromsweeft/.env. - Seed the hosted demo once from the Render Shell:
python manage.py seed_demo --issue-carrier-key. Put the printedswft_…credential inDEMO_CARRIER_API_KEYand restart the service. Without credentials the manual on-chain fallbacks still work; no carrier events or relayer calls are faked. - Open the service URL — the footer shows the live contract account.
Free-plan notes: the web service spins down when idle (the first request warms it up), including its
companion automation loops. Keep settlement running by pointing an external uptime monitor at
/health/ every 5 minutes — the ping both prevents spin-down and alerts, because the endpoint
returns 503 whenever the relayer heartbeat is stale or missing (/health/live/ is the always-200
platform liveness probe Render itself checks). On paid plans, uncomment the sweeft-relayer worker
in render.yaml (background workers start at $7/month compute) and set RELAYER_ENABLED=false on
the web service, so settlement runs independently of web traffic.
Confirm the proxy hop count before trusting client IPs: set DJANGO_PROXY_DEBUG=1, hit
/health/ once, and read the proxy-debug … line in the Render logs (raw X-Forwarded-For,
REMOTE_ADDR, resolved client IP). Set TRUSTED_PROXY_COUNT to the number of trusted hops you see
(Render = 1), then unset the flag.
- Connect a wallet (Meteor / HERE / Nightly — sign the free NEP-413 message to sign in).
- Marketplace: browse
/market/, open a listing, inspect the seller's trust profile (/u/<wallet>/— live contract reputation), then "Request to buy via escrow". - The seller sees the purchase request under
/market/mine/and creates the escrow — prefilled from the listing — with a wallet-signedcreate_escrow. When creating directly, the seller explicitly picks the acceptance policy: only a specific wallet (the contract rejects every other account) or an invite link (only its sha256 is committed on-chain). - Buyer accepts, then funds the exact total in native NEAR. Logistics is assigned and the Demo Carrier tracking number is registered.
- Dispatch starts the carrier run: at "Mark dispatched" pick a scenario (
deliveredin ~60s, orfailed/lostfor dispute demos). The standalone Demo Carrier simulator plays receive → transport → deliver over the partner API; the escrow page shows the live timeline. - The platform relayer runs the settlement pipeline automatically (start it once:
python3 manage.py run_relayer): when the carrier reports delivery it requests the OutLayer TEE verification; when the attested result lands it pays logistics; after the inspection window it releases seller + platform — no wallet signatures in the happy path. The buyer can confirm receipt early, or report a problem at any moment: that freezes the funds into the review path. - With settlement complete the listing flips to
soldand reputation moves on-chain for both wallets — visible instantly on their profiles. Platform fees land in the review-board treasury. - Governance: while an escrow is
ReviewRequired, either party can Escalate to the review board from the escrow page — a wallet-signed DAO proposal (resolve_review); council members approve on/governance/; at 2-of-3 the DAO executes the split on-chain. The arbitration pool is disabled in every deployment with a board (it was exploitable via sockpuppet voting and has no slashing); the review board is the only resolution path.
Scripted version of the escrow path: scripts/e2e_lifecycle.sh.
The carrier is a standalone service, not part of Django: it talks only to the key-authenticated
partner API (the same surface a real GIG/DHL/FedEx integration would use) and holds no database
state. Start it next to runserver:
python3 manage.py seed_demo --issue-carrier-key # one-time: prints the swft_… key
SWEEFT_BASE_URL=http://127.0.0.1:8000 DEMO_CARRIER_API_KEY=swft_… \
python3 tools/demo-carrier/simulator.pyIt gates on the on-chain Shipped state, then POSTs scans at +5s ACCEPTED, +15s PICKED_UP,
+30s IN_TRANSIT, +45s OUT_FOR_DELIVERY, +60s DELIVERED (per-shipment scenario may instead
end DELIVERY_FAILED at +60s or LOST at +30s). Server-side transitions are idempotent and
forward-only, so retries and restarts cannot corrupt the timeline OutLayer validates. If the
simulator is down, shipments wait at CREATED and the UI says so — nothing else breaks.
The co-pilot is a first-class part of the product (floating 💬 panel on every page, plus a homepage section). It operates on real marketplace data through a strict tool registry — read tools never write, and every state-changing tool enforces session authorization and records its result:
- Discovery — “find me a laptop with 16 GB RAM under 5 NEAR” → requirements + budget are
extracted,
search_listingsranks actual active listings by match and seller reputation, and the reply renders selectable product cards with reasons. - Comparison — “which of these is better value?” →
compare_listingsreturns price/spec/seller rows with pros, from real listing data only. - Offers & negotiation — “offer 4.2 NEAR for this laptop, I can go to 4.8” → the co-pilot creates
a real marketplace Offer (
proposed → countered → accepted/rejected/withdrawn) with the buyer's ceiling recorded. Sellers accept/reject/counter on/market/mine/; buyers instruct the co-pilot to counter (“counter with 4.5”) and the ceiling is enforced server-side — the agent cannot exceed it, and asks for new authorization when the seller pushes past it. Accepted offers prefill the escrow at the agreed price (“Create escrow (agreed price)”). - Payment preparation & execution — “pay the seller for this accepted offer” → a payment card
shows recipient, amount and available budget; nothing moves until you click Pay/authorize.
The agent then calls
pay(owner, receiver, amount, intent_id)onbudget.steepdata3968.testnet; every execution is audited as aPaymentIntent. - Escrow & monitoring — “where is my order / is the escrow still active / when can funds
release?” →
get_my_trade_statusreads actual chain + shipment + verification state and renders order cards (pending / shipped / verified / awaiting confirmation / settled). - Execution feedback — tool activity is shown as concise named steps (“Searching marketplace”, “Preparing offer”, “Checking budget”, “Preparing payment”) with 🔎 read / ⚙ prepare / ⚡ action badges; results appear as cards (products, comparisons, offers, payments, escrows) inside the conversation.
Payment safety: proposals now expire (AI_PAYMENT_INTENT_TTL_SECONDS, default 15 min) and a
crashed execution is reclaimable after AI_PAYMENT_PROCESSING_TIMEOUT_SECONDS; amounts and
recipients are immutable per intent, one session can only execute its own intents, and the
on-chain intent id makes duplicate execution impossible even across retries.
The agent key is a function-call access key scoped to pay on the budget contract only
(allowance-capped, full-access key removed — tx 4HPRtHBYHJR7uemWd26e2erL6S6SBd1pWgYubGaTrrWJ).
Since the 2026-11 hardening upgrade (tx 2UteeXb3ci15ZEf4XbwVzNVywYRcPCKQgCvMDXg3jx5B) the contract
also supports per-owner agent authorization (set_my_agent/get_owner_agent/is_revoked) and
rejects duplicate intent_ids on-chain. Existing budgets were preserved across the upgrade; the
dashboard’s co-pilot budget card authorizes the agent per wallet with one signature.
Verified live: agent pay executed with "intent_id": "14" in the transaction args (tx
DfJCDKu85garMiSSBBYxAen43dYx4wSonZ5w6PC6G18R); replay of the same intent returns the cached
receipt; over-cap and no-budget paths refused correctly.
/governance/— board account, council members + threshold, all proposals with votes and statuses, treasury balance, treasury Transfer proposals, and the on-chain wiring (arbiter/treasury).- Escrow page — “Review board” panel appears while a dispute is open: escalation form for the parties, Approve/Reject for council members, live vote chips.
- Contract —
get_gov_info,set_arbiter,set_treasury(+ 7 Rust unit tests for the authorization rules) and permissionlessretry_platform_payoutfor failed fee transfers.
A pre-submission review surfaced real exploit paths; all critical findings are fixed and verified on-chain:
| Finding | Fix |
|---|---|
| Seller sockpuppet arbitration (open dispute → fake vote → settle → reclaim stake) | The arbitration pool is disabled whenever a review board is set (vote_dispute/finalize_arbitration revert); the board is the only resolution path. Votes are one-per-wallet and board resolutions finalize open cases so stakes stay claimable. Tie-break is buyer-favourable. deploy_testnet.sh now requires BOARD_ACCOUNT and calls set_arbiter before anything else, so a fresh deployment is never left exploitable. |
Owner could drain escrowed NEAR via withdraw |
Removed. No owner sweep exists; value leaves only through settlement/board paths. |
Owner could retake dispute power via set_arbiter(owner) |
set_arbiter/set_treasury are bootstrap-only for the owner; afterwards only the current board/treasury can rotate them. Verified live: owner call reverts. |
| Double payouts from failed buyer legs / folded logistics | Independent per-leg settlement: the buyer remainder is stored and retried via permissionless retry_review_buyer_payout; resolution paths mark folded logistics paid; settle_logistics is state-gated; reputation counters are exactly-once and value-filtered. |
| Storage-drain spam / unbounded input | Creation requires a 0.02 NEAR storage deposit; string lengths, per-account indexes and pending lists are capped; escrow count is capped; token field is an allowlist (native NEAR). |
| TEE input controlled by caller | Carrier signatures are mandatory: the carrier payload must be ed25519-signed by the key registered on-chain (set_carrier_pubkey, required at init); the TEE verifier rejects unsigned/invalid payloads (it fails closed when no key is configured). The contract further enforces tracking + carrier-provider identity, and the verifier enforces shipment identity, timeline, pickup-before-delivery and the signed issued_at freshness window. |
| Logistics allocation could strand | Completion (confirm_receipt and the timeout release) now pays the logistics allocation if still due — requires a recorded provider — then seller, then platform fee, with per-leg rollback. Regression tests cover both completion paths. |
| Seller could replace the logistics beneficiary after funding | A provider committed at creation can only be confirmed; otherwise the first assignment is final. Replacement and confirmation paths have contract regression coverage. |
| Failed refunds / premature reputation | Refund callbacks restore the exact prior state; completion and refund reputation move only after their transfers succeed. |
| Creation-time tracking blocked no-dispatch refunds | Tracking is only an identifier at creation; shipment_registered becomes true solely through register_shipment. Pre-registered marketplace escrows retain the buyer refund path. |
| Failed dispute seller leg corrupted the split pot | Resolution stores the prior logistics-payment flag and restores it on failure, so retries neither deduct unpaid logistics nor double-count paid logistics. Tracking numbers and dispute reasons are length-capped. |
| Zero/very-short inspection window | create_escrow enforces a 1-hour minimum inspection period (UI defaults to 72h and the escrow page shows the auto-release time); the timeout release can never skip a real buyer review window. |
| Frozen funds if the board stalls | Buyer dispute and long-stop refunds: unresolved disputes default to a buyer refund after 7 days; undelivered shipments have a 30-day long-stop. No-dispatch refunds work with creation-time tracking, verified live on SWFT-951559, and with seller-opened disputes in regression tests. |
| Upgrade key could redeploy the contract | Deploy keys were deleted on both sweeft-eco.testnet (tx Er5pEHC8Dx8vgSdTvrXKF685KjXTypS16aZH1qj5Wsso) and sweeft-board.testnet (tx BYxu9F3G…); view_access_key_list returns empty for both — no key can deploy new code, ever. Owner/board actions remain signature-gated by their member accounts. |
| Carrier key churn | Carrier key/provider-id changes are board-only (owner cannot set them), and rotation is visible on-chain. |
| Pool reachable before a board exists | The review board is a required init argument (new(..., arbiter, ...)); a fresh deployment never exposes the pool, and the deploy script additionally requires the carrier key. |
| Login accepted scoped function-call keys | Sessions require a FullAccess on-chain key (verified against the access-key list), plus CSRF-protected POSTs, session fixation rotation, cache-backed rate limits, and a secret-key fail-hard when DEBUG=0. |
| AI budget cap lived only in server settings | Enforced on-chain in the budget contract (get_max_payment/set_max_payment, default 0.1 NEAR per payment). |
| Shared agent key could spend any budget | Fixed 2026-11: the budget contract now supports per-owner agent authorization (set_my_agent, get_owner_agent, is_revoked), so an agent authorized by one wallet cannot spend another wallet's budget; revocation blocks both the per-owner and the global agent. Deployed by state-preserving upgrade (tx 2UteeXb3ci15ZEf4XbwVzNVywYRcPCKQgCvMDXg3jx5B). |
| Duplicate logical payments | Fixed 2026-11: pay(owner, receiver, amount, intent_id) rejects a reused intent id on-chain (rollback releases the id on transfer failure so retries with the same id succeed). Django passes the PaymentIntent id (live proof tx DfJCDKu85garMiSSBBYxAen43dYx4wSonZ5w6PC6G18R). |
| Stale payment approvals / stranded executions | PaymentProposals expire (default 15 min, AI_PAYMENT_INTENT_TTL_SECONDS) and a crashed processing claim is reclaimable after AI_PAYMENT_PROCESSING_TIMEOUT_SECONDS; amount/recipient are immutable per intent and execution is session-scoped. |
| Event timestamps were not authenticated | The verifier v2 canonical message signs each event as status@ts (epoch ms) and rejects missing, zero, out-of-order or future-dated timestamps; the Python carrier signer emits the same v2 format. Deployed to OutLayer (wasm sha256 1f42106080777f03546599891b531de1f8420decdc94931ed578231aeb0d59f2). |
Residual (disclosed) risks:
- The review-board council is a demo council on testnet (single operator; multisig/hardware on mainnet).
- Carrier key custody: on testnet the Demo Carrier signing key is held by this project's service
(
DEMO_CARRIER_PRIVATE_KEYin the server env) — a real deployment would hold it at the carrier. The TEE verifies the signature, so trust is in the registered carrier key holder; the owner/board can rotate that key on-chain, and rotation is visible to verifiers. - The demo agent key is server-side (on-chain cap + budget bound its blast radius).
- The arbitration pool has no slashing — which is why it is disabled in favour of the board.
- OutLayer compute refunds accumulate in the contract unspent: there is deliberately no owner sweep, so they are dust on testnet rather than a drain vector.
- Carrier-payload replay window: payloads carry a signed
issued_atand the verifier rejects stale (and future-dated) reports; the check relies on the OutLayer runtime's clock, so it holds only if that host is honest. Payloads are additionally bound to the on-chain shipment id. - The pending-invitation index is capped at 10 entries per account; filling a victim's list costs ~0.2 NEAR. A production deployment would charge a reclaimable bond instead.
Everything below runs from a fresh git clone — no secrets, no accounts, no testnet funds required
for the automated suites.
git clone https://github.com/Dekantiok/sweeft && cd sweeft
# --- Django app + full test suite -----------------------------------------
cd sweeft
python3 -m venv .venv && source .venv/bin/activate
python3 -m pip install -r requirements.txt
cp .env.example .env # testnet addresses + DEBUG=1; nothing else needed
python3 manage.py migrate
python3 manage.py test # 169 tests: wallets, escrow, offers, logistics, disputes, relayer, AI
python3 manage.py seed_demo # optional sample listings + Demo Carrier partner
python3 manage.py runserver 0.0.0.0:8000 # → http://localhost:8000
# --- Escrow contract: unit + invariant (proptest) tests -------------------
cd ../contracts/sweeft
cargo test # 72 tests, no network
# --- Escrow contract: full sandbox lifecycle (near-workspaces) ------------
# Needs both wasm artifacts; the test drives the real promise callback path.
rustup target add wasm32-unknown-unknown
cargo build --release --target wasm32-unknown-unknown
cargo build --release --target wasm32-unknown-unknown \
--manifest-path ../stub-outlayer/Cargo.toml
cargo test --test sandbox # spins a local chain and runs create → TEE → settle
# --- Co-pilot budget contract: per-owner agent + intent idempotency -------
cd ../near-budget
cargo test # 19 tests incl. revocation + duplicate-intent guards
# --- TEE verifier (WASI) ---------------------------------------------------
cd ../../wasi/sweeft-verify
cargo test # 24 tests incl. signature, replay window and event timestampsWhat works locally without any server-side keys: wallet login (NEP-413 with your own testnet
wallet), marketplace, purchase requests, on-chain escrow create/accept/fund/assign/ship/confirm,
disputes, review-board pages and all read-only views. The carrier TEE request returns a clear
503 carrier signing is not configured instead of failing, the relayer reports "not configured",
and AI co-pilot payments need only your own AI_AGENT_* keys if you want them.
On-chain testnet flow (uses your wallet + free testnet NEAR from https://near-faucet.io/):
/market/ → request a listing → seller creates the escrow → buyer accepts + funds → register a
tracking number → either run the relayer (RELAYER_* in .env) or use the escrow page's manual
TEE request, which needs the Demo Carrier key. The full lifecycle on the live deployment is
evidenced with transaction hashes in Verified end-to-end on testnet above.
Carrier TEE verification, the settlement relayer and AI co-pilot payments run with project-held keys — a judge should not need (or get) them. Three ways to verify them anyway:
- Automated suites — no keys, no funds, no accounts:
cargo test --test sandboxdeploys the contract to a local chain with its own carrier key and a stub OutLayer runner, then drives TEE verification → logistics payout → buyer confirmation through the real promise callback, and asserts the terminal escrow leaves the active index.manage.py testmocks chain reads and signing for the relayer, AI payments, disputes and logistics guards, marketplace offers/negotiation and payment lifecycle (169 tests).
- Read-only live check —
python3 manage.py verify_livere-hashes the deployed contract against the reproducible build, confirms the contract is keyless, checks governance/carrier wiring, and re-reads the lifecycle evidence (TEE verification, payout flags, index pruning, refund/reject/cancel paths, reputation) straight from testnet via public RPC. Exits non-zero if the deployment stops matching the README — safe for judges and CI to run. - Bring your own keys — for full manual flows on a deployment of your own: create your own
testnet accounts, set
DEMO_CARRIER_PRIVATE_KEY/DEMO_CARRIER_PUBKEY,RELAYER_*andAI_AGENT_*in.env(see.env.example), and deploy withscripts/deploy_testnet.sh, which registers your carrier key on-chain at init. On the hosted demo (Render) the server already holds the project keys, so the same flows are clickable in the UI without entering anything.
- Contract logic is exercised on testnet by
scripts/e2e_lifecycle.sh(create → … → settle), asserting exact balances at each settlement step. - Django:
python3 manage.py test(169 tests) — carrier state-machine guards (forward-only, idempotent, failure-terminal), partner API auth + event round-trips, escrow tracking lookup, the verification payload matching the OutLayer invariants, marketplace offers/negotiation (ceilings, party checks, strict transitions, escrow prefill at the agreed price), payment-intent lifecycle (expiry, stale-claim recovery, ownership, on-chain intent id), listing↔escrow reconciliation, health probes, and the relayer (chain-conditioned actions, inspection-window gating, high-water reconciliation, failure isolation). - Carrier simulator:
cd tools/demo-carrier && python3 -m unittest test_simulator -v. - Django smoke:
python3 manage.py check; pages/,/dashboard/,/escrow/<id>/,/logistics/,/partners/portal/, plus the JSON API under/api/v1/. - Rust unit tests:
cargo testincontracts/sweeft— state machine (proptest invariants: total payouts never exceed deposits, terminal states never change), permissionless verification/settlement/release gates, beneficiary immutability, dispute deadlines, payout rollback, dispute-resolution retries, deadline/tracking guards, stake safety, storage caps and post-payout reputation (72 tests). - Sandbox lifecycle:
cargo test --test sandboxincontracts/sweeft— near-workspaces spins a local chain, deploys a stub OutLayer runner, and drives the whole lifecycle through the real promise callback (request_delivery_verification→on_verification_result→ settlement) and asserts the terminal escrow leaves the active index. - Co-pilot budget contract:
cargo testincontracts/near-budget(19 tests) — per-owner agent authorization and revocation, global-agent fallback, spending caps, duplicate intent-id rejection and failure rollback that releases the id for retries. - TEE verifier:
cargo testinwasi/sweeft-verify(24 tests) — mandatory carrier signatures, freshness window, timeline rules, and v2 signed event timestamps (missing/zero/out-of-order/future timestamps rejected).
- Demo Carrier is simulated — a standalone service (
tools/demo-carrier/) polling the partner API; real GIG/DHL/FedEx integrations require API access (not assumed). - The verification module receives the carrier payload as input; fetching carrier APIs from inside the TEE is a WASI P2 upgrade path.
REVIEW_REQUIREDhas an explicit, disclosed demo-board path (resolve_review) plus a seven-day buyer-refund fallback — this is not decentralized arbitration.- Reputation economics are unproven: counters are mechanism-complete and chain-derived, but on testnet wash-trading is cheap. Production would add stake, fees, or dispute-bond mechanics.
- Marketplace listings are an off-chain catalog (photos/descriptions); the on-chain reference is the wallet and its escrow history.
- Fiat/bank payouts, cross-chain settlement, reputation staking, and mobile apps are out of MVP scope.
License: MIT.