Skip to content

Instantly share code, notes, and snippets.

@tonsky
Created August 15, 2021 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonsky/1e9ca71f8912ccfc7bdc2288b53203b0 to your computer and use it in GitHub Desktop.
Save tonsky/1e9ca71f8912ccfc7bdc2288b53203b0 to your computer and use it in GitHub Desktop.
(def ^:private last-window-ms 120000)
(def ^:private max-last-txs 3)
defn- authorize-tx [authorizer tx]
(let [{:keys [active-card available-limit]} authorizer
{:keys [amount time]} tx]
(cond
(nil? active-card)
(assoc authorizer
:violations [:account-not-initialized])
(false? active-card)
(assoc authorizer
:violations [:card-not-active])
(> amount available-limit)
(assoc authorizer
:violations [:insufficient-limit])
:else
(let [window-start (java.util.Date. (- (.getTime time) last-window-ms))
authorizer' (-> authorizer
(update :last-txs clear-until window-start))]
(cond
(has-similar? (:last-txs authorizer') tx)
(assoc authorizer
:violations [:doubled-transaction])
(>= (count (:last-txs authorizer')) max-last-txs)
(assoc authorizer
:violations [:high-frequency-small-interval])
:else
(-> authorizer'
(update :last-txs conj tx)
(update :available-limit - (bigint amount))
(assoc :violations [])))))))
last_window_sec = 120
max_last_txs = 3
fun authorize_tx(authorizer, tx):
active_card = authorizer.active_card
available_limit = authorizer.available_limit
amount = tx.amount
time = tx.time
if None == active_card:
authorizer.violations = ["account-not-initialized"]
return
if False == active_card:
authorizer.violations = ["card-not-active"]
return
if amount > available_limit:
authorizer.violations = ["insufficient-limit"]
return
window_start = time.time() - last_window_sec
clear_until(authorizer, window_start)
if has_similar(authorizer.last_txs, tx):
authorizer.violations = ["doubled-transaction"]
return
if len(authorizer.last_txs) > max_last_txs:
authorizer.violations = ["high-frequency-small-interval"]
return
authorizer.last_txs.add(tx)
authorizer.available_limit -= amount
authorizer.violations = []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment