store: close a failed paid name order after refund (#8094)

This commit is contained in:
Evgeny authored and GitHub committed 2026-11-12 08:20:19 +00:00
commit bb5d95fc24
9 files changed
+411 -46

No files matched your search

+54 -6
View File
@@ -1191,8 +1191,8 @@ psql "postgresql://simplex@127.0.0.1:5432/badge_service" -c "SELECT registrar_no
An order sends at most 5 commits, 5 terms acceptances and 5 registers, its moves included, since an
owner who changes their terms acceptance on chain can make each acceptance and register revert at the
service's gas. Past that the order fails, Try again and a move answer `400 bad_request`, and support refunds it
at the provider: `//refund` records nothing for such an order, which has no balance.
service's gas. Past that the order fails, Try again and a move answer `400 bad_request`, and support closes it
with `//close` (see [Closing a failed order](#closing-a-failed-order)).
The log line is `[WARN …] names worker: registration <id> failed: it sent <n> transactions of one kind`.
Try again or a move of a failed order, and the worker's judgment of a register that did not go
@@ -1350,8 +1350,9 @@ were already given out, and the command answers with an error. A multi-use code
be revoked, which stops the uses that remain.
Core parses `//...` into `CustomChatCommand` and leaves it to the service's `preCmdHook`, which is
why issuing codes lives in the service rather than in core. `//refund`, the other command of this
console, is in [Refunding a name balance](#refunding-a-name-balance).
why issuing codes lives in the service rather than in core. `//refund` and `//close`, the other
commands of this console, are in [Refunding a name balance](#refunding-a-name-balance) and
[Closing a failed order](#closing-a-failed-order).
### From the group
@@ -1444,7 +1445,8 @@ them later is logged as not applied and changes nothing.
## Refunding a name balance
A paid name order keeps its money as a balance when it ends `taken` (another buyer registered the
name first), when it moves to a cheaper name (the difference), when a payment reaches its invoice
name first, or support closed the failed order with `//close`, which also records the refund; see
[Closing a failed order](#closing-a-failed-order)), when it moves to a cheaper name (the difference), when a payment reaches its invoice
after the invoice closed, and when its invoice was paid more crypto than it asked (the extra). The
buyer spends a balance on another name from Your names, or asks for it back: the page tells them to
write to chat@simplex.chat with the order's reference, which is its invoice id, or its registration
@@ -1491,7 +1493,7 @@ expiry unless money reached the invoice:
once the invoice expires and the poller, in service mode, closes the order. Run the command again
then.
- `its invoice expired at <time>; start the service so the poller closes that order, 10 minutes
after the expiry at the earliest, then stop it and run //refund again`: the poller runs only in
after the expiry at the earliest, then stop it and run the command again`: the poller runs only in
service mode. Its first pass from 10 minutes after the expiry closes the order and releases the
hold; a card order closes only once Stripe accepts the cancel.
- `whose invoice holds money`: a payment reached the invoice, before or after its expiry; the hold
@@ -1502,6 +1504,52 @@ The command also answers when the reference matches no order, when the order has
when the cents are not the balance. A refunded balance shows `amount` 0 and its `refunded` total in
Your names; a later late payment credits it again, and a second refund adds to `refunded`.
## Closing a failed order
A failed paid order stays live and keeps its money uncredited, so its wallet cannot order the name
again. When Try again cannot register it, as after 5 sends of a kind or refused links, support closes
it in `--run-cli` mode with the service stopped:
```
//close <reference>
```
The reference is the order's invoice id, or its registration id. The command reads the chain, so it
needs `[names]` and `[chain]` in `store_service.ini`; without `[names]` it answers that names are not
enabled. It:
1. checks the chain first, as Try again does: when a register of the order mined, or its owner holds
the name at the confirmation depth, the order is set `registered`, nothing is refunded, and the
change is logged at note with its registration id;
2. otherwise, in one transaction, sets the order `taken`, credits its price to its balance, which may
already hold a move's difference or an overpayment, and records all of that balance as refunded,
as `//refund` does.
The answer, `Closed order <id>, failed at <time>, as taken and recorded a refund of $100.00. Check at
the provider that it was not refunded by hand before; if not, refund it now, by: …`, lists what paid
for the order, as the answer of `//refund` does. Before this command existed, support refunded failed
orders at the provider by hand, so look for a refund of that payment after the failure time first, and
pay the amount back by those methods only if none is found. The service logs each closed order at
note with its registration id and the cents.
Before the first version with `//close` is deployed, list the failed paid orders, with the committed
ones past their signing deadline, which read failed and can be closed too, and find at the provider,
by the provider reference listed, each one already refunded by hand. An order paid from a balance
also lists the order whose balance paid it, and one paid wholly from it lists no invoice. After the deploy, close
the orders refunded by hand with `//close` and pay nothing, so that their records match the money:
```
psql "$BADGE_DB_CONN" -Atc "SELECT r.registration_id, r.phase, r.failed_at, r.reveal_before, ni.invoice_id, ni.provider_ref, r.balance_source FROM simplex_v1_chat_schema.sx_badge_service_name_registrations r LEFT JOIN simplex_v1_chat_schema.sx_badge_service_name_invoices ni ON ni.registration_id = r.registration_id WHERE r.name_prepaid_code_id IS NULL AND (r.phase = 'failed' OR (r.phase = 'committed' AND r.label IS NULL AND r.reveal_before < EXTRACT(EPOCH FROM now()))) ORDER BY r.created_at"
```
A closed order reads `taken` in Your names, with its refund. Try again and a move answer
`400 bad_request`, `//refund` finds nothing to refund, and the wallet can order the name again.
The command records nothing for an order that is not failed or was paid with a prepaid code, whose
code is released 30 days after the order failed; for a failed chain read; for a balance an order
holds, worded as for `//refund`; and for an order or a balance that changed meanwhile. Run the
command again after the last three.
## Running the webapp's cases against the service
`scripts/store-service/dev/contract-run.sh` runs the names webapp's end-to-end cases that need no
+30 -3
View File
@@ -83,7 +83,7 @@ How a request flows:
7. Every transaction is sent through the sender: dry run, nonce, fees, EIP-1559 signature with the registrar key, a saved row, then broadcast. Receipts are followed every 4 s to the confirmation depth ([`Names/Sender.hs:107-131`](../src/StoreService/Names/Sender.hs#L107-L131), [`Names/Sender.hs:151-226`](../src/StoreService/Names/Sender.hs#L151-L226)).
8. A link edit is submitted to the sender on its request's thread, and pending edits are settled by the record edits lane every 4 s ([`Names/Records.hs:156-263`](../src/StoreService/Names/Records.hs#L156-L263), [`Names/Records.hs:265-302`](../src/StoreService/Names/Records.hs#L265-L302)).
9. Link profiles are read through the chat core's connect plan, and the link data through SMP servers ([`Names/Profiles.hs:269-274`](../src/StoreService/Names/Profiles.hs#L269-L274), [`Chat/Library/Internal.hs:1723-1726`](../../../src/Simplex/Chat/Library/Internal.hs#L1723-L1726)).
10. Operators issue and revoke codes in the managed group while the service runs. In the console, a separate run of the same binary while the service is stopped, they issue and revoke codes and record refunds ([`Group.hs:263-300`](../src/StoreService/Group.hs#L263-L300), [`Main.hs:25-28`](../Main.hs#L25-L28), [`Service.hs:412-430`](../src/StoreService/Service.hs#L412-L430)).
10. Operators issue and revoke codes in the managed group while the service runs. In the console, a separate run of the same binary while the service is stopped, they issue and revoke codes, record refunds and close failed paid orders ([`Group.hs:263-300`](../src/StoreService/Group.hs#L263-L300), [`Main.hs:25-28`](../Main.hs#L25-L28), [`Service.hs:415-434`](../src/StoreService/Service.hs#L415-L434)).
11. One process runs per database: a PostgreSQL advisory lock is held on a connection of its own for the whole run ([`Store/Migrate.hs:46-58`](../src/StoreService/Store/Migrate.hs#L46-L58)).
---
@@ -106,7 +106,7 @@ How a request flows:
| Chat core | The SimpleX chat controller with the bot user: the bot address for badge requests, the managed group's messages, and connect plans for link profiles. Every chat event is read from `outputQ` by one reader. | [`Service.hs:293-313`](../src/StoreService/Service.hs#L293-L313), [`Service.hs:636-645`](../src/StoreService/Service.hs#L636-L645), [`Names/Profiles.hs:269-274`](../src/StoreService/Names/Profiles.hs#L269-L274) |
| Badge request lanes | Badge requests on the bot address, present before this PR: three lanes, each answer sent as `APISendServiceResponse`. | [`Service.hs:572-657`](../src/StoreService/Service.hs#L572-L657) |
| Group lane | With `[group]`: one managed group. `/issue` and `/bulk` are taken from moderators, `/revoke` and name codes from admins. A name code command is refused once the name codes created in the last 24 hours, console ones included, would pass 100. | [`Group.hs:87-304`](../src/StoreService/Group.hs#L87-L304), [`Group/Command.hs:59-73`](../src/StoreService/Group/Command.hs#L59-L73), [`Group/Command.hs:216-220`](../src/StoreService/Group/Command.hs#L216-L220) |
| Console | The same binary under `--run-cli`, while the service is stopped: the terminal chat and the badge request lanes only, with `//issue`, `//issue name`, `//revoke` and `//refund`. | [`Main.hs:25-28`](../Main.hs#L25-L28), [`Service.hs:381-506`](../src/StoreService/Service.hs#L381-L506) |
| Console | The same binary under `--run-cli`, while the service is stopped: the terminal chat and the badge request lanes only, with `//issue`, `//issue name`, `//revoke`, `//refund` and `//close`. `//close` reads the chain through a client of its own, made at start with `[names]`. | [`Main.hs:25-28`](../Main.hs#L25-L28), [`Service.hs:383-540`](../src/StoreService/Service.hs#L383-L540) |
| PostgreSQL | One database (`BADGE_DB_CONN`) with the chat core's schema and the `sx_badge_service_` tables. Names tables: prepaid codes, registrations, balances, name invoices, late credits, record edits and their changes, transactions, terms texts. Partial unique indexes admit one active order (`live = 1`) per commitment and per owner and label hash. | [`Store/Postgres/Migrations.hs:276-478`](../src/StoreService/Store/Postgres/Migrations.hs#L276-L478), [`compose.yml:16`](../../../scripts/store-service/compose.yml#L16) |
| Names page | simplex.domains, in the submodule `apps/simplex-domains`, outside this checkout. `/api/*` is called on its own origin, and the owner's EIP-191 and EIP-712 signatures are sent from it. | [`.gitmodules:4-7`](../../../.gitmodules#L4-L7), [`Web/Names.hs:28-44`](../src/StoreService/Web/Names.hs#L28-L44) |
| BTCPay | Bitcoin and Monero invoices through Greenfield: create, read, list, cancel (status `Invalid`), store rates; webhooks signed with `BTCPay-Sig`. | [`Providers/BTCPay.hs:267-367`](../src/StoreService/Providers/BTCPay.hs#L267-L367), [`Providers/BTCPay.hs:524-538`](../src/StoreService/Providers/BTCPay.hs#L524-L538), [`Providers/BTCPay.hs:555-578`](../src/StoreService/Providers/BTCPay.hs#L555-L578) |
@@ -517,10 +517,37 @@ sequenceDiagram
Notes:
- The refund must equal the whole balance, and a held balance is refused, overdue or not. `//refund` closes no holder: its answer asks support to start the service, whose poller closes an overdue holder 10 minutes after its expiry, then to run `//refund` again ([`Names/Balances.hs:40-65`](../src/StoreService/Names/Balances.hs#L40-L65), [`Names/Store.hs:1046-1056`](../src/StoreService/Names/Store.hs#L1046-L1056), [`Service.hs:498-506`](../src/StoreService/Service.hs#L498-L506)).
- The refund must equal the whole balance, and a held balance is refused, overdue or not. `//refund` closes no holder: its answer asks support to start the service, whose poller closes an overdue holder 10 minutes after its expiry, then to run the command again ([`Names/Balances.hs:40-65`](../src/StoreService/Names/Balances.hs#L40-L65), [`Names/Store.hs:1046-1056`](../src/StoreService/Names/Store.hs#L1046-L1056), [`Service.hs:532-540`](../src/StoreService/Service.hs#L532-L540)).
- The provider interface offers create, read, cancel, list, rate and webhook verification, so the money is paid back by hand ([`Providers.hs:120-130`](../src/StoreService/Providers.hs#L120-L130)). The buyer's email to chat@simplex.chat is described in the README; the page code is in the submodule ([`README.md:1371-1411`](../README.md#L1371-L1411)).
- The console starts only while the service is stopped, as the database lock is held by one process ([`Store/Migrate.hs:46-54`](../src/StoreService/Store/Migrate.hs#L46-L54)).
A failed paid order has no balance until it is closed. Support closes it with `//close`, which checks the chain first and records the refund in the same transaction that ends the order.
```mermaid
sequenceDiagram
participant B as Buyer
participant O as Support
participant C as Console in run-cli mode
participant N as Ethereum node
participant D as PostgreSQL
B--)O: asks for a refund of a failed order with its reference (outside the service)
Note over O,C: the service is stopped, then run with --run-cli
O->>C: //close REFERENCE
C->>D: the order, under its name's lock
C->>N: a mined register of the order, or the owner holding the name at the confirmation depth
alt the register went through
C->>D: order set registered
C-->>O: Nothing refunded: the register of order ID went through
else not registered
C->>D: under the balance's lock, one transaction: order set taken, price credited, the whole balance recorded as refunded
C-->>O: Closed order ID, failed at TIME ... Check at the provider ...; if not, refund it now, by: ORDERS.
O--)B: money paid back by hand, unless refunded before (outside the service)
end
```
- Only a failed order paid by invoice or balance is closed, and a lapsed committed order reads failed. A balance an order holds refuses the close and writes nothing ([`Names/Worker.hs:515-564`](../src/StoreService/Names/Worker.hs#L515-L564), [`Names/Worker.hs:376-380`](../src/StoreService/Names/Worker.hs#L376-L380), [`Names/Orders.hs:366-412`](../src/StoreService/Names/Orders.hs#L366-L412)).
- The answer names the failure time, as failed orders were refunded at the provider by hand before `//close` existed ([`Service.hs:502-530`](../src/StoreService/Service.hs#L502-L530), [`README.md:1491-1536`](../README.md#L1491-L1536)).
---
### 3.11 A registered name's links edited
@@ -40,6 +40,7 @@ module StoreService.Names.Orders
retargetOrder,
versionWritten,
confirmLanded,
checkLanded,
)
where
@@ -362,12 +363,15 @@ versionWritten = \case
LiveOrderExists -> Left $ WRRefused OROrderExists
NotLive -> Left $ WRRefused ORBadRequest
confirmLanded :: OrdersEnv -> NameRegistration -> IO Landing
confirmLanded OrdersEnv {oeStore, oeContracts, oeTurns, oeNow} = checkLanded oeStore oeContracts oeTurns oeNow
-- | /retry's first check, on the order's current name: a register mined with status 1, or the owner holding the name at the confirmation depth,
-- went through with only its confirmation lost. The order then becomes registered by a compare-and-set on the version read, a code order spending its code.
-- The caller holds the turn of the order's label hash and passes the order as registrationAt reads it.
confirmLanded :: OrdersEnv -> NameRegistration -> IO Landing
confirmLanded OrdersEnv {oeStore, oeContracts, oeTurns, oeNow} r@NameRegistration {nrId, nrOwner, nrLabelHash, nrPayment} = do
txs <- withTransaction oeStore (`registrationTransactions` nrId)
checkLanded :: DBStore -> Contracts -> Turns -> IO UTCTime -> NameRegistration -> IO Landing
checkLanded st ct turns clock r@NameRegistration {nrId, nrOwner, nrLabelHash, nrPayment} = do
txs <- withTransaction st (`registrationTransactions` nrId)
let mined = [(ntHash, ntMinedBlock) | NameTransaction {ntFor = TxRegister _, ntStatus = TSMined, ntHash, ntMinedBlock} <- txs]
runExceptT (landed mined) >>= \case
Left e -> LUnread <$ logWarn ("names: a register check's chain read failed: " <> tshow e)
@@ -375,13 +379,13 @@ confirmLanded OrdersEnv {oeStore, oeContracts, oeTurns, oeNow} r@NameRegistratio
Right (Just (tx, expiry)) -> either (const LChanged) LRegistered <$> markRegistered tx expiry
where
landed mined = do
confirmed <- ExceptT $ confirmedTag oeContracts
confirmed <- ExceptT $ confirmedTag ct
registerTx <- case mined of
tx : _ -> pure $ Just $ Just tx
[] -> (\holder -> if holder == Just nrOwner then Just Nothing else Nothing) <$> ExceptT (ownerOfToken oeContracts confirmed nrLabelHash)
forM registerTx $ \tx -> (tx,) <$> ExceptT (nameExpires oeContracts confirmed nrLabelHash)
[] -> (\holder -> if holder == Just nrOwner then Just Nothing else Nothing) <$> ExceptT (ownerOfToken ct confirmed nrLabelHash)
forM registerTx $ \tx -> (tx,) <$> ExceptT (nameExpires ct confirmed nrLabelHash)
markRegistered tx expiry = do
now <- oeNow
now <- clock
let registered =
r
{ nrPhase = PRegistered,
@@ -395,12 +399,12 @@ confirmLanded OrdersEnv {oeStore, oeContracts, oeTurns, oeNow} r@NameRegistratio
}
write db = versionWritten <$> updateRegistration db registered now
case nrPayment of
RPInvoice {} -> withTransaction oeStore write
RPBalance -> withTransaction oeStore write
RPCode codeId -> spendLandedCode oeTurns oeStore now codeId nrId write >>= traverse (paidWith codeId)
RPInvoice {} -> withTransaction st write
RPBalance -> withTransaction st write
RPCode codeId -> spendLandedCode turns st now codeId nrId write >>= traverse (paidWith codeId)
paidWith codeId (v, spent) = do
unless spent $ do
code <- withTransaction oeStore (`getPrepaidCodeById` codeId)
code <- withTransaction st (`getPrepaidCodeById` codeId)
logError $
"names: registration " <> ridText nrId <> " turned out registered with prepaid code " <> maybe (tshow codeId) (hex . pcCodeHash) code
<> ", which was released and then spent, revoked or expired: the name was paid with it"
@@ -17,15 +17,20 @@ module StoreService.Names.Worker
Retried (..),
RetryRefusal (..),
retryRegistration,
Closed (..),
CloseRefusal (..),
closeRegistration,
maxSendsPerKind,
sendsUsedUp,
)
where
import Control.Applicative ((<|>))
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (Async, asyncWithUnmask, cancel, poll)
import Control.Concurrent.STM
import Control.Exception (finally, mask_)
import qualified Control.Exception as E
import Control.Logger.Simple (logError, logNote, logWarn)
import Control.Monad (forM, forM_, forever, void, when)
import Control.Monad.Except (ExceptT (..), runExceptT)
@@ -39,20 +44,22 @@ import qualified Data.Text as T
import Data.Time.Clock (NominalDiffTime, UTCTime, addUTCTime, diffUTCTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Word (Word64)
import Simplex.Messaging.Agent.Store.Common (withTransaction)
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
import qualified Simplex.Messaging.Agent.Store.DB as DB
import Simplex.Messaging.Util (tshow, ($>>=))
import StoreService.Config (ChainConfig (..), NamesConfig (..))
import StoreService.Names.Balances (RefundRecord (..))
import StoreService.Names.Chain (Block (..), BlockTag (..), ChainClient, ChainError (..), TxHash, blockAt)
import StoreService.Names.Codes (CodeRefusal (..), codeRefusal, releaseCode, reserveCode)
import StoreService.Names.Contracts (CommitmentAges (..), acceptedTerms, commitmentAges, commitmentTime, communityName, confirmedTag, controllerAvailable, forgetNamePolicy, namePolicy, sponsorNonce)
import StoreService.Names.Orders (Landing (..), OrdersEnv (..), WriteRefusal (..), confirmLanded, unixSeconds, versionWritten)
import StoreService.Names.Contracts (CommitmentAges (..), Contracts, acceptedTerms, commitmentAges, commitmentTime, communityName, confirmedTag, controllerAvailable, forgetNamePolicy, namePolicy, sponsorNonce)
import StoreService.Names.Orders (Landing (..), OrderRefusal, OrdersEnv (..), WriteRefusal (..), checkLanded, confirmLanded, unixSeconds, versionWritten)
import StoreService.Names.Phases (RegistrationId (..), awaitChange, publish)
import StoreService.Names.Registration (TermsAcceptance (..), acceptCalldata, commitCalldata, policyDomain, registerWithCreditCalldata, sponsorDomain, termsKind, verifyAcceptance, verifyRegisterIntent)
import StoreService.Names.Reveal (intentOf)
import StoreService.Names.Revert (RevertName (..))
import StoreService.Names.Sender (PendingTx, SendError (..), Sender, awaitOutcome, inFlightTransaction, ptHash, submitTransaction)
import StoreService.Names.Store
import StoreService.Names.Turns (withBalanceTurn, withLabelTurn)
import StoreService.Names.Turns (Turns, withBalanceTurn, withLabelTurn)
import StoreService.Names.View (lapseMoment, notSignedInTime, registrationAt, registrationVersion)
import StoreService.Safely (safely, safelyWith)
@@ -359,13 +366,18 @@ judge w@Worker {wkOrders = oe@OrdersEnv {oeContracts}} now r@NameRegistration {n
-- | A paid order keeps its whole price as a balance of its own, credited in the taken write's transaction, registration before balance,
-- in the balance's turn after the name's; a code order's code is released.
taken :: Worker -> UTCTime -> NameRegistration -> IO (Maybe Int64, Next)
taken Worker {wkOrders = OrdersEnv {oeStore, oeTurns}} now r@NameRegistration {nrId, nrPayment, nrPrice} = case nrPayment of
taken Worker {wkOrders = OrdersEnv {oeStore, oeTurns}} now r@NameRegistration {nrId, nrPayment} = case nrPayment of
RPInvoice {} -> credited
RPBalance -> credited
RPCode codeId -> written r . fmap fst <$> releaseCode oeTurns oeStore codeId nrId write
RPCode codeId -> written r . fmap fst <$> releaseCode oeTurns oeStore codeId nrId (takenWrite now r)
where
write db = versionWritten <$> updateRegistration db r {nrPhase = PTaken, nrError = Nothing} now
credited = written r <$> withBalanceTurn oeTurns nrId (withTransaction oeStore $ \db -> write db >>= traverse (\v -> v <$ creditBalance db nrId nrPrice now))
credited = written r <$> withBalanceTurn oeTurns nrId (withTransaction oeStore $ creditedTaken now r)
takenWrite :: UTCTime -> NameRegistration -> DB.Connection -> IO (Either WriteRefusal Int64)
takenWrite now r db = versionWritten <$> updateRegistration db r {nrPhase = PTaken, nrError = Nothing} now
creditedTaken :: UTCTime -> NameRegistration -> DB.Connection -> IO (Either WriteRefusal Int64)
creditedTaken now r@NameRegistration {nrId, nrPrice} db = takenWrite now r db >>= traverse (\v -> v <$ creditBalance db nrId nrPrice now)
-- | A code order keeps its code for Try again.
failed :: Worker -> UTCTime -> NameRegistration -> IO (Maybe Int64, Next)
@@ -500,6 +512,57 @@ servingReveal OrdersEnv {oeConfig = cfg@NamesConfig {nChain = ChainConfig {cChai
Just lapse | reusable cfg now lapse && lapse <= toInteger rvDeadline -> Just rv
_ -> Nothing
data Closed = CLRegistered RegistrationId | CLRefunded (Maybe UTCTime) RefundRecord | CLRefused CloseRefusal
deriving (Eq, Show)
data CloseRefusal = CFNoOrder | CFNotFailedPaid | CFUnread | CFChanged | CFWriteRefused OrderRefusal | CFHeld BalanceHold | CFBalanceChanged
deriving (Eq, Show)
newtype CloseRefused = CloseRefused CloseRefusal
deriving (Show)
instance E.Exception CloseRefused
closeRegistration :: DBStore -> Contracts -> Turns -> IO UTCTime -> Text -> IO Closed
closeRegistration st ct turns clock ref = do
now <- clock
withTransaction st (\db -> balanceByReference db ref now $>>= getRegistration db . fst) >>= \case
Nothing -> refused CFNoOrder
Just NameRegistration {nrId, nrLabelHash} ->
withLabelTurn turns nrLabelHash $
withTransaction st (`getRegistration` nrId) >>= \case
Just current@NameRegistration {nrLabelHash = currentHash} | currentHash == nrLabelHash -> closeFailed now current
_ -> refused CFChanged
where
refused = pure . CLRefused
closeFailed now current = case registrationAt now current of
NameRegistration {nrPayment = RPCode _} -> refused CFNotFailedPaid
r@NameRegistration {nrId, nrPhase = PFailed} ->
checkLanded st ct turns clock r >>= \case
LRegistered _ -> pure $ CLRegistered nrId
LChanged -> refused CFChanged
LUnread -> refused CFUnread
LNotLanded -> either CLRefused (CLRefunded $ nrFailedAt current <|> lapseMoment current) <$> refundTaken st turns now r
_ -> refused CFNotFailedPaid
refundTaken :: DBStore -> Turns -> UTCTime -> NameRegistration -> IO (Either CloseRefusal RefundRecord)
refundTaken st turns now r@NameRegistration {nrId} =
withBalanceTurn turns nrId $ either (\(CloseRefused refusal) -> Left refusal) id <$> E.try (withTransaction st refund)
where
refund db =
getBalance db nrId now >>= \case
Just Balance {blHold = Just hold} -> pure $ Left $ CFHeld hold
_ ->
creditedTaken now r db >>= \case
Left WRChanged -> pure $ Left CFChanged
Left (WRRefused refusal) -> pure $ Left $ CFWriteRefused refusal
Right _ -> Right <$> refundAll db
refundAll db = do
cents <- maybe 0 blAmount <$> getBalance db nrId now
refundBalance db nrId cents now >>= \case
True -> RefundRecord nrId cents <$> balanceChain db nrId
False -> E.throwIO $ CloseRefused CFBalanceChanged
-- | Each code order failed for failedCodeHold gives its code back, in its name's and its code's turns, unless it was requeued meanwhile.
sweepFailedCodes :: Worker -> IO ()
sweepFailedCodes Worker {wkOrders = OrdersEnv {oeStore, oeTurns, oeNow}} = do
@@ -51,9 +51,9 @@ import StoreService.Group (GroupEvent, ensureManagedGroup, fmtTime, groupEvent,
import StoreService.Group.Command (badgeTypeP, codeP, maxMonths, maxNameYears, nameCodeP, prepaidCodeP, textTokenP)
import StoreService.Names.Abi (hex)
import StoreService.Names.Balances (RefundRecord (..), RefundRefusal (..), recordRefund)
import StoreService.Names.Chain (newChainClient, nodeChainId)
import StoreService.Names.Chain (ChainClient, newChainClient, nodeChainId)
import StoreService.Names.Codes (issueNameCode, revokeNameCode)
import StoreService.Names.Contracts (Contracts, Terms (..), communityName, namePolicy, runTermsFetch, termsLinkAllowed, termsLinks, termsOf)
import StoreService.Names.Contracts (Contracts, Terms (..), communityName, namePolicy, newContracts, runTermsFetch, termsLinkAllowed, termsLinks, termsOf)
import StoreService.Names.Env (NamesEnv (..), newNamesEnv)
import StoreService.Names.Orders (ordersEnv)
import StoreService.Names.Phases (RegistrationId (..))
@@ -62,7 +62,7 @@ import StoreService.Names.Sender (checkPendingSignatures, runSender)
import StoreService.Names.Store (Balance (..), BalanceHold (..), BalanceLink (..), LateCredit (..), RegistrationPayment (..), balanceByReference, balanceChain, methodText)
import StoreService.Names.Turns (Turns, newTurns)
import StoreService.Names.View (addressText)
import StoreService.Names.Worker (newWorker, runCodeSweep, runWorkers)
import StoreService.Names.Worker (CloseRefusal (..), Closed (..), closeRegistration, newWorker, runCodeSweep, runWorkers)
import StoreService.Options
import StoreService.Poller (expiryGrace, newPollerEnv, newReadHints, runPoller)
import StoreService.Providers (Provider)
@@ -120,7 +120,7 @@ import qualified Simplex.Messaging.Agent.Store.DB as DB
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Crypto.BBS (bbsPublicKey)
import Simplex.Messaging.Encoding.String (strEncode)
import Simplex.Messaging.SimplexName (LabelHash (..))
import Simplex.Messaging.SimplexName (LabelHash (..), SimplexTLD)
import Simplex.Messaging.Util (catchOwn, catchOwn', raceAny_, safeDecodeUtf8, tshow)
import Simplex.Messaging.Version (isCompatible)
import System.Directory (getAppUserDataDirectory)
@@ -286,6 +286,7 @@ storeService opts serviceCfg baseCfg env = do
waiters <- newWaiters
-- The hooks' //revoke takes a prepaid code's turn, so the turns exist before the chat starts.
turns <- newTurns
consoleChain <- mapM newConsoleChain (serviceCfg >>= names)
requestEnv <- configureStoreVerifier serviceCfg env
let groupCfg = serviceCfg >>= \ServiceConfig {group} -> group
trackerQ_ = groupEventQ env <$ groupCfg
@@ -307,7 +308,7 @@ storeService opts serviceCfg baseCfg env = do
defaultChatHooks
{ preStartHook = Just $ badgePreStartHook opts (serviceCfg >>= names),
postStartHook = Just $ badgePostStartHook opts env,
preCmdHook = Just $ badgeCmdHook turns
preCmdHook = Just $ badgeCmdHook turns consoleChain
}
-- The reader runs from the start and must not block, since outputQ carries every chat event and a full queue stalls the core.
simplexChatCore cfg {chatHooks} (mkChatOpts opts) $ \_ cc -> raceAny_ [readEvents cc, startLanes cc]
@@ -387,6 +388,7 @@ storeServiceCLI opts serviceCfg = do
env <- newServiceState >>= configureStoreVerifier serviceCfg
-- This mode runs no names lanes, so only its own //revoke takes these turns.
turns <- newTurns
consoleChain <- mapM newConsoleChain (serviceCfg >>= names)
let eventHook _cc = \case
Right (CEvtServiceRequest u reqId sigKey reqData) -> do
atomically $ writeTQueue (serviceRequestQ env) (u, reqId, sigKey, reqData)
@@ -396,7 +398,7 @@ storeServiceCLI opts serviceCfg = do
defaultChatHooks
{ preStartHook = Just $ badgePreStartHook opts Nothing,
postStartHook = Just $ badgePostStartHook opts env,
preCmdHook = Just $ badgeCmdHook turns,
preCmdHook = Just $ badgeCmdHook turns consoleChain,
eventHook = Just eventHook
}
raceAny_
@@ -410,13 +412,13 @@ shownServiceRequest reqData = case KM.lookup "request" reqData of
Just (J.Object cmd) | Just t <- KM.lookup "type" cmd -> KM.singleton "request" $ J.object ["type" J..= t]
_ -> KM.empty
badgeCmdHook :: Turns -> ChatController -> ChatCommand -> IO (Either (Either ChatError ChatResponse) ChatCommand)
badgeCmdHook turns cc = \case
CustomChatCommand cmd -> Left <$> runBadgeCmd turns cc cmd
badgeCmdHook :: Turns -> Maybe (SimplexTLD, Int, ChainClient) -> ChatController -> ChatCommand -> IO (Either (Either ChatError ChatResponse) ChatCommand)
badgeCmdHook turns chain_ cc = \case
CustomChatCommand cmd -> Left <$> runBadgeCmd turns chain_ cc cmd
cmd -> pure $ Right cmd
runBadgeCmd :: Turns -> ChatController -> ByteString -> IO (Either ChatError ChatResponse)
runBadgeCmd turns cc cmd
runBadgeCmd :: Turns -> Maybe (SimplexTLD, Int, ChainClient) -> ChatController -> ByteString -> IO (Either ChatError ChatResponse)
runBadgeCmd turns chain_ cc cmd
| Right issueOpts <- A.parseOnly issueCmdP cmd =
issuedReply formatBadgeCode <$> issueBadgeCode cc issueOpts
| Right (len, years, paymentStatus) <- A.parseOnly issueNameCmdP cmd =
@@ -424,11 +426,12 @@ runBadgeCmd turns cc cmd
| Right code <- A.parseOnly revokeCmdP cmd = textReply <$> revokeWithTracker cc code
| Right code <- A.parseOnly revokeNameCmdP cmd = textReply <$> revokeNameCode turns cc code
| Right (ref, cents_) <- A.parseOnly refundCmdP cmd = textReply <$> maybe (showRefund cc ref) (refundBalanceCmd turns cc ref) cents_
| Right ref <- A.parseOnly closeCmdP cmd = textReply <$> maybe (pure $ Left "Names are not enabled on this service.") (\chain -> closeOrderCmd turns chain cc ref) chain_
| otherwise =
pure $ chatCmdError $
"Usage: //issue supporter|legend|investor [months 1-" <> show maxMonths <> "] [paid|unpaid|free], //issue name <length "
<> show minNameLength <> "-" <> show maxNameLength <> "> [years " <> show minNameYears <> "-" <> show maxNameYears
<> "] [paid|free], //revoke <code>, or //refund <reference> [<cents>]"
<> "] [paid|free], //revoke <code>, //refund <reference> [<cents>], or //close <reference>"
where
issuedReply :: (c -> T.Text) -> Either String c -> Either ChatError ChatResponse
issuedReply format = \case
@@ -496,9 +499,41 @@ refundBalanceCmd turns ChatController {chatStore} ref cents = do
RefundAmount amount -> "the balance is " <> dollars amount <> " now, not " <> dollars cents
RefundHeld hold -> heldText hold
closeCmdP :: A.Parser T.Text
closeCmdP = "close " *> (safeDecodeUtf8 <$> A.takeWhile1 (not . isSpace)) <* (A.skipSpace *> A.endOfInput)
newConsoleChain :: NamesConfig -> IO (SimplexTLD, Int, ChainClient)
newConsoleChain NamesConfig {nTLD, nMinPriceCentsPerYear, nChain} = do
chain <- C.newRandom >>= (`newChainClient` nChain)
pure (nTLD, nMinPriceCentsPerYear, chain)
closeOrderCmd :: Turns -> (SimplexTLD, Int, ChainClient) -> ChatController -> T.Text -> IO (Either T.Text T.Text)
closeOrderCmd turns (tld, minPriceCentsPerYear, chain) ChatController {chatStore} ref = do
ct <- newContracts chatStore tld minPriceCentsPerYear chain
((Right <$> closeRegistration chatStore ct turns getCurrentTime ref) `catchOwn` (pure . Left)) >>= \case
Right (CLRefunded failedAt RefundRecord {rdRegistration = RegistrationId rid, rdCents, rdChain}) -> do
logNote $ "names: closed order " <> rid <> " and recorded a refund of " <> tshow rdCents <> " cents"
pure $ Right $
"Closed order " <> rid <> maybe "" (\t -> ", failed at " <> fmtTime t <> ",") failedAt <> " as taken and recorded a refund of " <> dollars rdCents
<> ". Check at the provider that it was not refunded by hand before; if not, refund it now, by: " <> chainText rdChain <> "."
Right (CLRegistered (RegistrationId rid)) -> do
logNote $ "names: order " <> rid <> " set registered by //close, as its register went through"
pure $ Left $ "Nothing refunded: the register of order " <> rid <> " went through, so the order is registered now."
Right (CLRefused refusal) -> pure $ Left $ "Nothing recorded: " <> refusalText refusal <> "."
Left e -> Left "The order could not be closed." <$ logError ("names: closing an order failed: " <> tshow e)
where
refusalText = \case
CFNoOrder -> "no order has the reference " <> ref
CFNotFailedPaid -> "the order of " <> ref <> " is not a failed order paid by invoice or balance"
CFUnread -> "the chain could not be read; run //close again"
CFChanged -> "the order of " <> ref <> " changed meanwhile; run //close again"
CFWriteRefused _ -> "the order of " <> ref <> " could not be set taken; run //close again"
CFHeld hold -> heldText hold
CFBalanceChanged -> "the balance of the order of " <> ref <> " changed meanwhile; run //close again"
heldText :: BalanceHold -> T.Text
heldText BalanceHold {bhHolder = RegistrationId holder, bhUntil, bhOverdue, bhFunded}
| bhOverdue = heldBy <> "its invoice expired at " <> fmtTime bhUntil <> "; start the service so the poller closes that order, " <> tshow graceMinutes <> " minutes after the expiry at the earliest, then stop it and run //refund again"
| bhOverdue = heldBy <> "its invoice expired at " <> fmtTime bhUntil <> "; start the service so the poller closes that order, " <> tshow graceMinutes <> " minutes after the expiry at the earliest, then stop it and run the command again"
| bhFunded = heldBy <> "whose invoice holds money; it holds until that payment settles or the invoice closes; run the command again then"
| otherwise = heldBy <> "its invoice open until " <> fmtTime bhUntil <> "; run the command again then"
where
+1 -1
View File
@@ -1885,7 +1885,7 @@ testRevokeRejectsTrailingInput ps =
-- The text is spelled out rather than taken from the service, so a change there fails here.
badgeCmdUsage :: Text
badgeCmdUsage = "Usage: //issue supporter|legend|investor [months 1-255] [paid|unpaid|free], //issue name <length 6-63> [years 2-10] [paid|free], //revoke <code>, or //refund <reference> [<cents>]"
badgeCmdUsage = "Usage: //issue supporter|legend|investor [months 1-255] [paid|unpaid|free], //issue name <length 6-63> [years 2-10] [paid|free], //revoke <code>, //refund <reference> [<cents>], or //close <reference>"
purchaseCmd :: BadgeMasterKey -> ServicePayment -> StoreServiceCommand
purchaseCmd masterKey payment = STCPurchaseBadge {masterKey, payment, upgrade = Nothing}
@@ -17,7 +17,7 @@ import StoreService.Names.Abi (addressWord, selector, uint256)
import StoreService.Names.Codes (issueNameCode, reserveCode, revokeNameCode)
import StoreService.Names.Phases (RegistrationId (..))
import StoreService.Names.Chain (SignedTx (..), TxRequest (..), newChainClient, signTransaction)
import StoreService.Names.Store (NewTransaction (..), PrepaidCode (..), TxFor (..), getPrepaidCode, insertTransaction, spendLandedPrepaidCode)
import StoreService.Names.Store (NamePhase (PFailed), NameRegistration (nrFailedAt, nrPhase), NewTransaction (..), PrepaidCode (..), TxFor (..), VersionWrite (Written), getPrepaidCode, insertTransaction, spendLandedPrepaidCode)
import StoreService.Names.Turns (newTurns, withCodeTurn)
import StoreService.Options (StoreServiceOpts (..))
import StoreService.Orders (cancelOpenInvoice)
@@ -32,7 +32,8 @@ import Bots.StoreService.NamesContractsTests (nameExpiresCall, rentPriceAnswer,
import Bots.StoreService.WebTests (capturingStderr, digestFixture)
import Bots.StoreService.NamesSearchTests (aliceHex)
import qualified Bots.StoreService.NamesBalancesTests as Balances
import Bots.StoreService.NamesStoreTests (issue, order, ownerA, placeCode, placePaid, t0, usable)
import Bots.StoreService.NamesStoreTests (issue, order, ownerA, placeCode, placePaid, reg, t0, usable, write)
import Bots.StoreService.NamesOwnerTests (labelBytes, ownerOfSelector)
import ChatClient
import ChatTests.DBUtils
import ChatTests.Utils
@@ -507,10 +508,57 @@ namesRefundChatTests = describe "StoreService names: operator refund" $ do
it "refuses an unknown reference, an order without a balance and another amount, and answers the usage to a malformed command" testRefundRefusals
it "refuses a balance held by an open order, naming it and its expiry, and records it once that order's invoice is cancelled" testRefundOpenHolder
it "is not a group command" $ \_ -> groupCmdAction GROwner "/refund s 10000" `shouldBe` IgnoreMsg
it "closes a failed paid order by its invoice id, recording the refund of its price, and refuses an unknown reference and an order no longer failed" testCloseRecorded
it "refuses //close without [names], and answers the usage to a malformed one" testCloseNamesOff
refundRaw :: HasCallStack => ChatController -> Text -> IO (Either Text Text)
refundRaw cc args = operatorCmd cc ("//refund " <> args)
closeRaw :: HasCallStack => ChatController -> Text -> IO (Either Text Text)
closeRaw cc args = operatorCmd cc ("//close " <> args)
testCloseRecorded :: HasCallStack => TestParams -> IO ()
testCloseRecorded ps = withFakeEthNode $ \node@FakeEthNode {fnUrl} -> do
svc <- prepareGroupService ps
let registrar = address $ encodeUtf8 registrarAddr
(t, cc, _, port) <- startGroupService svc {gsIniSections = "" : namesSection <> withRpcUrl (T.pack fnUrl)} Nothing
flip finally (stopGroupService t cc) $ do
pollUntilTrue (listening port)
let st = chatStore cc
paidBy = "order f: $100.00 by btc on invoice inv-f"
now <- getCurrentTime
Balances.placeOrderRow st "f" False 10000 (addUTCTime 3600 now)
unpaid <- reg st "f"
write st unpaid {nrPhase = PFailed, nrFailedAt = Just t0} `shouldReturn` Written 2
answerCall node registrar (ownerOfSelector <> labelBytes "f") $ Reverts ""
closeRaw cc "nothing" `shouldReturn` Left "Nothing recorded: no order has the reference nothing."
logs <- capturingStderr $
closeRaw cc "inv-f"
`shouldReturn` Right
( "Closed order f, failed at " <> minuteText t0 <> ", as taken and recorded a refund of $100.00. Check at the provider that it was not refunded by hand before; if not, refund it now, by: "
<> paidBy
<> "."
)
logs `shouldSatisfy` T.isInfixOf "names: closed order f and recorded a refund of 10000 cents"
closeRaw cc "f" `shouldReturn` Left "Nothing recorded: the order of f is not a failed order paid by invoice or balance."
Balances.figures st "f" t0 `shouldReturn` Just (0, 10000, 10000, Nothing)
refundRaw cc "f" `shouldReturn` Right ("Order f: balance $0.00 (credited $100.00, refunded $100.00). Paid by: " <> paidBy <> ". Nothing to refund.")
Balances.placeOrderRow st "g" False 10000 (addUTCTime 3600 now)
unpaidG <- reg st "g"
write st unpaidG {nrPhase = PFailed, nrFailedAt = Just t0} `shouldReturn` Written 2
answerCall node registrar (ownerOfSelector <> labelBytes "g") $ Returns $ addressWord ownerA
answerCall node registrar (selector "nameExpires(uint256)" <> labelBytes "g") $ Returns $ uint256 (2000000000 :: Int)
registeredLogs <- capturingStderr $ closeRaw cc "inv-g" `shouldReturn` Left "Nothing refunded: the register of order g went through, so the order is registered now."
registeredLogs `shouldSatisfy` T.isInfixOf "names: order g set registered by //close, as its register went through"
Balances.figures st "g" t0 `shouldReturn` Nothing
testCloseNamesOff :: HasCallStack => TestParams -> IO ()
testCloseNamesOff ps = withStoreService ps $ \_ _ cc -> do
Balances.source (chatStore cc) "s" 10000
closeRaw cc "s" `shouldReturn` Left "Names are not enabled on this service."
forM_ ["", "s junk"] $ \args -> (args,) <$> closeRaw cc args `shouldReturn` (args, Left badgeCmdUsage)
Balances.figures (chatStore cc) "s" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
minuteText :: UTCTime -> Text
minuteText = T.pack . formatTime defaultTimeLocale "%Y-%m-%d %H:%M UTC"
@@ -582,7 +582,7 @@ testHeldText :: IO ()
testHeldText = do
let held overdue funded = heldText BalanceHold {bhHolder = RegistrationId "h", bhUntil = UTCTime (fromGregorian 2027 1 2) 3600, bhOverdue = overdue, bhFunded = funded}
held False False `shouldBe` "held by order h, its invoice open until 2027-01-02 01:00 UTC; run the command again then"
held True False `shouldBe` "held by order h, its invoice expired at 2027-01-02 01:00 UTC; start the service so the poller closes that order, 10 minutes after the expiry at the earliest, then stop it and run //refund again"
held True False `shouldBe` "held by order h, its invoice expired at 2027-01-02 01:00 UTC; start the service so the poller closes that order, 10 minutes after the expiry at the earliest, then stop it and run the command again"
held False True `shouldBe` "held by order h, whose invoice holds money; it holds until that payment settles or the invoice closes; run the command again then"
testChainText :: IO ()
+141 -1
View File
@@ -6,6 +6,7 @@
module Bots.StoreService.NamesWorkerTests (namesWorkerTests) where
import Bots.StoreService.FakeEthNode
import Bots.StoreService.NamesBalancesTests (figures)
import Bots.StoreService.NamesContractsTests (availableCall, maxCommitmentAgeCall, minCommitmentAgeCall, newPolicy, noncesCall, registrarOf, unhex)
import Bots.StoreService.NamesOrdersTests
import Bots.StoreService.NamesOwnerTests (answerExpiry, answerFree, answerOwner, answerUnowned, byB, codeIn, committedPhase, dynamisOrder, failedPhase, labelBytes, move, moveTo, ownerOfSelector, paidIn, rewrite, sentRegister, stored)
@@ -42,6 +43,7 @@ import Simplex.Messaging.SimplexName (labelHash)
import Simplex.Messaging.Util (tshow)
import StoreService.Config (NamesConfig)
import StoreService.Names.Abi (abiBytes, abiTuple, addressWord, AbiValue (..), hex, selector, uint256)
import StoreService.Names.Balances (RefundRecord (..), RefundRefusal (..), recordRefund)
import StoreService.Names.Chain (Block (..), ChainClient, TxHash (..), TxRequest (..), blockAt, decodeSignedTx, newChainClient)
import StoreService.Names.Contracts (namePolicy)
import StoreService.Names.Orders (Landing (..), OrdersEnv (..), confirmLanded)
@@ -51,7 +53,7 @@ import StoreService.Names.Reveal (intentOf)
import StoreService.Names.Sender
import StoreService.Names.Signatures (OrderFields (..))
import StoreService.Names.Store
import StoreService.Names.Turns (labelTurnCount, withLabelTurn)
import StoreService.Names.Turns (labelTurnCount, turnsCount, withLabelTurn)
import StoreService.Names.Worker
import StoreService.Web.Http (createLimit, holdMicros, readLimit)
import StoreService.Web.Names (Route (..), namesApp)
@@ -134,6 +136,15 @@ workerTests = describe "StoreService names: worker" $ do
it "requeues a lapsed committed order, which reads failed, answering an old version at once after it" testRetryLapsed
it "answers registration_changed with the current view when the order changed during its checks, writing nothing" testRetryLostRace
it "runs in the name's turn, answering registration_changed for an order moved to another name meanwhile" testRetryInNameTurn
describe "close" $ do
it "closes a failed paid order taken, not live, its price credited and refunded, then refuses Try again, a move and a second refund, and accepts a new order for the name" testCloseFailed
it "closes a lapsed committed order, which reads failed, naming its lapse as its failure time" testCloseLapsed
it "closes a failed order paid from a balance, its chain naming the paying order" testCloseFromBalance
it "registers a failed order whose owner holds the name, and one whose register row mined while the owner no longer holds it, refunding nothing" testCloseLanded
it "refuses an unknown reference, an order not failed, a failed code order and a failed chain read, changing nothing" testCloseRefused
it "refuses an order changed during its chain check as changed, writing nothing" testCloseLostRace
it "refuses a balance another order holds, writing nothing, and refunds the whole balance once released" testCloseHeld
it "rolls back the taken write and the credit when the refund is refused" testCloseRollback
-- fixtures
@@ -1249,3 +1260,132 @@ testRetryInNameTurn = withWorker $ \W {wCtx = ctx@Ctx {cOrders}} -> do
(status', v') <- whileHeld (retryOf ctx moving) (void $ rewrite ctx moving $ \o -> o {nrLabelHash = labelHash "dynamis", nrLength = 7})
(status', field "error" =<< v') `shouldBe` (409, Just "registration_changed")
nrPhase <$> stored ctx moving `shouldReturn` PFailed
closeOf :: Ctx -> NameRegistration -> IO Closed
closeOf Ctx {cOrders = OrdersEnv {oeStore, oeContracts, oeTurns, oeNow}} NameRegistration {nrId = RegistrationId rid} = closeRegistration oeStore oeContracts oeTurns oeNow rid
figuresOf :: Ctx -> NameRegistration -> IO (Maybe (Int, Int, Int, Maybe BalanceHold))
figuresOf Ctx {cStore} NameRegistration {nrId = RegistrationId rid} = figures cStore rid orderTime
refundedWhole :: NameRegistration -> Int -> RefundRecord
refundedWhole r price = RefundRecord {rdRegistration = nrId r, rdCents = price, rdChain = [BalanceLink {lkRegistration = nrId r, lkPayment = nrPayment r, lkPaid = price, lkFromBalance = 0, lkLateCredits = []}]}
testCloseFailed :: IO ()
testCloseFailed = withWorker $ \W {wCtx = ctx@Ctx {cStore, cOrders}} -> do
r <- paidIn ctx aliceOrder failedPhase
let again = aliceOrder {oCommitment = commitmentOf 9, oSealed = "sealed-alicebakery-9"}
price = oPrice aliceOrder
RegistrationId rid = nrId r
placeOrder ctx again `shouldReturn` refusedWith 409 "order_exists"
closeOf ctx r `shouldReturn` CLRefunded (Just orderTime) (refundedWhole r price)
x <- stored ctx r
(nrPhase x, nrLive x, nrVersion x, nrError x) `shouldBe` (PTaken, False, nrVersion r + 1, Nothing)
figuresOf ctx r `shouldReturn` Just (0, price, price, Nothing)
turnsCount (oeTurns cOrders) `shouldReturn` 0
recordRefund (oeTurns cOrders) cStore rid price orderTime `shouldReturn` Left (RefundAmount 0)
retryOf ctx x `shouldReturn` refusedWith 400 "bad_request"
answerFree ctx "alicebakers"
to <- moveTo ctx "alicebakers" 10
move ctx keyA x to `shouldReturn` refusedWith 400 "bad_request"
closeOf ctx x `shouldReturn` CLRefused CFNotFailedPaid
stored ctx r `shouldReturn` x
figuresOf ctx r `shouldReturn` Just (0, price, price, Nothing)
fst <$> placeOrder ctx again `shouldReturn` 200
testCloseLapsed :: IO ()
testCloseLapsed = withWorker $ \W {wCtx = ctx} -> do
r <- paidIn ctx aliceOrder committedPhase
advance ctx (2 * day)
closeOf ctx r `shouldReturn` CLRefunded (Just $ addUTCTime day orderTime) (refundedWhole r (oPrice aliceOrder))
nrPhase <$> stored ctx r `shouldReturn` PTaken
testCloseFromBalance :: IO ()
testCloseFromBalance = withWorker $ \W {wCtx = ctx@Ctx {cStore}} -> do
paying <- paidIn ctx (byB dynamisOrder) failedPhase
let price = oPrice aliceOrder
withTransaction cStore $ \db -> creditBalance db (nrId paying) 30000 orderTime
withTransaction cStore (\db -> createBalanceRegistration db (aliceRegistration "covered" 1) (nrId paying) price 30000 orderTime) `shouldReturn` Right ()
covered <- registrationById ctx (RegistrationId "covered") >>= \r -> rewrite ctx r failedPhase
closeOf ctx covered
`shouldReturn` CLRefunded
(Just orderTime)
RefundRecord
{ rdRegistration = nrId covered,
rdCents = price,
rdChain =
[ BalanceLink {lkRegistration = nrId covered, lkPayment = RPBalance, lkPaid = 0, lkFromBalance = price, lkLateCredits = []},
BalanceLink {lkRegistration = nrId paying, lkPayment = nrPayment paying, lkPaid = oPrice dynamisOrder, lkFromBalance = 0, lkLateCredits = []}
]
}
nrPhase <$> stored ctx covered `shouldReturn` PTaken
figuresOf ctx covered `shouldReturn` Just (0, price, price, Nothing)
figuresOf ctx paying `shouldReturn` Just (30000 - price, 30000, 0, Nothing)
testCloseLanded :: IO ()
testCloseLanded = withWorker $ \W {wCtx = ctx} -> do
owned <- paidIn ctx aliceOrder failedPhase
answerOwner ctx "alicebakery" (nrOwner owned)
answerExpiry ctx "alicebakery" expiry
closeOf ctx owned `shouldReturn` CLRegistered (nrId owned)
x <- stored ctx owned
(nrPhase x, nrExpiresAt x, nrLive x) `shouldBe` (PRegistered, Just expiry, False)
figuresOf ctx owned `shouldReturn` Nothing
minedOrder <- paidIn ctx dynamisOrder failedPhase
answerUnowned ctx "dynamis"
answerExpiry ctx "dynamis" expiry
minedHash <- sentRegister ctx minedOrder 1 TSMined
closeOf ctx minedOrder `shouldReturn` CLRegistered (nrId minedOrder)
y <- stored ctx minedOrder
(nrPhase y, nrRegisterTx y, nrExpiresAt y) `shouldBe` (PRegistered, Just minedHash, Just expiry)
figuresOf ctx minedOrder `shouldReturn` Nothing
testCloseRefused :: IO ()
testCloseRefused = withWorker $ \W {wCtx = ctx@Ctx {cNode, cOrders = OrdersEnv {oeStore, oeContracts, oeTurns, oeNow}}} -> do
closeRegistration oeStore oeContracts oeTurns oeNow "t2Jk8RmQ4vXw9NcP3yLb6g" `shouldReturn` CLRefused CFNoOrder
queued <- paidIn ctx aliceOrder id
(failedCode, _) <- codeIn ctx 8 (byB aliceOrder) {oCommitment = commitmentOf 2} failedPhase
unread <- paidIn ctx dynamisOrder failedPhase
answerCall cNode (registrarOf cNode) (ownerOfSelector <> labelBytes "dynamis") $ Reverts $ unhex "37ed32e8"
forM_ [(queued, CFNotFailedPaid), (failedCode, CFNotFailedPaid), (unread, CFUnread)] $ \(r, refusal) -> do
(nrId r,) <$> closeOf ctx r `shouldReturn` (nrId r, CLRefused refusal)
stored ctx r `shouldReturn` r
figuresOf ctx r `shouldReturn` Nothing
testCloseLostRace :: IO ()
testCloseLostRace = withWorker $ \W {wCtx = ctx@Ctx {cNode}} -> do
r <- paidIn ctx aliceOrder failedPhase
(closing, gate) <- pausedAt cNode "eth_call" $ closeOf ctx r
changed <- rewrite ctx r id
releaseGate gate
timeout prompt (wait closing) >>= maybe (fail "the close did not finish") pure >>= (`shouldBe` CLRefused CFChanged)
stored ctx r `shouldReturn` changed
figuresOf ctx r `shouldReturn` Nothing
testCloseRollback :: IO ()
testCloseRollback = withWorker $ \W {wCtx = ctx} -> do
r <- paidIn ctx aliceOrder $ \o -> (failedPhase o) {nrPrice = 0}
closeOf ctx r `shouldReturn` CLRefused CFBalanceChanged
stored ctx r `shouldReturn` r
figuresOf ctx r `shouldReturn` Nothing
testCloseHeld :: IO ()
testCloseHeld = withWorker $ \W {wCtx = ctx@Ctx {cStore}} -> do
r <- paidIn ctx dynamisOrder failedPhase
answerUnowned ctx "dynamis"
let diffPrice = oPrice aliceOrder
expiresAt = addUTCTime 3600 orderTime
hold = BalanceHold {bhHolder = RegistrationId "diff", bhUntil = expiresAt, bhOverdue = False, bhFunded = False}
whole = 4000 + oPrice dynamisOrder
withTransaction cStore $ \db -> do
creditBalance db (nrId r) 4000 orderTime
insertInvoiceRow db "inv-diff" expiresAt "open"
createPaidRegistration db (aliceRegistration "diff" 2) (OTBalance (nrId r) diffPrice 4000 (Just btc)) (paidOrder "inv-diff") {poPrice = diffPrice} orderTime `shouldReturn` Right ()
closeOf ctx r `shouldReturn` CLRefused (CFHeld hold)
stored ctx r `shouldReturn` r
figuresOf ctx r `shouldReturn` Just (4000, 4000, 0, Just hold)
withTransaction cStore (\db -> releaseHeldBalance db (RegistrationId "diff") orderTime) `shouldReturn` True
closeOf ctx r >>= \case
CLRefunded _ RefundRecord {rdCents} -> rdCents `shouldBe` whole
other -> expectationFailure $ "not refunded: " <> show other
nrPhase <$> stored ctx r `shouldReturn` PTaken
figuresOf ctx r `shouldReturn` Just (0, whole, whole, Nothing)