Class: Wallets::Wallet

Inherits:
ApplicationRecord show all
Defined in:
lib/wallets/models/wallet.rb

Overview

Wallet is the owner-facing API for one asset balance.

Balances are not maintained by incrementing a counter in place. Instead, the wallet derives its current balance from transactions and allocations so it can support FIFO consumption, expirations, transfers, and a durable audit trail at the same time.

This class supports embedding: subclasses can override config, callbacks, table names, and related model classes without affecting the base Wallets::* behavior in the same application.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.allocation_classObject



51
52
53
# File 'lib/wallets/models/wallet.rb', line 51

def self.allocation_class
  allocation_class_name.constantize
end

.create_for_owner!(owner:, asset_code:, initial_balance: 0, metadata: {}) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/wallets/models/wallet.rb', line 89

def create_for_owner!(owner:, asset_code:, initial_balance: 0, metadata: {})
  initial_balance = normalize_initial_balance(initial_balance)
  asset_code = normalize_asset_code(asset_code)
   = .respond_to?(:to_h) ? .to_h : {}

  existing_wallet = find_by(owner: owner, asset_code: asset_code)
  return existing_wallet if existing_wallet.present?

  transaction do
    wallet = create!(
      owner: owner,
      asset_code: asset_code,
      balance: 0,
      metadata: 
    )

    if initial_balance.positive?
      wallet.credit(initial_balance, **initial_balance_credit_attributes)
    end

    wallet
  rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid => error
    wallet = find_by(owner: owner, asset_code: asset_code)
    raise error if wallet.nil?

    if record_conflict_due_to_existing_wallet?(error)
      wallet
    else
      raise error
    end
  end
end

.resolved_configObject



42
43
44
45
# File 'lib/wallets/models/wallet.rb', line 42

def self.resolved_config
  value = config_provider
  value.respond_to?(:call) ? value.call : value
end

.table_nameObject

Table Name Resolution



38
39
40
# File 'lib/wallets/models/wallet.rb', line 38

def self.table_name
  embedded_table_name || "#{resolved_config.table_prefix}wallets"
end

.transaction_classObject



47
48
49
# File 'lib/wallets/models/wallet.rb', line 47

def self.transaction_class
  transaction_class_name.constantize
end

.transfer_classObject



55
56
57
# File 'lib/wallets/models/wallet.rb', line 55

def self.transfer_class
  transfer_class_name.constantize
end

Instance Method Details

#balanceObject

Balance & History



175
176
177
# File 'lib/wallets/models/wallet.rb', line 175

def balance
  current_balance
end

#credit(amount, metadata: {}, category: :credit, expires_at: nil, transfer: nil, **extra_transaction_attributes) ⇒ Object

Credit & Debit Operations



198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/wallets/models/wallet.rb', line 198

def credit(amount, metadata: {}, category: :credit, expires_at: nil, transfer: nil, **extra_transaction_attributes)
   = ()

  with_lock do
    apply_credit(
      amount,
      metadata: ,
      category: category,
      expires_at: expires_at,
      transfer: transfer,
      extra_attributes: extra_transaction_attributes
    )
  end
end

#current_balanceObject



179
180
181
# File 'lib/wallets/models/wallet.rb', line 179

def current_balance
  positive_remaining_balance - unbacked_negative_balance
end

#debit(amount, metadata: {}, category: :debit, transfer: nil, **extra_transaction_attributes) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/wallets/models/wallet.rb', line 213

def debit(amount, metadata: {}, category: :debit, transfer: nil, **extra_transaction_attributes)
   = ()

  with_lock do
    apply_debit(
      amount,
      metadata: ,
      category: category,
      transfer: transfer,
      extra_attributes: extra_transaction_attributes
    )
  end
end

#has_enough_balance?(amount) ⇒ Boolean

Returns:

  • (Boolean)


187
188
189
190
191
192
# File 'lib/wallets/models/wallet.rb', line 187

def has_enough_balance?(amount)
  normalized_amount = normalize_positive_amount!(amount)
  balance >= normalized_amount
rescue ArgumentError
  false
end

#historyObject



183
184
185
# File 'lib/wallets/models/wallet.rb', line 183

def history
  transactions.order(created_at: :asc)
end

#metadataObject

Metadata Handling



157
158
159
# File 'lib/wallets/models/wallet.rb', line 157

def 
  @indifferent_metadata ||= ActiveSupport::HashWithIndifferentAccess.new(super || {})
end

#metadata=(hash) ⇒ Object



161
162
163
164
# File 'lib/wallets/models/wallet.rb', line 161

def metadata=(hash)
  @indifferent_metadata = nil
  super(hash.respond_to?(:to_h) ? hash.to_h : {})
end

#reloadObject



166
167
168
169
# File 'lib/wallets/models/wallet.rb', line 166

def reload(*)
  @indifferent_metadata = nil
  super
end

#transfer_to(other_wallet, amount, category: :transfer, metadata: {}, expiration_policy: nil, expires_at: nil) ⇒ Object

Transfers

Raises:



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/wallets/models/wallet.rb', line 231

def transfer_to(other_wallet, amount, category: :transfer, metadata: {}, expiration_policy: nil, expires_at: nil)
  raise InvalidTransfer, "Target wallet is required" if other_wallet.nil?
  raise InvalidTransfer, "Target wallet must be persisted" unless other_wallet.persisted?
  raise InvalidTransfer, "Cannot transfer to the same wallet" if other_wallet.id == id
  raise InvalidTransfer, "Wallet assets must match" unless asset_code == other_wallet.asset_code
  raise InvalidTransfer, "Wallet classes must match" unless other_wallet.class == self.class

  amount = normalize_positive_amount!(amount)
   = ()
  resolved_policy, inbound_expires_at = resolve_transfer_expiration!(expiration_policy, expires_at)

  ActiveRecord::Base.transaction do
    lock_wallet_pair!(other_wallet)

    previous_balance = balance

    # Insufficient-balance gate.
    #
    # `allow_negative_balance` is the single source of truth for whether
    # the gem permits a wallet to drop below zero. Direct `wallet.debit`
    # has always honored it via `apply_debit`; transfers must too, or
    # the flag is half-applied and surprising (debits go through, the
    # canonical transfer primitive doesn't).
    #
    # When the flag is OFF, this is the only chance to refuse cleanly:
    # we want to dispatch `:insufficient_balance` for the observability
    # callback, then raise BEFORE creating the Transfer row. (The later
    # `apply_debit` call would also catch this, but only after a
    # pointless Transfer row was created.)
    #
    # When the flag is ON, we let the transfer through. `apply_debit`
    # below will allocate as many positive buckets as exist; the
    # remaining shortfall lands as an unbacked negative transaction the
    # wallet's `balance` accounting accommodates via
    # `unbacked_negative_balance`.
    if amount > previous_balance && !allow_negative_balance?
      dispatch_insufficient_balance!(amount, previous_balance, )
      raise InsufficientBalance, "Insufficient balance (#{previous_balance} < #{amount})"
    end

    # When a transfer dips below zero we can't faithfully apply the
    # `:preserve` expiration policy: there are no positive source
    # buckets to inherit expirations from for the deficit portion.
    # `build_preserved_transfer_inbound_credit_specs` would refuse with
    # `InvalidTransfer` on the count mismatch, defeating the very
    # callers who opted into negative balances. The only honest
    # fallback is to collapse the inbound side to a single evergreen
    # credit (`:none`) — value created without a source bucket has no
    # source expiration to preserve.
    #
    # Callers who care about a specific expiration on the inbound side
    # should pass `expiration_policy: :fixed, expires_at: …`. Those are
    # honored unchanged because they don't depend on source-bucket
    # walking. Same for an explicit `:none`.
    if resolved_policy == "preserve" && amount > previous_balance
      resolved_policy = "none"
      inbound_expires_at = nil
    end

    transfer = transfer_class.create!(
      from_wallet: self,
      to_wallet: other_wallet,
      asset_code: asset_code,
      amount: amount,
      category: category,
      expiration_policy: resolved_policy,
      metadata: 
    )

     = .to_h.deep_stringify_keys.merge(
      "transfer_id" => transfer.id,
      "asset_code" => asset_code,
      "transfer_category" => category.to_s,
      "transfer_expiration_policy" => resolved_policy
    )

    outbound_transaction = apply_debit(
      amount,
      category: :transfer_out,
      metadata: .merge(
        "counterparty_wallet_id" => other_wallet.id,
        "counterparty_owner_id" => other_wallet.owner_id,
        "counterparty_owner_type" => other_wallet.owner_type
      ),
      transfer: transfer
    )

    build_transfer_inbound_credit_specs(
      transfer: transfer,
      outbound_transaction: outbound_transaction,
      amount: amount,
      expiration_policy: resolved_policy,
      expires_at: inbound_expires_at
    ).each do |spec|
      other_wallet.send(
        :apply_credit,
        spec[:amount],
        category: :transfer_in,
        metadata: .merge(
          "counterparty_wallet_id" => id,
          "counterparty_owner_id" => owner_id,
          "counterparty_owner_type" => owner_type
        ),
        expires_at: spec[:expires_at],
        transfer: transfer
      )
    end

    dispatch_callback(:transfer_completed,
      wallet: self,
      transfer: transfer,
      amount: amount,
      category: category,
      metadata: 
    )

    transfer
  end
end