tronzap-sdk 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +70 -0
  3. data/README.es.md +145 -15
  4. data/README.md +143 -14
  5. data/README.pt-br.md +145 -14
  6. data/README.ru.md +141 -13
  7. data/lib/tronzap/client.rb +157 -6
  8. data/lib/tronzap/coerce.rb +8 -0
  9. data/lib/tronzap/errors.rb +74 -17
  10. data/lib/tronzap/models/bulk_rejected_row.rb +30 -0
  11. data/lib/tronzap/models/direct_recharge_rate.rb +1 -1
  12. data/lib/tronzap/models/energy_rate.rb +12 -8
  13. data/lib/tronzap/models/enums.rb +15 -1
  14. data/lib/tronzap/models/subscription_params.rb +28 -0
  15. data/lib/tronzap/requests/aml_check.rb +17 -6
  16. data/lib/tronzap/requests/bulk_calculate.rb +40 -0
  17. data/lib/tronzap/requests/bulk_create.rb +52 -0
  18. data/lib/tronzap/requests/bulk_history.rb +28 -0
  19. data/lib/tronzap/requests/bulk_item.rb +29 -0
  20. data/lib/tronzap/requests/bulk_lookup.rb +48 -0
  21. data/lib/tronzap/requests/bulk_report.rb +55 -0
  22. data/lib/tronzap/requests/start_subscription.rb +54 -0
  23. data/lib/tronzap/requests/subscription_history.rb +35 -0
  24. data/lib/tronzap/requests/subscription_lookup.rb +48 -0
  25. data/lib/tronzap/requests/validation.rb +8 -0
  26. data/lib/tronzap/response_decoder.rb +53 -15
  27. data/lib/tronzap/responses/aml_check.rb +1 -1
  28. data/lib/tronzap/responses/bulk_calculation.rb +44 -0
  29. data/lib/tronzap/responses/bulk_history.rb +28 -0
  30. data/lib/tronzap/responses/bulk_order.rb +87 -0
  31. data/lib/tronzap/responses/calculation.rb +5 -3
  32. data/lib/tronzap/responses/energy_estimate.rb +6 -4
  33. data/lib/tronzap/responses/service_rates.rb +3 -2
  34. data/lib/tronzap/responses/subscription.rb +73 -0
  35. data/lib/tronzap/responses/subscription_history.rb +28 -0
  36. data/lib/tronzap/responses/subscription_plan.rb +52 -0
  37. data/lib/tronzap/version.rb +1 -1
  38. data/lib/tronzap.rb +17 -0
  39. metadata +18 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 47eb7ea9f4ddd00ae8d660cc3b80423ec34badd0b79282e0a0ee3467018192d4
4
- data.tar.gz: 8d8eaaedce42acb5aba146c6cd610af884c3d535002e296593bf4102a30d5777
3
+ metadata.gz: 95551b6b4d331797048d81550bc7118548f59c64bbb3d46deda99fdcb7568790
4
+ data.tar.gz: 57d6bf136386ad894af3faa8b7a048f520e4c3c82e39c8622ce971a8f4ed7b28
5
5
  SHA512:
6
- metadata.gz: a70751df5acfd943527b15de891f78fd69bd25a245df44086e2c805001c6a31805a854f93c6079f0df0c945ba9f66f82f79750570e9f8385d09c56d5857b8b72
7
- data.tar.gz: 3b279e1a68f525fdb795d9c54ec6da604b3d635884e03a869cd983ccadf26df4433b65300d2bce5d94e2e74389b16466470a972f4b46cba55cd7ab85155bc21a
6
+ metadata.gz: 7aa368493a594653c4a39dca2bba537ef8f2c58608fb375b93b099d7ac639934f3bd6a6a96f1caaab22d28934504dea1d2661a7b0adc3d868e4a81d0348d1eb4
7
+ data.tar.gz: 3382112bcaad87611ef1dd468db4d5c35b6eb06249982e8ccec1a101b44f767c042937fe45387e2725277db8589a6262f489b63fa98a6309d2a45eb371bf2432
data/CHANGELOG.md CHANGED
@@ -4,6 +4,73 @@ All notable changes to this project are documented in this file. The format is b
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ## [1.2.0] - 2026-11-20
10
+
11
+ ### Added
12
+
13
+ - Bulk energy orders for up to 10 000 addresses: `Client#bulk_calculate`, `#bulk_create`, `#bulk_check`,
14
+ `#get_bulk_history` and `#bulk_report`, with the requests `Requests::BulkItem`, `Requests::BulkCalculate`,
15
+ `Requests::BulkCreate`, `Requests::BulkLookup`, `Requests::BulkReport` and `Requests::BulkHistory`, the results
16
+ `Responses::BulkCalculation`, `Responses::BulkOrder` and `Responses::BulkHistory`, `Models::BulkRejectedRow`,
17
+ `Models::BULK_STATUSES` and `Models::BULK_ROW_STATUSES`. `bulk_report` returns the CSV report as a UTF-8 string.
18
+ - `Client#verify_webhook_signature` checks the `X-Signature` header of the webhook a bulk order sends when it becomes
19
+ final.
20
+ - `ApiError#result`: the `result` the API sends along with an error, as parsed JSON. Until now the SDK dropped it.
21
+ - `BulkPriceChangedError` (code 92) with the new calculation in `#calculation`, and `BulkNoValidItemsError` (code 94)
22
+ with the rejected rows in `#rejected`. Both are `ApiError`s.
23
+ - `ApiError#retry_after` and `HttpError#retry_after`: seconds to wait before retrying, from the `Retry-After` header
24
+ (seconds or an HTTP date) or the `retry_after` field, or `nil` when the server sent neither.
25
+ - The error codes `BULK_NOT_FOUND` (90), `BULK_EXPIRED` (91), `BULK_PRICE_CHANGED` (92), `BULK_TOO_MANY_ITEMS` (93),
26
+ `BULK_NO_VALID_ITEMS` (94), `BULK_RESOURCE_NOT_SUPPORTED` (95), `PAYLOAD_TOO_LARGE` (96) and `RATE_LIMITED` (429).
27
+ - The example program lists bulk orders, calculates one with an invalid row, checks and reports `TRONZAP_BULK_ID`,
28
+ and with purchases allowed starts a one-address bulk order.
29
+
30
+ ### Changed
31
+
32
+ - `retry_after` moved from `RateLimitError` to its base class `HttpError`, so a 503 from `ServerError` carries it
33
+ too. Code that reads it is unchanged, and the body's `retry_after` field is read when the header is missing.
34
+ - The documentation of `RateLimitError`: it is only an HTTP 429 without an API payload, such as one from a proxy. A
35
+ rate limit reported by the API is an `ApiError` with `RATE_LIMITED`, as it always has been.
36
+
37
+ ## [1.1.0] - 2026-10-09
38
+
39
+ ### Added
40
+
41
+ - Energy subscriptions: `Client#get_subscriptions`, `#start_subscription`, `#check_subscription`,
42
+ `#stop_subscription` and `#get_subscription_history`, with the requests `Requests::StartSubscription`,
43
+ `Requests::SubscriptionLookup` and `Requests::SubscriptionHistory`, the results `Responses::SubscriptionPlan`,
44
+ `Responses::Subscription` and `Responses::SubscriptionHistory`, `Models::SubscriptionParams` and
45
+ `Models::SUBSCRIPTION_STATUSES`. `get_subscriptions` returns the plans in the API's order, each with its key as
46
+ `subscription_id`.
47
+ - The example program lists subscription plans and history, checks `TRONZAP_SUBSCRIPTION_ID`, and with purchases
48
+ allowed and `TRONZAP_SUBSCRIPTION_PLAN` set starts a one-day subscription and always stops it.
49
+
50
+ ### Changed
51
+
52
+ - A hash AML check without a `direction` now sends `deposit` explicitly instead of leaving the direction to the API.
53
+ An address check still sends a direction only when one is given.
54
+ - The documentation of AML checks: for a hash check, `address` is the recipient address of the transaction, and
55
+ `direction` says which side you are on (`:deposit` if the funds were sent to your address, `:withdrawal` if you
56
+ sent them); the risk is scored for the counterparty.
57
+ - The documentation of error codes 10 and 21: `INVALID_TRON_ADDRESS` is also reported when the address already has
58
+ an active subscription, and `CANNOT_STOP_SUBSCRIPTION` covers, for example, a subscription with a transactions
59
+ limit.
60
+
61
+ ### Deprecated
62
+
63
+ - `Models::EnergyRate#min_energy` and `#max_energy`: use `#min_amount` and `#max_amount`. They now hold the same
64
+ values, read from the API's `min_amount` and `max_amount`.
65
+ - `Responses::Calculation#energy`: use `#amount`. It now holds the same value, read from the API's `amount`.
66
+ - `Responses::EnergyEstimate#energy`: use `#amount`. It now holds the same value, read from the API's `amount`.
67
+
68
+ ### Fixed
69
+
70
+ - The documentation of `get_services` prices: energy, like bandwidth, is priced per 1000 units, so a purchase costs
71
+ `price × amount / 1000`. It was described as priced per unit.
72
+ - `Models::DirectRechargeRate#price` is the price of 1000 units of energy as well, not of one unit.
73
+
7
74
  ## [1.0.0] - 2026-10-06
8
75
 
9
76
  First release of the official Ruby SDK for the [TronZap API](https://docs.tronzap.com/).
@@ -20,4 +87,7 @@ First release of the official Ruby SDK for the [TronZap API](https://docs.tronza
20
87
  - An error hierarchy under `Tronzap::Error` that separates API, HTTP, response and network failures, with the HTTP
21
88
  status, API error code, error key, request ID and raw response body.
22
89
 
90
+ [Unreleased]: https://github.com/tron-energy-market/tronzap-sdk-ruby/compare/v1.2.0...HEAD
91
+ [1.2.0]: https://github.com/tron-energy-market/tronzap-sdk-ruby/releases/tag/v1.2.0
92
+ [1.1.0]: https://github.com/tron-energy-market/tronzap-sdk-ruby/releases/tag/v1.1.0
23
93
  [1.0.0]: https://github.com/tron-energy-market/tronzap-sdk-ruby/releases/tag/v1.0.0
data/README.es.md CHANGED
@@ -57,7 +57,7 @@ begin
57
57
 
58
58
  transaction = client.create_energy_transaction(
59
59
  address: "TRecipientAddress",
60
- energy: estimate.energy,
60
+ energy: estimate.amount,
61
61
  duration: 1,
62
62
  external_id: "order-42",
63
63
  activate_address: true
@@ -185,6 +185,17 @@ bibliotecas HTTP debe traducirlos el adaptador, como en el ejemplo anterior.
185
185
  | `create_aml_check(type:, network:, address:, transaction_hash: nil, direction: nil)` | `/v1/aml-checks/new` | Iniciar una verificación AML |
186
186
  | `check_aml_status(id)` | `/v1/aml-checks/check` | Estado y resultado de una verificación AML |
187
187
  | `get_aml_history(page: 1, per_page: 10, status: nil)` | `/v1/aml-checks/history` | Historial paginado de verificaciones AML |
188
+ | `get_subscriptions` | `/v1/subscriptions` | Planes de suscripción y precios |
189
+ | `start_subscription(subscription_id:, address:, duration_days: 0, transactions_limit: 0, external_id: nil, activate_address: false)` | `/v1/subscription/start` | Suscribir una dirección a un plan |
190
+ | `check_subscription(id: nil, external_id: nil)` | `/v1/subscription/check` | Estado de una suscripción, por id o id externo |
191
+ | `stop_subscription(id: nil, external_id: nil)` | `/v1/subscription/stop` | Detener una suscripción |
192
+ | `get_subscription_history(page: 1, per_page: 10, status: nil)` | `/v1/subscriptions/history` | Historial paginado de suscripciones |
193
+ | `bulk_calculate(items:, duration: 1)` | `/v1/bulk/calculate` | Validar y calcular las filas de un pedido masivo de energía |
194
+ | `bulk_create(id:, external_id: nil, force: false, max_price_increase: nil, webhook_url: nil)` | `/v1/bulk/create` | Iniciar un pedido masivo a partir de un cálculo |
195
+ | `bulk_check(id: nil, external_id: nil)` | `/v1/bulk/check` | Estado y progreso de un pedido masivo |
196
+ | `get_bulk_history(page: 1, per_page: 10)` | `/v1/bulk/history` | Historial paginado de pedidos masivos |
197
+ | `bulk_report(id: nil, external_id: nil, status: nil)` | `/v1/bulk/report` | Informe por dirección de un pedido masivo, en CSV |
198
+ | `verify_webhook_signature(body, signature)` | — | Comprobar el `X-Signature` del webhook de un pedido masivo |
188
199
 
189
200
  Los métodos con parámetros aceptan argumentos de palabra clave o un objeto de
190
201
  solicitud de `Tronzap::Requests`, así que una solicitud se puede construir, validar
@@ -197,11 +208,13 @@ client.create_energy_transaction(request)
197
208
 
198
209
  Una solicitud se valida al crearse, así que una solicitud inválida lanza
199
210
  `ArgumentError` y nunca llega a la API. Las cantidades deben ser `Integer`
200
- positivos. Los valores por defecto coinciden con la API: `duration` es 1 hora y el
201
- historial AML empieza en la página 1 con 10 elementos.
211
+ positivos. Los valores por defecto coinciden con la API: `duration` es 1 hora y los
212
+ historiales AML y de suscripciones empiezan en la página 1 con 10 elementos. La
213
+ excepción es `start_subscription`, donde `duration_days` y `transactions_limit`
214
+ valen 0 por defecto, lo que significa sin límite.
202
215
 
203
216
  Los resultados son objetos `Data` inmutables en `Tronzap::Responses` y
204
- `Tronzap::Models`, no hashes: `transaction.status`, `estimate.energy`. Las
217
+ `Tronzap::Models`, no hashes: `transaction.status`, `estimate.amount`. Las
205
218
  colecciones están congeladas y nunca son `nil`, y los valores que la API puede
206
219
  omitir son `nil`.
207
220
 
@@ -232,10 +245,10 @@ client.create_resource_bundle_transaction(
232
245
  client.create_address_activation_transaction(address: "TRecipientAddress", external_id: "activation-1")
233
246
  ```
234
247
 
235
- El precio de la energía es por unidad y el del ancho de banda por 1000 unidades:
236
- en `get_services`, `EnergyRate#price` × 65000 es el coste de 65000 de energía,
237
- mientras que 345 de ancho de banda con un `BandwidthRate#price` de 1 cuestan
238
- 0.345.
248
+ En `get_services`, los precios de la energía y del ancho de banda son ambos por
249
+ 1000 unidades, así que una compra cuesta `price × amount / 1000`: 65000 de energía
250
+ con un `EnergyRate#price` de 0.03 cuestan 1.95, y 345 de ancho de banda con un
251
+ `BandwidthRate#price` de 1 cuestan 0.345.
239
252
 
240
253
  Actualmente la API informa un paquete de recursos con `service` igual a `:energy`,
241
254
  no `:resource_bundle`. Consulta `params.amounts` para saber qué recursos contiene
@@ -268,10 +281,102 @@ if result.status == :completed
268
281
  end
269
282
  ```
270
283
 
284
+ En una verificación por hash, `address` es la dirección del destinatario de la
285
+ transacción, donde se recibieron los fondos, y `direction` indica en qué lado
286
+ estás: `:deposit` si los fondos llegaron a tu dirección (`address` es tu
287
+ dirección), `:withdrawal` si los enviaste tú (`address` es la dirección del
288
+ destinatario externo). El riesgo se calcula para la contraparte: el remitente en
289
+ un deposit, el destinatario en un withdrawal. Sin `direction`, el SDK envía
290
+ `deposit`.
291
+
271
292
  `risk_score` es `nil` hasta que termina la verificación. Una verificación
272
293
  completada puede tener una puntuación de 0, que no es lo mismo que no tener
273
294
  puntuación todavía.
274
295
 
296
+ ### Suscripciones
297
+
298
+ Una suscripción mantiene una dirección abastecida de energía para cada transacción
299
+ hasta que se detiene o se agotan sus días o transacciones. Elija un plan de
300
+ `get_subscriptions` y pase su `subscription_id`, como `"unlimited_energy"`, no su
301
+ `id` numérico. Iniciar una suscripción cobra el precio inicial del plan.
302
+
303
+ ```ruby
304
+ client.get_subscriptions.each do |plan|
305
+ puts "#{plan.subscription_id} #{plan.initial_price.to_s("F")} #{plan.price.to_s("F")}"
306
+ end
307
+
308
+ subscription = client.start_subscription(
309
+ subscription_id: "unlimited_energy",
310
+ address: "TRecipientAddress",
311
+ duration_days: 30, # 0 para no limitar el tiempo
312
+ transactions_limit: 0, # 0 para no limitar
313
+ external_id: "subscription-42"
314
+ )
315
+
316
+ subscription = client.check_subscription(external_id: "subscription-42")
317
+
318
+ subscription = client.stop_subscription(id: subscription.id)
319
+
320
+ history = client.get_subscription_history(status: :active)
321
+ ```
322
+
323
+ Iniciar, consultar y detener devuelven la suscripción con sus `params`; el
324
+ historial devuelve en su lugar los contadores de uso `transactions_used`,
325
+ `energy_used` y `total_price`, y deja `params` en `nil`. Los estados de una
326
+ suscripción están en `Tronzap::Models::SUBSCRIPTION_STATUSES`. Una suscripción con
327
+ límite de transacciones no se puede detener (`CANNOT_STOP_SUBSCRIPTION`).
328
+
329
+ ### Pedidos masivos
330
+
331
+ Compra energía para hasta 10 000 direcciones en un solo pedido. `bulk_calculate`
332
+ valida y calcula las filas y devuelve un cálculo válido durante 10 minutos; no se
333
+ cobra nada. Las filas inválidas no hacen fallar la solicitud: se devuelven en
334
+ `rejected` con su número de fila. `bulk_create` inicia el pedido; cada dirección se
335
+ cobra al procesarse, y las direcciones no activadas se omiten sin cobro.
336
+
337
+ Si el precio cambió desde el cálculo, `bulk_create` no inicia el pedido y lanza
338
+ `Tronzap::BulkPriceChangedError` (código `BULK_PRICE_CHANGED`). Su `calculation` es
339
+ el nuevo cálculo: confirma el nuevo total e inícialo con su `id`.
340
+
341
+ ```ruby
342
+ calculation = client.bulk_calculate(items: [
343
+ { address: "TRecipientAddress1", amount: 65000 },
344
+ { address: "TRecipientAddress2", amount: 131000 }
345
+ ])
346
+ calculation.rejected.each { |row| puts "row #{row.row}: #{row.reason}" }
347
+
348
+ begin
349
+ order = client.bulk_create(id: calculation.id, external_id: "order-42",
350
+ webhook_url: "https://example.com/tronzap/bulk")
351
+ rescue Tronzap::BulkPriceChangedError => e
352
+ new_calculation = e.calculation # confirma el nuevo total e inícialo
353
+ order = client.bulk_create(id: new_calculation.id, external_id: "order-42")
354
+ end
355
+
356
+ order = client.bulk_check(external_id: "order-42") # consulta hasta :completed, :partial o :failed
357
+ csv = client.bulk_report(id: order.id) # row,address,amount,status,reason,charged,transaction_id
358
+ history = client.get_bulk_history(page: 1, per_page: 10)
359
+ ```
360
+
361
+ Las filas son `Tronzap::Requests::BulkItem` o hashes con `address` y `amount`. Un
362
+ pedido pasa por los estados de `Tronzap::Models::BULK_STATUSES`; `:completed`,
363
+ `:partial` y `:failed` son finales. `status:` de `bulk_report` acepta uno de
364
+ `Tronzap::Models::BULK_ROW_STATUSES`.
365
+
366
+ Con `webhook_url`, la API envía un `POST` cuando el pedido llega a un estado final.
367
+ Comprueba su cabecera `X-Signature` con el cuerpo sin procesar antes de confiar en
368
+ él, por ejemplo en Sinatra:
369
+
370
+ ```ruby
371
+ post "/tronzap/bulk" do
372
+ body = request.body.read
373
+ halt 401 unless client.verify_webhook_signature(body, request.env["HTTP_X_SIGNATURE"])
374
+
375
+ order = JSON.parse(body) # {"id":"01kb2m5x9qj4v8n3c7d6e5f4g3","external_id":"order-42","status":"partial"}
376
+ 200
377
+ end
378
+ ```
379
+
275
380
  ## Gestión de errores
276
381
 
277
382
  Todo fallo de una llamada a la API es un `Tronzap::Error`. Captura una subclase
@@ -281,7 +386,7 @@ para tratar un tipo concreto de fallo:
281
386
  Tronzap::Error
282
387
  ├── Tronzap::ApiError — la API respondió con un código distinto de cero
283
388
  ├── Tronzap::HttpError — respuesta no 2xx sin payload de la API
284
- │ ├── Tronzap::RateLimitError — HTTP 429
389
+ │ ├── Tronzap::RateLimitError — HTTP 429 sin respuesta de la API
285
390
  │ ├── Tronzap::UnauthorizedError — HTTP 401 o 403
286
391
  │ └── Tronzap::ServerError — HTTP 5xx
287
392
  ├── Tronzap::InvalidResponseError — respuesta 2xx que el SDK no pudo leer
@@ -294,8 +399,7 @@ Tronzap::Error
294
399
  `ApiError`, `HttpError` e `InvalidResponseError` incluyen el estado HTTP
295
400
  (`status`) y el cuerpo de la respuesta sin procesar (`response_body`). `ApiError`
296
401
  incluye además el código de error de la API (`code`), la clave del error
297
- (`error_key`) y el ID de la solicitud (`request_id`). `RateLimitError#retry_after`
298
- contiene el retraso de `Retry-After` en segundos cuando la API lo envía.
402
+ (`error_key`) y el ID de la solicitud (`request_id`).
299
403
 
300
404
  Los argumentos inválidos no son fallos de la API: lanzan `ArgumentError` antes de
301
405
  enviar nada.
@@ -316,8 +420,8 @@ rescue Tronzap::ApiError => e
316
420
  else
317
421
  warn "api error #{e.code}: #{e.message} (request #{e.request_id || "-"})"
318
422
  end
319
- rescue Tronzap::RateLimitError => e
320
- # Espera y reintenta, tras e.retry_after segundos si la API lo envió.
423
+ rescue Tronzap::RateLimitError
424
+ # HTTP 429 sin respuesta de la API, p. ej. de un proxy: espera y reintenta.
321
425
  rescue Tronzap::UnauthorizedError
322
426
  # Token o firma incorrectos.
323
427
  rescue Tronzap::TimeoutError, Tronzap::ServerError
@@ -335,6 +439,24 @@ algunos fallos con estado 2xx y de otros con 4xx o 5xx, así que un payload legi
335
439
  con un código distinto de cero siempre se informa como `Tronzap::ApiError`, nunca
336
440
  como `Tronzap::HttpError`.
337
441
 
442
+ `ApiError#result` es el `result` que la API envió con el error, como JSON
443
+ analizado, o `nil`. El SDK lee los datos de `BULK_PRICE_CHANGED` y
444
+ `BULK_NO_VALID_ITEMS` en `Tronzap::BulkPriceChangedError#calculation` y
445
+ `Tronzap::BulkNoValidItemsError#rejected`; ambos son `ApiError`. Un límite de
446
+ solicitudes informado por la API es un `ApiError` con `RATE_LIMITED`;
447
+ `Tronzap::RateLimitError` es solo un HTTP 429 sin respuesta de la API, p. ej. de un
448
+ proxy. `ApiError` y `HttpError` incluyen `retry_after`, los segundos que esperar
449
+ según la cabecera `Retry-After` o el campo `retry_after`, o `nil` si el servidor no
450
+ indicó cuánto esperar:
451
+
452
+ ```ruby
453
+ rescue Tronzap::ApiError => e
454
+ raise unless e.code == Tronzap::ErrorCode::RATE_LIMITED
455
+
456
+ sleep(e.retry_after || 60)
457
+ end
458
+ ```
459
+
338
460
  ### Códigos de error de la API
339
461
 
340
462
  | Código | Constante | Descripción |
@@ -343,16 +465,24 @@ como `Tronzap::HttpError`.
343
465
  | 2 | `INVALID_SERVICE_OR_PARAMS` | Servicio o parámetros inválidos |
344
466
  | 5 | `WALLET_NOT_FOUND` | Billetera interna no encontrada. Contacta con soporte. |
345
467
  | 6 | `INSUFFICIENT_FUNDS` | Fondos insuficientes |
346
- | 10 | `INVALID_TRON_ADDRESS` | Dirección TRON inválida |
468
+ | 10 | `INVALID_TRON_ADDRESS` | Dirección TRON inválida, o la dirección ya tiene una suscripción activa |
347
469
  | 11 | `INVALID_ENERGY_AMOUNT` | Cantidad de energía inválida |
348
470
  | 12 | `INVALID_DURATION` | Duración inválida |
349
471
  | 20 | `TRANSACTION_NOT_FOUND` | Transacción/suscripción no encontrada |
350
- | 21 | `CANNOT_STOP_SUBSCRIPTION` | No se puede detener la suscripción |
472
+ | 21 | `CANNOT_STOP_SUBSCRIPTION` | No se puede detener la suscripción, p. ej. tiene límite de transacciones |
351
473
  | 24 | `ADDRESS_NOT_ACTIVATED` | Dirección no activada |
352
474
  | 25 | `ADDRESS_ALREADY_ACTIVATED` | Dirección ya activada |
353
475
  | 30 | `AML_CHECK_NOT_FOUND` | Verificación AML no encontrada |
354
476
  | 35 | `SERVICE_NOT_AVAILABLE` | Servicio no disponible |
355
477
  | 50 | `INVALID_BANDWIDTH_AMOUNT` | Cantidad de ancho de banda inválida |
478
+ | 90 | `BULK_NOT_FOUND` | Pedido masivo no encontrado |
479
+ | 91 | `BULK_EXPIRED` | El cálculo expiró, calcula de nuevo |
480
+ | 92 | `BULK_PRICE_CHANGED` | El precio cambió; el nuevo cálculo está en `BulkPriceChangedError#calculation` |
481
+ | 93 | `BULK_TOO_MANY_ITEMS` | Más de 10 000 filas |
482
+ | 94 | `BULK_NO_VALID_ITEMS` | No hay filas válidas; están en `BulkNoValidItemsError#rejected` |
483
+ | 95 | `BULK_RESOURCE_NOT_SUPPORTED` | Solo se puede pedir energía en masa |
484
+ | 96 | `PAYLOAD_TOO_LARGE` | Cuerpo de la solicitud demasiado grande (HTTP 413) |
485
+ | 429 | `RATE_LIMITED` | Demasiadas solicitudes; espera `retry_after` si se indica |
356
486
  | 500 | `INTERNAL_SERVER_ERROR` | Error interno del servidor: contacta con soporte |
357
487
 
358
488
  Las constantes están en `Tronzap::ErrorCode`. Un código que esta versión del SDK
data/README.md CHANGED
@@ -57,7 +57,7 @@ begin
57
57
 
58
58
  transaction = client.create_energy_transaction(
59
59
  address: "TRecipientAddress",
60
- energy: estimate.energy,
60
+ energy: estimate.amount,
61
61
  duration: 1,
62
62
  external_id: "order-42",
63
63
  activate_address: true
@@ -185,6 +185,17 @@ libraries need to be translated by the adapter, as above.
185
185
  | `create_aml_check(type:, network:, address:, transaction_hash: nil, direction: nil)` | `/v1/aml-checks/new` | Start an AML screening |
186
186
  | `check_aml_status(id)` | `/v1/aml-checks/check` | Status and result of an AML check |
187
187
  | `get_aml_history(page: 1, per_page: 10, status: nil)` | `/v1/aml-checks/history` | Paginated AML check history |
188
+ | `get_subscriptions` | `/v1/subscriptions` | Subscription plans and prices |
189
+ | `start_subscription(subscription_id:, address:, duration_days: 0, transactions_limit: 0, external_id: nil, activate_address: false)` | `/v1/subscription/start` | Subscribe an address to a plan |
190
+ | `check_subscription(id: nil, external_id: nil)` | `/v1/subscription/check` | Status of a subscription, by id or external id |
191
+ | `stop_subscription(id: nil, external_id: nil)` | `/v1/subscription/stop` | Stop a subscription |
192
+ | `get_subscription_history(page: 1, per_page: 10, status: nil)` | `/v1/subscriptions/history` | Paginated subscription history |
193
+ | `bulk_calculate(items:, duration: 1)` | `/v1/bulk/calculate` | Validate and price the rows of a bulk energy order |
194
+ | `bulk_create(id:, external_id: nil, force: false, max_price_increase: nil, webhook_url: nil)` | `/v1/bulk/create` | Start a bulk order from a calculation |
195
+ | `bulk_check(id: nil, external_id: nil)` | `/v1/bulk/check` | Status and progress of a bulk order |
196
+ | `get_bulk_history(page: 1, per_page: 10)` | `/v1/bulk/history` | Paginated bulk order history |
197
+ | `bulk_report(id: nil, external_id: nil, status: nil)` | `/v1/bulk/report` | Per-address report of a bulk order, as CSV |
198
+ | `verify_webhook_signature(body, signature)` | — | Check the `X-Signature` of a bulk order webhook |
188
199
 
189
200
  Methods with parameters take either keyword arguments or a request object from
190
201
  `Tronzap::Requests`, so a request can be built, validated and passed around before
@@ -197,11 +208,12 @@ client.create_energy_transaction(request)
197
208
 
198
209
  A request is validated when it is created, so an invalid one raises
199
210
  `ArgumentError` and never reaches the API. Amounts must be positive `Integer`s.
200
- Defaults match the API: `duration` is 1 hour, and AML history starts at page 1
201
- with 10 items.
211
+ Defaults match the API: `duration` is 1 hour, and AML and subscription history
212
+ start at page 1 with 10 items. The exception is `start_subscription`, where
213
+ `duration_days` and `transactions_limit` default to 0, which means no limit.
202
214
 
203
215
  Results are immutable `Data` objects in `Tronzap::Responses` and
204
- `Tronzap::Models`, not hashes: `transaction.status`, `estimate.energy`. Collections
216
+ `Tronzap::Models`, not hashes: `transaction.status`, `estimate.amount`. Collections
205
217
  are frozen and never `nil`, and values the API may omit are `nil`.
206
218
 
207
219
  ### Buying resources
@@ -231,9 +243,9 @@ client.create_resource_bundle_transaction(
231
243
  client.create_address_activation_transaction(address: "TRecipientAddress", external_id: "activation-1")
232
244
  ```
233
245
 
234
- Energy prices are per unit, bandwidth prices are per 1000 units: in
235
- `get_services`, `EnergyRate#price` × 65000 is the cost of 65000 energy, while 345
236
- bandwidth at a `BandwidthRate#price` of 1 costs 0.345.
246
+ Energy and bandwidth prices in `get_services` are both per 1000 units, so a
247
+ purchase costs `price × amount / 1000`: 65000 energy at an `EnergyRate#price` of
248
+ 0.03 costs 1.95, and 345 bandwidth at a `BandwidthRate#price` of 1 costs 0.345.
237
249
 
238
250
  The API currently reports a resource bundle with `service` equal to `:energy`, not
239
251
  `:resource_bundle`. Read `params.amounts` to see which resources a transaction
@@ -266,9 +278,101 @@ if result.status == :completed
266
278
  end
267
279
  ```
268
280
 
281
+ For a hash check, `address` is the recipient address of the transaction, where
282
+ the funds were received, and `direction` says which side you are on: `:deposit`
283
+ if the funds were sent to your address (`address` is your address), `:withdrawal`
284
+ if you sent them (`address` is the external recipient's address). The risk is
285
+ scored for the counterparty: the sender of a deposit, the recipient of a
286
+ withdrawal. Without a `direction`, the SDK sends `deposit`.
287
+
269
288
  `risk_score` is `nil` until screening finishes. A completed check can have a score
270
289
  of 0, which is not the same as having no score yet.
271
290
 
291
+ ### Subscriptions
292
+
293
+ A subscription keeps an address supplied with energy for every transaction until
294
+ it is stopped or runs out of days or transactions. Pick a plan from
295
+ `get_subscriptions` and pass its `subscription_id`, such as `"unlimited_energy"`,
296
+ not its numeric `id`. Starting a subscription charges the plan's initial price.
297
+
298
+ ```ruby
299
+ client.get_subscriptions.each do |plan|
300
+ puts "#{plan.subscription_id} #{plan.initial_price.to_s("F")} #{plan.price.to_s("F")}"
301
+ end
302
+
303
+ subscription = client.start_subscription(
304
+ subscription_id: "unlimited_energy",
305
+ address: "TRecipientAddress",
306
+ duration_days: 30, # 0 for no time limit
307
+ transactions_limit: 0, # 0 for no limit
308
+ external_id: "subscription-42"
309
+ )
310
+
311
+ subscription = client.check_subscription(external_id: "subscription-42")
312
+
313
+ subscription = client.stop_subscription(id: subscription.id)
314
+
315
+ history = client.get_subscription_history(status: :active)
316
+ ```
317
+
318
+ Start, check and stop return the subscription with its `params`; the history
319
+ returns the usage counters `transactions_used`, `energy_used` and `total_price`
320
+ instead, and leaves `params` `nil`. A subscription moves through the statuses in
321
+ `Tronzap::Models::SUBSCRIPTION_STATUSES`. A subscription with a transactions limit
322
+ cannot be stopped (`CANNOT_STOP_SUBSCRIPTION`).
323
+
324
+ ### Bulk orders
325
+
326
+ Buy energy for up to 10 000 addresses in one order. `bulk_calculate` validates and
327
+ prices the rows and returns a calculation valid for 10 minutes; nothing is
328
+ charged. Invalid rows do not fail the request: they come back in `rejected` with
329
+ their row number. `bulk_create` starts the order; each address is charged when it
330
+ is processed, and addresses that are not activated are skipped without a charge.
331
+
332
+ If the price changed since the calculation, `bulk_create` does not start the order
333
+ and raises `Tronzap::BulkPriceChangedError` (code `BULK_PRICE_CHANGED`). Its
334
+ `calculation` is the new calculation: confirm the new total, then start it by its
335
+ `id`.
336
+
337
+ ```ruby
338
+ calculation = client.bulk_calculate(items: [
339
+ { address: "TRecipientAddress1", amount: 65000 },
340
+ { address: "TRecipientAddress2", amount: 131000 }
341
+ ])
342
+ calculation.rejected.each { |row| puts "row #{row.row}: #{row.reason}" }
343
+
344
+ begin
345
+ order = client.bulk_create(id: calculation.id, external_id: "order-42",
346
+ webhook_url: "https://example.com/tronzap/bulk")
347
+ rescue Tronzap::BulkPriceChangedError => e
348
+ new_calculation = e.calculation # confirm the new total, then start it
349
+ order = client.bulk_create(id: new_calculation.id, external_id: "order-42")
350
+ end
351
+
352
+ order = client.bulk_check(external_id: "order-42") # poll until :completed, :partial or :failed
353
+ csv = client.bulk_report(id: order.id) # row,address,amount,status,reason,charged,transaction_id
354
+ history = client.get_bulk_history(page: 1, per_page: 10)
355
+ ```
356
+
357
+ The rows are `Tronzap::Requests::BulkItem`s or hashes with `address` and `amount`.
358
+ An order moves through the statuses in `Tronzap::Models::BULK_STATUSES`;
359
+ `:completed`, `:partial` and `:failed` are final. `status:` of `bulk_report` takes
360
+ one of `Tronzap::Models::BULK_ROW_STATUSES`.
361
+
362
+ With `webhook_url`, the API sends one `POST` to it when the order becomes final.
363
+ Check its `X-Signature` header against the raw body before trusting it, for
364
+ example in Sinatra:
365
+
366
+ ```ruby
367
+ post "/tronzap/bulk" do
368
+ body = request.body.read
369
+ halt 401 unless client.verify_webhook_signature(body, request.env["HTTP_X_SIGNATURE"])
370
+
371
+ order = JSON.parse(body) # {"id":"01kb2m5x9qj4v8n3c7d6e5f4g3","external_id":"order-42","status":"partial"}
372
+ 200
373
+ end
374
+ ```
375
+
272
376
  ## Error handling
273
377
 
274
378
  Every failure of an API call is a `Tronzap::Error`. Rescue a subclass to handle
@@ -278,7 +382,7 @@ one kind of failure:
278
382
  Tronzap::Error
279
383
  ├── Tronzap::ApiError — the API answered with a non-zero code
280
384
  ├── Tronzap::HttpError — non-2xx response without an API payload
281
- │ ├── Tronzap::RateLimitError — HTTP 429
385
+ │ ├── Tronzap::RateLimitError — HTTP 429 without an API payload
282
386
  │ ├── Tronzap::UnauthorizedError — HTTP 401 or 403
283
387
  │ └── Tronzap::ServerError — HTTP 5xx
284
388
  ├── Tronzap::InvalidResponseError — 2xx response the SDK could not read
@@ -291,8 +395,7 @@ Tronzap::Error
291
395
  `ApiError`, `HttpError` and `InvalidResponseError` carry the HTTP status
292
396
  (`status`) and the raw response body (`response_body`). `ApiError` also carries
293
397
  the API error code (`code`), the error key (`error_key`) and the request ID
294
- (`request_id`). `RateLimitError#retry_after` holds the `Retry-After` delay in
295
- seconds when the API sends one.
398
+ (`request_id`).
296
399
 
297
400
  Invalid arguments are not API failures: they raise `ArgumentError` before anything
298
401
  is sent.
@@ -313,8 +416,8 @@ rescue Tronzap::ApiError => e
313
416
  else
314
417
  warn "api error #{e.code}: #{e.message} (request #{e.request_id || "-"})"
315
418
  end
316
- rescue Tronzap::RateLimitError => e
317
- # Back off and retry, after e.retry_after seconds if the API sent it.
419
+ rescue Tronzap::RateLimitError
420
+ # HTTP 429 without an API payload, e.g. from a proxy: back off and retry.
318
421
  rescue Tronzap::UnauthorizedError
319
422
  # Bad token or signature.
320
423
  rescue Tronzap::TimeoutError, Tronzap::ServerError
@@ -332,6 +435,24 @@ with a 2xx status and others with a 4xx or 5xx status, so a readable payload wit
332
435
  a non-zero code is always reported as `Tronzap::ApiError`, never as
333
436
  `Tronzap::HttpError`.
334
437
 
438
+ `ApiError#result` is the `result` the API sent along with the error, as parsed
439
+ JSON, or `nil`. The SDK reads the data of `BULK_PRICE_CHANGED` and
440
+ `BULK_NO_VALID_ITEMS` into `Tronzap::BulkPriceChangedError#calculation` and
441
+ `Tronzap::BulkNoValidItemsError#rejected`; both are `ApiError`s. A rate limit
442
+ reported by the API is an `ApiError` with `RATE_LIMITED`;
443
+ `Tronzap::RateLimitError` is only an HTTP 429 without an API payload, such as one
444
+ from a proxy. `ApiError` and `HttpError` carry `retry_after`, the seconds to wait
445
+ from the `Retry-After` header or the `retry_after` field, `nil` when the server did
446
+ not say how long to wait:
447
+
448
+ ```ruby
449
+ rescue Tronzap::ApiError => e
450
+ raise unless e.code == Tronzap::ErrorCode::RATE_LIMITED
451
+
452
+ sleep(e.retry_after || 60)
453
+ end
454
+ ```
455
+
335
456
  ### API error codes
336
457
 
337
458
  | Code | Constant | Description |
@@ -340,16 +461,24 @@ a non-zero code is always reported as `Tronzap::ApiError`, never as
340
461
  | 2 | `INVALID_SERVICE_OR_PARAMS` | Invalid service or parameters |
341
462
  | 5 | `WALLET_NOT_FOUND` | Internal wallet not found. Contact support. |
342
463
  | 6 | `INSUFFICIENT_FUNDS` | Insufficient funds |
343
- | 10 | `INVALID_TRON_ADDRESS` | Invalid TRON address |
464
+ | 10 | `INVALID_TRON_ADDRESS` | Invalid TRON address, or the address already has an active subscription |
344
465
  | 11 | `INVALID_ENERGY_AMOUNT` | Invalid energy amount |
345
466
  | 12 | `INVALID_DURATION` | Invalid duration |
346
467
  | 20 | `TRANSACTION_NOT_FOUND` | Transaction/subscription not found |
347
- | 21 | `CANNOT_STOP_SUBSCRIPTION` | Cannot stop subscription |
468
+ | 21 | `CANNOT_STOP_SUBSCRIPTION` | Cannot stop subscription, e.g. it has a transactions limit |
348
469
  | 24 | `ADDRESS_NOT_ACTIVATED` | Address not activated |
349
470
  | 25 | `ADDRESS_ALREADY_ACTIVATED` | Address already activated |
350
471
  | 30 | `AML_CHECK_NOT_FOUND` | AML check not found |
351
472
  | 35 | `SERVICE_NOT_AVAILABLE` | Service not available |
352
473
  | 50 | `INVALID_BANDWIDTH_AMOUNT` | Invalid bandwidth amount |
474
+ | 90 | `BULK_NOT_FOUND` | Bulk order not found |
475
+ | 91 | `BULK_EXPIRED` | The calculation expired, calculate again |
476
+ | 92 | `BULK_PRICE_CHANGED` | The price changed; the new calculation is in `BulkPriceChangedError#calculation` |
477
+ | 93 | `BULK_TOO_MANY_ITEMS` | More than 10 000 rows |
478
+ | 94 | `BULK_NO_VALID_ITEMS` | No valid rows; they are in `BulkNoValidItemsError#rejected` |
479
+ | 95 | `BULK_RESOURCE_NOT_SUPPORTED` | Only energy can be ordered in bulk |
480
+ | 96 | `PAYLOAD_TOO_LARGE` | Request body too large (HTTP 413) |
481
+ | 429 | `RATE_LIMITED` | Too many requests; wait `retry_after` if given |
353
482
  | 500 | `INTERNAL_SERVER_ERROR` | Internal server error – contact support |
354
483
 
355
484
  The constants live in `Tronzap::ErrorCode`. A code this SDK version does not know