ekzyis d89a4a429a
Wallet v2 (#2169)
* Migrate vault entries to new schema (#2092)

* Migrate existing vault entries to new schema

* Read+write new vault schema

* Drop VaultEntry table

* Refactor vaultPrismaFragments

* Remove wrong comment

* Remove TODO

* Fix possible race condition on update of vault key

* Remove lib/object.js

* Wallet schema v2 (#2146)

* Add wallet-v2 TODOs

* Update checkWallet

* Wallet list

* Delete almost all wallet v1 code

and add some code for wallet protocol forms

* Define protocol display name in JSON

* Show form per protocol

* Increase max-height of image in form

* Add JSdoc for protocols, form validation

* Use wallet cards again

My wallet list was quite ugly and I couldn't look at it anymore.

* Refactor hooks in wallet provider

* Fix PasswordInput not used

* Read encrypted wallets

* Decrypt wallets

* useWalletQuery now returns decrypted wallets
* Refactor useIndexedDB because its only purpose will be to store the key, so no need for pagination code etc.
* There is still a bug: if the wallet is not decrypted on first render, the form will not see the decrypted value. See TODO.

* Rename protocolJson to protocol

it no longer uses a JSON file

* Fix form not updated with decrypted API key

* Fix wallet template forms

* Fix optional shown as hint

* Rename to mapUserWalletResolveTypes

* Save LNbits send and recv

TODO:

* implement resolvers for other protocols
* fix double update required for trigger?
* add missing validation on server
* add missing network tests
* don't import from wallets/client on server

* Move definitions to lib/wallets.json and lib/protocols

* Fix ProtocolWallet.updated_at not updated by trigger

* Move wallet fragments into wallets/client/fragments/

* move invoice fragments to fragments/invoice.js
* remove some unused fragments that I don't think I also will not use
* move fragments that will be generated in own file

* Move wallet resolvers into wallets/server/resolvers

* Fix missing authorization check on wallet update

* Run all shared code in generic wallet update function

* Fix 'encrypt' flag not set for blink send currency

* Add mutations for all protocols

* Fix macaroon validation

* Fix CLN socket value not set

* Add server-side schema validation

* Fix JSDoc typedef for protocols

* Don't put JSDoc into separate file

* Create test invoices on save

* Also move type resolvers into wallets/server/resolvers

* Fix unconfigured protocols of UserWallet not found

* Fix Blink API key in wallet seed

* Test send payment on save (except LNC)

This does not include LNC because LNC cannot be saved yet

* Check if window.webln is defined on save

* Create new wallets from templates

* Separate protocols in wallets/lib into individual files

* Use justify-content-start for protocol tabs

and larger margin at the top

* Add LNC to client protocols

* Only return wallets from useWallets

* Query decrypted wallets

* Payments with new wallets

* More wallet logos

* Fix TypeError in useIndexedDB

* Add protocol attach docs

* Fix undefined useWalletRecvPrompt import

* Remove outdated TODOs

* First successful zap to new wallets

* Fix walletLogger imports

* Fix sequences

* the sequences for InvoiceForward and DirectPayment were still starting at 1
* when using setval() with two arguments, nextval() will return the second argument+1 (see https://www.postgresql.org/docs/current/functions-sequence.html)

* Rename ProtocolWallet columns

* Remove more outdated TODOs

* Update wallet indicator

* Fix page reset on route change

* Refactor __typename checks into functions

* Refactor protocol selection into own hook

* Add button to detach protocol

* Refetch wallet on save and detach

* Refetch wallets on change

* Always show all templates

* Refactor WalletLink component

* Also put wallet into forms context

* Remove outdated TODOs

* Use useMemo in wallets hooks

* Passphrase modals

* prompt for password if decryption failed
* add button to reveal passphrase on wallet page

TODO:
* remove button if passphrase was revealed or imported
* encrypt wallets with new key on passphrase reveal

* Fix protocol missing as callback dependency

* Encrypt wallets with new key on passphrase export

* Update 'unlock wallets' text

* Rename wallet mutation hooks

* Remove 'removeWallet' mutation

Wallets are automatically deleted when all protocols are deleted

* Passphrase reset

* Use 110px as minimum width for bip39 words

longest bip39 words are 8 characters and they fit into 103px so I rounded up to 110px.

* Also disable passphrase export on save

* Wallet settings

* Fix wallet receive prompt

* Remove unused parameters from postgres function

* Rename UserWallet to Wallet, ProtocolWallet to WalletProtocol

* Use danger variant for button to show passphrase

* Fix inconsistent imports and exports

* Remove outdated TODOs

* wallet logs

* Remove outdated comment

* Make sure wallets are used in priority order

* Separate wallets from templates in reducer

* Fix missing useCallback dependencies

* Refactor with useWalletLogger hook

* Move enabled to WalletProtocol

* Add checkbox to enable/disable protocol

* Fix migration with prod db dump

* Parse Coinos relay URLs

* Skip network tests if only enabled changed

* Allow IndexedDB calls without session

* Add code to migrate old CryptoKey

* first try to use existing CryptoKey before generating a new one
* bump IDB version to delete old object stores and create new ones
* return IDB callbacks with useMemo
* don't delete old IDB right away, wait until next release

* Fix ghost import error

*Sometimes*, I get import errors because it tries to resolve @/wallets/server to wallets/server.js instead of wallets/server/index.js.

For the files in wallets/server, it kind of makes sense because it's a circular import.

But I don't know why the files in worker/ have this problem.

Interestingly, it only seems to happen with walletLogger imports, so I guess its related to its import chain.

Anyway, this commit should make sure this never happens again ...

* Skip wallets queries if not logged in

* Split CUSTOM wallet into NWC and LN_ADDR

* Migrate local wallets

* Link to /wallets/:id/receive if send not supported

* Hide separator if there are no configured wallets

* Save LNC

* Add one-liner to attach LNC

* Update wallet priorities via DnD

* Wallet logs are part of protocol resolvers

* Fix logging to deleted protocol

* Fix trying to fetch logs for template

* also change type to Int so GraphQL layer can catch trying to fetch string IDs as is the case for templates

* Fix embedded flag for wallets logs not set

* Remove TODO

* Decrease max-height for embedded wallet logs on big screens

* Fix missing refetch on wallet priority update

* Set priorities of all wallets in one tx

* Fix nested state update

* Add DragIcon

* DnD mobile support and refactor

* Add CancelButton to wallet settings

* Remount form if path changes

This fixes the following warning in the console:

"""
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
"""

* Support string and object for wallet.image JSON

* Append domain to lightning address inputs

* Remove outdated TODOs

* Add template IDs to wallet JSON

* Fix missing callback dependency

* Implement lightning address save in receive prompt

* Update TODOs

* Fix missing check for enabled

* Pay QR codes with WebLN as anon

* Add logo for NWC

* Fix trying to save logs for template

* Add template logs

* Fix inconsistent margin

* Always throw on missing key

* Remove misleading comment

Wallets are returned even if decryption fails so we can show the unlock page if a wallet is stored as encrypted in the context.

Maybe I should rethink this.

* Check for existing wallets on local wallet migration

* Fix local wallet migration causing duplicates

* Fix protocol reattached on detach due to migration

* Fix form not centered

* Fix ZEUS lightning address domain

* Add placeholder, help, hints etc. to wallet form inputs

* Fix wallet badges not updated

* Remove unused declared variables

* Rename to ATTACH_PAGE

* Fix 500 error if no amount was given to LNURLp endpoint

* Tag log messages with wallet name

* Only skip network tests if we're disabling the wallet

* Rename var to networkTests

* Continue to store key hash in IndexedDB

* Rethink wallet state management

If decryption failed, the function to decrypt the wallets didn't throw but simply returned wallets that were still encrypted.

This was bad because it meant we could not rely on the wallets in the state being decrypted, even though this was the original idea behind the query hooks: hide the details of encryption and decryption inside them.

Because of this, we had to check if the wallets were still encrypted before we ran the wallet migration since we want to check if a protocol already exists.

This commit fixes this by making encryption and decryption always throw (and catching the errors), as well as returning a ready state from hooks. A hook might not be ready because it still needs to load something (in the case of the crypto hooks, it's loading the key from IndexedDB). Callers check that ready state before they call the function returned by the hook.

So now, the wallet migration hook can itself simply check if the hook to encrypt wallets is ready and if the wallets are no longer loading to let callers know if it itself is ready.

Since we also relied on wallets stored as encrypted in the context to show the unlock page, this was also changed by comparing the local and remote key hash.

* Add empty line

* Save new key hash during wallet reset

* Only receive protocol upserts require networkTests param

* Compare key hashes on server on each save

* Delete old code

* Fix card shows attach instead of configure

* Fix empty wallets created during migration

The old schema can contain '' instead of NULL in the columns of wallets for receiving.

* Update reset passphrase text

* Wrap passphrase reset in try/catch

* Fix migrate called multiple times

* Update key hash on migration if not set

* Fetch local wallets in migrate

* Fix missing await on setKey

* Let first device set key hash

* Fix indicator not shown if wallets locked

* Check if IndexedDB is available

* Fix inconsistent WebLN error message

* Disable WebLN if not available

* Remove outdated TODO

* Cursor-based pagination for wallet logs

* Fix log message x-overflow

* Add context to wallet logs

* Wrap errors are warnings in logs

* Rename wallet v2 migrations

* Update wallet status during logging

* Fix wallet logs loading state

The loading state would go from false -> true -> false because it's false when the lazy query wasn't called yet.

* Add wallet search

* Add Alby Go wallet

* Revert "Add Alby Go wallet"

This reverts commit 926c70638f1673756480c848237e52d5889dc037.

* Fix wallet logs sent by client don't update protocol status

* Fix mutation name

* put drag icon on opposite corner

* Add wallets/README.md

* Fix inconsistent case in wallets/README.md

* Fix autoprefixer warning about mixed support

This warning was in the app logs:

app     | Warning
app     |
app     | (31:3) autoprefixer: end value has mixed support, consider using flex-end instead
app     |
app     | Import trace for requested module:
app     | ./styles/wallet.module.css
app     | ./wallets/client/hooks/prompt.js
app     | ./wallets/client/hooks/index.js
app     | ./wallets/client/context/hooks.js
app     | ./wallets/client/context/provider.js
app     | ./wallets/client/context/index.js

* fix effect of wallet indicators on logo

* Fix deleting wallet template logs

* Use name as primary key of WalletTemplate

* Fix wallet_clear_vault trigger not mentioned in README

* Fix wallet receive prompt

Also remove no longer needed templateId from wallets.json and helper functions

* Use findUnique since name is now primary key

* Merge Alby wallets into one

* Remove unused name parameter from WalletsForm component

* Fix number check to decide if wallet or template

* Update wallet encryption on click, not as effect

* add cashu.me and lightning address logos

* add images

* Use recommended typeof to check if IDB available

* Also check if IDB available on delete

* Use constraint triggers

* Add indices on columns used for joins

* Fix inconsistent CLEAR OR REPLACE TRIGGER

* Attach wallet_check_support trigger to WalletProtocol table

* Update wallets/README.md

* Remove debugging code

* Refactor reducer: replace page with status

* Show 'wallets unavailable' if device does not support IndexedDB

* Remove duplicate ELSIF condition

* Fix hasSendWallet

The useSendWallets hook was not checking if the returned send wallets are enabled.

Since the components that used that hook only need to know if there is a send wallet, I replaced the useSendWallets hook with a useHasSendWallet hook.

* Add Cash App wallet

* fix changes loglevel enum

* Fix key init race condition in strict mode if no key exists yet

* Formatting

* Fix key init race condition via transactions in readwrite mode

* Replace Promise.withResolvers with regular promises

* replace generic spinner with our usual

---------

Co-authored-by: k00b <k00b@stacker.news>
2025-07-15 16:36:43 -05:00
..
2025-03-15 08:11:33 -05:00
2025-07-15 16:36:43 -05:00
2025-03-15 08:11:33 -05:00
2025-07-15 16:36:43 -05:00

Paid Actions

Paid actions are actions that require payments to perform. Given that we support several payment flows, some of which require more than one round of communication either with LND or the client, and several paid actions, we have this plugin-like interface to easily add new paid actions.

internals

All paid action progress, regardless of flow, is managed using a state machine that's transitioned by the invoice progress and payment progress (in the case of p2p paid action). Below is the full state machine for paid actions:

stateDiagram-v2
    [*] --> PENDING
    PENDING --> PAID
    PENDING --> CANCELING
    PENDING --> FAILED
    PAID --> [*]
    CANCELING --> FAILED
    FAILED --> RETRYING
    FAILED --> [*]
    RETRYING --> [*]
    [*] --> PENDING_HELD
    PENDING_HELD --> HELD
    PENDING_HELD --> FORWARDING
    PENDING_HELD --> CANCELING
    PENDING_HELD --> FAILED
    HELD --> PAID
    HELD --> CANCELING
    HELD --> FAILED
    FORWARDING --> FORWARDED
    FORWARDING --> FAILED_FORWARD
    FORWARDED --> PAID
    FAILED_FORWARD --> CANCELING
    FAILED_FORWARD --> FAILED

Payment Flows

There are three payment flows:

Fee credits

The stacker has enough fee credits to pay for the action. This is the simplest flow and is similar to a normal request.

Optimistic

The optimistic flow is useful for actions that require immediate feedback to the client, but don't require the action to be immediately visible to everyone else.

For paid actions that support it, if the stacker doesn't have enough fee credits, we store the action in a PENDING state on the server, which is visible only to the stacker, then return a payment request to the client. The client then pays the invoice however and whenever they wish, and the server monitors payment progress. If the payment succeeds, the action is executed fully becoming visible to everyone and is marked as PAID. Otherwise, the action is marked as FAILED, the client is notified the payment failed and the payment can be retried.

Internals

Internally, optimistic flows make use of a state machine that's transitioned by the invoice payment progress.

stateDiagram-v2
    [*] --> PENDING
    PENDING --> PAID
    PENDING --> CANCELING
    PENDING --> FAILED
    PAID --> [*]
    CANCELING --> FAILED
    FAILED --> RETRYING
    FAILED --> [*]
    RETRYING --> [*]

Pessimistic

For paid actions that don't support optimistic actions (or when the stacker is @anon), if the client doesn't have enough fee credits, we return a payment request to the client without performing the action and only storing the action's arguments. After the client pays the invoice, the server performs the action with original arguments. Pessimistic actions require the payment to complete before being visible to them and everyone else.

Internally, pessimistic flows use hold invoices. If the action doesn't succeed, the payment is cancelled and it's as if the payment never happened (ie it's a lightning native refund mechanism).

Internals

Internally, pessimistic flows make use of a state machine that's transitioned by the invoice payment progress much like optimistic flows, but with extra steps.

stateDiagram-v2
    PAID --> [*]
    CANCELING --> FAILED
    FAILED --> [*]
    [*] --> PENDING_HELD
    PENDING_HELD --> HELD
    PENDING_HELD --> CANCELING
    PENDING_HELD --> FAILED
    HELD --> PAID
    HELD --> CANCELING
    HELD --> FAILED

Table of existing paid actions and their supported flows

action fee credits optimistic pessimistic anonable qr payable p2p wrapped side effects reward sats p2p direct
zaps x x x x x x x
posts x x x x x x x
comments x x x x x x x
downzaps x x x x x
poll votes x x x x
territory actions x x x x
donations x x x x x
update posts x x x x x
update comments x x x x x
receive x x x x
buy fee credits x x x
invite gift x x x

Not-custodial zaps (ie p2p wrapped payments)

Zaps, and possibly other future actions, can be performed peer to peer and non-custodially. This means that the payment is made directly from the client to the recipient, without the server taking custody of the funds. Currently, in order to trigger this behavior, the recipient must have a receiving wallet attached and the sender must have insufficient funds in their custodial wallet to perform the requested zap.

This works by requesting an invoice from the recipient's wallet and reusing the payment hash in a hold invoice paid to SN (to collect the sybil fee) which we serve to the sender. When the sender pays this wrapped invoice, we forward our own money to the recipient, who then reveals the preimage to us, allowing us to settle the wrapped invoice and claim the sender's funds. This effectively does what a lightning node does when forwarding a payment but allows us to do it at the application layer.

Internals

Internally, p2p wrapped payments make use of the same paid action state machine but it's transitioned by both the incoming invoice payment progress and the outgoing invoice payment progress.

stateDiagram-v2
    PAID --> [*]
    CANCELING --> FAILED
    FAILED --> RETRYING
    FAILED --> [*]
    RETRYING --> [*]
    [*] --> PENDING_HELD
    PENDING_HELD --> FORWARDING
    PENDING_HELD --> CANCELING
    PENDING_HELD --> FAILED
    FORWARDING --> FORWARDED
    FORWARDING --> FAILED_FORWARD
    FORWARDED --> PAID
    FAILED_FORWARD --> CANCELING
    FAILED_FORWARD --> FAILED

Paid Action Interface

Each paid action is implemented in its own file in the paidAction directory. Each file exports a module with the following properties:

Boolean flags

  • anonable: can be performed anonymously

Payment methods

  • paymentMethods: an array of payment methods that the action supports ordered from most preferred to least preferred
    • P2P: a p2p payment made directly from the client to the recipient
      • after wrapping the invoice, anonymous users will follow a PESSIMISTIC flow to pay the invoice and logged in users will follow an OPTIMISTIC flow
    • FEE_CREDIT: a payment made from the user's fee credit balance
    • OPTIMISTIC: an optimistic payment flow
    • PESSIMISTIC: a pessimistic payment flow

Functions

All functions have the following signature: function(args: Object, context: Object): Promise

  • getCost: returns the cost of the action in msats as a BigInt
  • perform: performs the action
    • returns: an object with the result of the action as defined in the graphql schema
    • if the action supports optimism and an invoiceId is provided, the action should be performed optimistically
      • any action data that needs to be hidden while it's pending, should store in its rows a PENDING state along with its invoiceId
      • it can optionally store in the invoice with the invoiceId the actionId to be able to link the action with the invoice regardless of retries
  • onPaid: called when the action is paid
    • if the action does not support optimism, this function is optional
    • this function should be used to mark the rows created in perform as PAID and perform critical side effects of the action (like denormalizations)
  • nonCriticalSideEffects: called after the action is paid to run any side effects whose failure does not affect the action's execution
    • this function is always optional
    • it's passed the result of the action (or the action's paid invoice) and the current context
    • this is where things like push notifications should be handled
  • onFail: called when the action fails
    • if the action does not support optimism, this function is optional
    • this function should be used to mark the rows created in perform as FAILED
  • retry: called when the action is retried with any new invoice information
    • return: an object with the result of the action as defined in the graphql schema (same as perform)
    • this function is called when an optimistic action is retried
    • it's passed the original invoiceId and the newInvoiceId
    • this function should update the rows created in perform to contain the new newInvoiceId and remark the row as PENDING
  • getInvoiceablePeer: returns the userId of the peer that's capable of generating an invoice so they can be paid for the action
    • this is only used for p2p wrapped zaps currently
  • describe: returns a description as a string of the action
    • for actions that require generating an invoice, and for stackers that don't hide invoice descriptions, this is used in the invoice description
  • getSybilFeePercent (required if getInvoiceablePeer is implemented): returns the action sybil fee percent as a BigInt (eg. 30n for 30%)

Function arguments

args contains the arguments for the action as defined in the graphql schema. If the action is optimistic or pessimistic, args will contain an invoiceId field which can be stored alongside the paid action's data. If this is a call to retry, args will contain the original invoiceId and newInvoiceId fields.

context contains the following fields:

  • me: the user performing the action (undefined if anonymous)
  • cost: the cost of the action in msats as a BigInt
  • sybilFeePercent: the sybil fee percent as a BigInt (eg. 30n for 30%)
  • tx: the current transaction (for anything that needs to be done atomically with the payment)
  • models: the current prisma client (for anything that doesn't need to be done atomically with the payment)
  • lnd: the current lnd client

Recording Cowboy Credits

To avoid adding sats and credits together everywhere to show an aggregate sat value, in most cases we denormalize a sats field that carries the "sats value", the combined sats + credits of something, and a credits field that carries only the earned credits. For example, the Item table has an msats field that carries the sum of the mcredits and msats earned and a mcredits field that carries the value of the mcredits earned. So, the sats value an item earned is item.msats BUT the real sats earned is item.msats - item.mcredits.

The ONLY exception to this are for the users table where we store a stacker's rewards sats and credits balances separately.

IMPORTANT: transaction isolation

We use a read committed isolation level for actions. This means paid actions need to be mindful of concurrency issues. Specifically, reading data from the database and then writing it back in read committed is a common source of consistency bugs (aka serialization anamolies).

This is a big deal

  1. If you read from the database and intend to use that data to write to the database, and it's possible that a concurrent transaction could change the data you've read (it usually is), you need to be prepared to handle that (see phantom reads).
  2. This applies to ALL, and I really mean ALL, read data regardless of how you read the data within the read committed transaction:
    • independent statements
    • WITH queries (CTEs) in the same statement
    • subqueries in the same statement

How to handle it

  1. take row level locks on the rows you read, using something like a SELECT ... FOR UPDATE statement
  2. check that the data you read is still valid before writing it back to the database i.e. optimistic concurrency control
    • NOTE: this does not protect against missing concurrent inserts. It only prevents concurrent updates to the rows you've already read.
  3. avoid having to read data from one row to modify the data of another row all together

Example

Let's say you are aggregating total sats for an item from a table zaps and updating the total sats for that item in another table item_zaps. Two 100 sat zaps are requested for the same item at the same time in two concurrent transactions. The total sats for the item should be 200, but because of the way read committed works, the following statements lead to a total sats of 100:

the statements here are listed in the order they are executed, but each transaction is happening concurrently

Incorrect

-- transaction 1
BEGIN;
INSERT INTO zaps (item_id, sats) VALUES (1, 100);
SELECT sum(sats) INTO total_sats FROM zaps WHERE item_id = 1;
-- total_sats is 100
-- transaction 2
BEGIN;
INSERT INTO zaps (item_id, sats) VALUES (1, 100);
SELECT sum(sats) INTO total_sats FROM zaps WHERE item_id = 1;
-- total_sats is still 100, because transaction 1 hasn't committed yet
-- transaction 1
UPDATE item_zaps SET sats = total_sats WHERE item_id = 1;
-- sets sats to 100
-- transaction 2
UPDATE item_zaps SET sats = total_sats WHERE item_id = 1;
-- sets sats to 100
COMMIT;
-- transaction 1
COMMIT;
-- item_zaps.sats is 100, but we would expect it to be 200

Note that row level locks wouldn't help in this case, because we can't lock the rows that the transactions don't know to exist yet.

Subqueries are still incorrect

-- transaction 1
BEGIN;
INSERT INTO zaps (item_id, sats) VALUES (1, 100);
UPDATE item_zaps SET sats = (SELECT sum(sats) INTO total_sats FROM zaps WHERE item_id = 1) WHERE item_id = 1;
-- item_zaps.sats is 100
-- transaction 2
BEGIN;
INSERT INTO zaps (item_id, sats) VALUES (1, 100);
UPDATE item_zaps SET sats = (SELECT sum(sats) INTO total_sats FROM zaps WHERE item_id = 1) WHERE item_id = 1;
-- item_zaps.sats is still 100, because transaction 1 hasn't committed yet
-- transaction 1
COMMIT;
-- transaction 2
COMMIT;
-- item_zaps.sats is 100, but we would expect it to be 200

Note that while the UPDATE transaction 2's update statement will block until transaction 1 commits, the subquery is computed before it blocks and is not re-evaluated after the block.

Correct

-- transaction 1
BEGIN;
INSERT INTO zaps (item_id, sats) VALUES (1, 100);
-- transaction 2
BEGIN;
INSERT INTO zaps (item_id, sats) VALUES (1, 100);
-- transaction 1
UPDATE item_zaps SET sats = sats + 100 WHERE item_id = 1;
-- transaction 2
UPDATE item_zaps SET sats = sats + 100 WHERE item_id = 1;
COMMIT;
-- transaction 1
COMMIT;
-- item_zaps.sats is 200

The above works because UPDATE takes a lock on the rows it's updating, so transaction 2 will block until transaction 1 commits, and once transaction 2 is unblocked, it will re-evaluate the sats value of the row it's updating.

More resources

From the postgres docs:

UPDATE, DELETE, SELECT FOR UPDATE, and SELECT FOR SHARE commands behave the same as SELECT in terms of searching for target rows: they will only find target rows that were committed as of the command start time. However, such a target row might have already been updated (or deleted or locked) by another concurrent transaction by the time it is found. In this case, the would-be updater will wait for the first updating transaction to commit or roll back (if it is still in progress). If the first updater rolls back, then its effects are negated and the second updater can proceed with updating the originally found row. If the first updater commits, the second updater will ignore the row if the first updater deleted it, otherwise it will attempt to apply its operation to the updated version of the row. The search condition of the command (the WHERE clause) is re-evaluated to see if the updated version of the row still matches the search condition. If so, the second updater proceeds with its operation using the updated version of the row. In the case of SELECT FOR UPDATE and SELECT FOR SHARE, this means it is the updated version of the row that is locked and returned to the client.

From the postgres source docs:

It is also possible that there are relations in the query that are not to be locked (they are neither the UPDATE/DELETE/MERGE target nor specified to be locked in SELECT FOR UPDATE/SHARE). When re-running the test query we want to use the same rows from these relations that were joined to the locked rows.

IMPORTANT: deadlocks

Deadlocks can occur when two transactions are waiting for each other to release locks. This can happen when two transactions lock rows in different orders whether explicit or implicit.

If both transactions lock the rows in the same order, the deadlock is avoided.

Incorrect

-- transaction 1
BEGIN;
UPDATE users set msats = msats + 1 WHERE id = 1;
-- transaction 2
BEGIN;
UPDATE users set msats = msats + 1 WHERE id = 2;
-- transaction 1 (blocks here until transaction 2 commits)
UPDATE users set msats = msats + 1 WHERE id = 2;
-- transaction 2 (blocks here until transaction 1 commits)
UPDATE users set msats = msats + 1 WHERE id = 1;
-- deadlock occurs because neither transaction can proceed to here

In practice, this most often occurs when selecting multiple rows for update in different orders. Recently, we had a deadlock when spliting zaps to multiple users. The solution was to select the rows for update in the same order.

Incorrect

WITH forwardees AS (
    SELECT "userId", (($1::BIGINT * pct) / 100)::BIGINT AS msats
    FROM "ItemForward"
    WHERE "itemId" = $2::INTEGER
),
UPDATE users
    SET
    msats = users.msats + forwardees.msats,
    "stackedMsats" = users."stackedMsats" + forwardees.msats
    FROM forwardees
    WHERE users.id = forwardees."userId";

If forwardees are selected in a different order in two concurrent transactions, e.g. (1,2) in tx 1 and (2,1) in tx 2, a deadlock can occur. To avoid this, always select rows for update in the same order.

Correct

We fixed the deadlock by selecting the forwardees in the same order in these transactions.

WITH forwardees AS (
    SELECT "userId", (($1::BIGINT * pct) / 100)::BIGINT AS msats
    FROM "ItemForward"
    WHERE "itemId" = $2::INTEGER
    ORDER BY "userId" ASC
),
UPDATE users
    SET
    msats = users.msats + forwardees.msats,
    "stackedMsats" = users."stackedMsats" + forwardees.msats
    FROM forwardees
    WHERE users.id = forwardees."userId";

More resources