state.go35 lines, 1.2 KB
| 1 | // Package transfer runs transfers between wallets as sagas. |
| 2 | package transfer |
| 3 | |
| 4 | import "slices" |
| 5 | |
| 6 | // State is where a transfer is in its saga. |
| 7 | type State string |
| 8 | |
| 9 | const ( |
| 10 | Pending State = "pending" // accepted: nothing has moved yet |
| 11 | InReview State = "in_review" // held, until a person decides, or time runs out |
| 12 | FundsHeld State = "funds_held" // the money left the sender, into a hold |
| 13 | Completed State = "completed" // the receiver has it |
| 14 | Compensating State = "compensating" // a later step failed: giving the hold back |
| 15 | Failed State = "failed" // refused before anything moved |
| 16 | Reversed State = "reversed" // the hold went back to the sender |
| 17 | ) |
| 18 | |
| 19 | // transitions is the state machine: every move a transfer can make. |
| 20 | var transitions = map[State][]State{ |
| 21 | Pending: {FundsHeld, InReview, Failed}, |
| 22 | InReview: {FundsHeld, Compensating}, |
| 23 | FundsHeld: {Completed, Compensating}, |
| 24 | Compensating: {Reversed}, |
| 25 | } |
| 26 | |
| 27 | // CanBecome reports whether a transfer in state s may move to next. |
| 28 | func (s State) CanBecome(next State) bool { |
| 29 | return slices.Contains(transitions[s], next) |
| 30 | } |
| 31 | |
| 32 | // Final reports whether the saga is over. |
| 33 | func (s State) Final() bool { |
| 34 | return len(transitions[s]) == 0 |
| 35 | } |