@v3finance/core-sdk 0.21.0 → 0.22.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 (67) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +1 -1
  3. package/dist/cjs/generated/operations.d.ts +16 -0
  4. package/dist/cjs/generated/operations.d.ts.map +1 -1
  5. package/dist/cjs/generated/operations.js +18 -2
  6. package/dist/cjs/generated/operations.js.map +1 -1
  7. package/dist/cjs/generated/types.d.ts +102 -3
  8. package/dist/cjs/generated/types.d.ts.map +1 -1
  9. package/dist/cjs/index.d.ts +1 -1
  10. package/dist/cjs/index.d.ts.map +1 -1
  11. package/dist/cjs/index.js.map +1 -1
  12. package/dist/cjs/query-keys.d.ts +5 -0
  13. package/dist/cjs/query-keys.d.ts.map +1 -1
  14. package/dist/cjs/query-keys.js +5 -0
  15. package/dist/cjs/query-keys.js.map +1 -1
  16. package/dist/cjs/resources/addresses.d.ts +47 -4
  17. package/dist/cjs/resources/addresses.d.ts.map +1 -1
  18. package/dist/cjs/resources/addresses.js +38 -3
  19. package/dist/cjs/resources/addresses.js.map +1 -1
  20. package/dist/cjs/resources/registries.d.ts +26 -1
  21. package/dist/cjs/resources/registries.d.ts.map +1 -1
  22. package/dist/cjs/resources/registries.js +26 -1
  23. package/dist/cjs/resources/registries.js.map +1 -1
  24. package/dist/cjs/resources/transfers.d.ts +20 -0
  25. package/dist/cjs/resources/transfers.d.ts.map +1 -1
  26. package/dist/cjs/resources/transfers.js +20 -0
  27. package/dist/cjs/resources/transfers.js.map +1 -1
  28. package/dist/cjs/version.d.ts +1 -1
  29. package/dist/cjs/version.js +1 -1
  30. package/dist/esm/generated/operations.d.ts +16 -0
  31. package/dist/esm/generated/operations.d.ts.map +1 -1
  32. package/dist/esm/generated/operations.js +18 -2
  33. package/dist/esm/generated/operations.js.map +1 -1
  34. package/dist/esm/generated/types.d.ts +102 -3
  35. package/dist/esm/generated/types.d.ts.map +1 -1
  36. package/dist/esm/index.d.ts +1 -1
  37. package/dist/esm/index.d.ts.map +1 -1
  38. package/dist/esm/index.js.map +1 -1
  39. package/dist/esm/query-keys.d.ts +5 -0
  40. package/dist/esm/query-keys.d.ts.map +1 -1
  41. package/dist/esm/query-keys.js +5 -0
  42. package/dist/esm/query-keys.js.map +1 -1
  43. package/dist/esm/resources/addresses.d.ts +47 -4
  44. package/dist/esm/resources/addresses.d.ts.map +1 -1
  45. package/dist/esm/resources/addresses.js +38 -3
  46. package/dist/esm/resources/addresses.js.map +1 -1
  47. package/dist/esm/resources/registries.d.ts +26 -1
  48. package/dist/esm/resources/registries.d.ts.map +1 -1
  49. package/dist/esm/resources/registries.js +26 -1
  50. package/dist/esm/resources/registries.js.map +1 -1
  51. package/dist/esm/resources/transfers.d.ts +20 -0
  52. package/dist/esm/resources/transfers.d.ts.map +1 -1
  53. package/dist/esm/resources/transfers.js +20 -0
  54. package/dist/esm/resources/transfers.js.map +1 -1
  55. package/dist/esm/version.d.ts +1 -1
  56. package/dist/esm/version.js +1 -1
  57. package/docs/concepts.md +9 -0
  58. package/docs/errors.md +40 -3
  59. package/package.json +1 -1
  60. package/src/generated/operations.ts +18 -2
  61. package/src/generated/types.ts +105 -3
  62. package/src/index.ts +1 -0
  63. package/src/query-keys.ts +6 -0
  64. package/src/resources/addresses.ts +53 -3
  65. package/src/resources/registries.ts +26 -1
  66. package/src/resources/transfers.ts +20 -0
  67. package/src/version.ts +1 -1
@@ -8,8 +8,8 @@
8
8
  // resource method calls an operation that exists, and that a new endpoint in
9
9
  // the API does not slip in unclassified.
10
10
  //
11
- // Operations: 256 · admin: 46 · both: 1 · member: 206 · service: 3
12
- // Spec sha256: d0f5c91b0efba0c9b35c34e64163da6f7ed995c7a1e65fb7f1b00e1295da54b8
11
+ // Operations: 258 · admin: 46 · both: 1 · member: 207 · service: 4
12
+ // Spec sha256: 124ba1ba93348e18e6998662349a7b5016f15f655c7f9bbeead84f98307f5984
13
13
 
14
14
  export type Audience = 'member' | 'admin' | 'service' | 'both' | 'unknown'
15
15
 
@@ -552,6 +552,14 @@ export const OPERATIONS = {
552
552
  "summary": "Детали адреса",
553
553
  "audience": "member"
554
554
  },
555
+ "GET /api/v1/vaults/{code}/addresses/{id}/gas": {
556
+ "method": "get",
557
+ "path": "/api/v1/vaults/{code}/addresses/{id}/gas",
558
+ "operationId": "getApiV1VaultsByCodeAddressesByIdGas",
559
+ "tag": "Addresses",
560
+ "summary": "Газ адреса: остаток монеты сети и оценка комиссии",
561
+ "audience": "member"
562
+ },
555
563
  "GET /api/v1/vaults/{code}/addresses/{id}/logo": {
556
564
  "method": "get",
557
565
  "path": "/api/v1/vaults/{code}/addresses/{id}/logo",
@@ -2040,6 +2048,14 @@ export const OPERATIONS = {
2040
2048
  "summary": "Открыть видимость участников (admin)",
2041
2049
  "audience": "admin"
2042
2050
  },
2051
+ "POST /webhooks/monitoring": {
2052
+ "method": "post",
2053
+ "path": "/webhooks/monitoring",
2054
+ "operationId": "postWebhooksMonitoring",
2055
+ "tag": "Webhooks",
2056
+ "summary": "Событие мониторинга V3 Finance (TOPUP, EVM-сети)",
2057
+ "audience": "service"
2058
+ },
2043
2059
  "POST /webhooks/wallet": {
2044
2060
  "method": "post",
2045
2061
  "path": "/webhooks/wallet",
@@ -378,6 +378,53 @@ export interface IncomingTxSummary {
378
378
  assetSymbol: string
379
379
  }
380
380
 
381
+ export interface AddressGasQuery {
382
+ /**
383
+ * Получатель перевода, для которого нужна оценка комиссии
384
+ *
385
+ * length: 1..128
386
+ */
387
+ to?: string
388
+ /**
389
+ * Код токена перевода (Token.code)
390
+ *
391
+ * length: 1..64
392
+ */
393
+ asset?: string
394
+ /**
395
+ * Сумма перевода в целых единицах токена, десятичной строкой
396
+ *
397
+ * length: 1..64
398
+ */
399
+ amount?: string
400
+ }
401
+
402
+ export interface AddressGas {
403
+ /** Network.slug адреса */
404
+ network: string
405
+ /** Кто платит комиссию сети. `address` — сам адрес, своей монетой (Ethereum: нет ETH — перевод токена не уйдёт). `platform` — платформа (Tron): держать на адресе ничего не нужно, остальные поля — null */
406
+ payer: "address" | "platform"
407
+ /** Тикер монеты газа */
408
+ symbol: string | null
409
+ /** Знаков у монеты газа */
410
+ decimals: number | null
411
+ /** Остаток монеты газа на адресе, десятичной строкой. Читается из сети в момент запроса: монета газа в учёте не ведётся, в `balances[]` адреса её нет */
412
+ balance: string | null
413
+ /** Тот же остаток в wei */
414
+ balanceRaw: string | null
415
+ /** Когда остаток прочитан из сети */
416
+ checkedAt: string | null
417
+ /** Оценка комиссии. null — не запрошена (нет to/asset/amount) или посчитать не удалось: не ответил узел, либо на адресе нет самой суммы токена. null — НЕ значит «газа хватает» */
418
+ estimate: {
419
+ /** ПОТОЛОК комиссии запрошенного перевода в монете газа: столько должно лежать на адресе, чтобы перевод ушёл. Спишется обычно меньше */
420
+ fee: string
421
+ /** Тот же потолок в wei */
422
+ feeRaw: string
423
+ /** Хватает ли остатка на эту комиссию (тем же расчётом проверяет отправка) */
424
+ enough: boolean
425
+ } | null
426
+ }
427
+
381
428
  export interface AddressGroupDetail {
382
429
  /** cuid */
383
430
  id: string
@@ -1769,6 +1816,14 @@ export interface CreateNetworkBody {
1769
1816
  logoUri?: string
1770
1817
  /** Тип сети, напр. "TRON", "EVM" */
1771
1818
  type?: string
1819
+ /**
1820
+ * Номер EVM-сети (EIP-155). ОБЯЗАТЕЛЕН для EVM-сети (Ethereum — 1) и запрещён для остальных
1821
+ *
1822
+ * range: 1..9007199254740991
1823
+ */
1824
+ chainId?: number
1825
+ /** Тикер монеты газа EVM-сети (ETH). Только для EVM-сетей */
1826
+ nativeSymbol?: string
1772
1827
  }
1773
1828
 
1774
1829
  export interface CreateOperationCategoryBody {
@@ -3047,6 +3102,36 @@ export interface Membership {
3047
3102
  createdAt: string
3048
3103
  }
3049
3104
 
3105
+ export interface MonitoringWebhookBody {
3106
+ tx: {
3107
+ /** Имя сети у мониторинга, ПРОПИСНЫМИ; в нижнем регистре обязано совпадать со `slug` сети в реестре */
3108
+ network: string
3109
+ /** Тикер; токен определяется по `contract`, не по нему */
3110
+ asset: string
3111
+ /** Адрес контракта токена или `native` (монета сети — не зачисляется) */
3112
+ contract: string
3113
+ type: "TOPUP"
3114
+ /** Хеш транзакции (EVM — с `0x`) */
3115
+ id: string
3116
+ /** range: -9007199254740991..9007199254740991 */
3117
+ block: number
3118
+ /** МИЛЛИСЕКУНДЫ (не секунды) */
3119
+ timestamp: number
3120
+ from: string
3121
+ to: string
3122
+ /** raw smallest units; только цифры, > 0 и ≤ 10^17 */
3123
+ value: string
3124
+ /**
3125
+ * Место перевода в блоке (EVM): различает одинаковые переводы одной транзакции
3126
+ *
3127
+ * range: 0..9007199254740991
3128
+ */
3129
+ logIndex?: number
3130
+ }
3131
+ /** Только у пробного события — оно не зачисляется */
3132
+ test?: true
3133
+ }
3134
+
3050
3135
  export interface MySessionList {
3051
3136
  items: MySession[]
3052
3137
  nextCursor: string | null
@@ -3103,6 +3188,10 @@ export interface Network {
3103
3188
  logoUri: string | null
3104
3189
  /** Тип сети (свободная строка) */
3105
3190
  type: string | null
3191
+ /** Номер EVM-сети (EIP-155): Ethereum — 1. null — у не-EVM сетей. По нему подписывающий сервис выбирает сеть: путь у всех EVM-сетей один */
3192
+ chainId: number | null
3193
+ /** Тикер монеты, которой адрес сам платит за газ (ETH). null — газ не оплачивается с адреса (Tron: ресурсы покупает платформа). Монета газа — не актив учёта: её остаток — `GET …/addresses/{id}/gas` */
3194
+ nativeSymbol: string | null
3106
3195
  /** format: date-time */
3107
3196
  createdAt: string
3108
3197
  /** format: date-time */
@@ -3480,7 +3569,7 @@ export interface PatchGroupGrantBody {
3480
3569
  canCreateAddress?: boolean
3481
3570
  }
3482
3571
 
3483
- /** Частичное обновление метаданных сети (admin). coinType/code/slug неизменяемы — на них ссылаются адреса, токены и webhook-матчинг */
3572
+ /** Частичное обновление метаданных сети (admin). coinType/code/slug неизменяемы — на них ссылаются адреса, токены и webhook-матчинг; chainId — только пока в сети нет адресов */
3484
3573
  export interface PatchNetworkBody {
3485
3574
  /** length: 1..∞ */
3486
3575
  name?: string
@@ -3489,6 +3578,14 @@ export interface PatchNetworkBody {
3489
3578
  logoUri?: string | null
3490
3579
  /** Тип сети, напр. "TRON", "EVM"; null — очистить */
3491
3580
  type?: string | null
3581
+ /**
3582
+ * Номер EVM-сети. Задать или сменить можно, только пока в сети нет адресов: тот же ключ в другой цепи — другой счёт
3583
+ *
3584
+ * range: 1..9007199254740991
3585
+ */
3586
+ chainId?: number
3587
+ /** Тикер монеты газа; null — очистить */
3588
+ nativeSymbol?: string | null
3492
3589
  }
3493
3590
 
3494
3591
  export interface PatchOperationCategoryBody {
@@ -4042,7 +4139,7 @@ export interface ReconcileLegacyMetadataResult {
4042
4139
  }
4043
4140
 
4044
4141
  export interface ReconcileTransferBody {
4045
- /** Хеш от подписывающего сервиса. ЕСТЬ — транзакция ушла в сеть, перевод доводится до confirmed. НЕТ (или null) — сверяющий утверждает, что broadcast'а не было, и резерв возвращается (failed). Для pending с неясным исходом (у pending без txHash его не отличить по ответам API — failureReason у незакрытого перевода null) это утверждение нужно ПРОВЕРИТЬ по сети: возврат за ушедшую транзакцию печатает деньги. Если у pending-перевода хеш уже сохранён (broadcast прошёл), он обязателен: без него — 409 TRANSFER_BROADCAST, с другим — 409 TXHASH_MISMATCH (сохранённый — в error.details.txHash) */
4142
+ /** Хеш от подписывающего сервиса. ЕСТЬ — транзакция ушла в сеть, перевод доводится до confirmed. НЕТ (или null) — сверяющий утверждает, что broadcast'а не было, и резерв возвращается (failed). Для pending с неясным исходом (у pending без txHash его не отличить по ответам API — failureReason у незакрытого перевода null) это утверждение нужно ПРОВЕРИТЬ по сети: возврат за ушедшую транзакцию печатает деньги. Если у pending-перевода хеш уже сохранён (broadcast прошёл), он обязателен: без него — 409 TRANSFER_BROADCAST, с другим — 409 TXHASH_MISMATCH (сохранённый — в error.details.txHash). EVM-сети: сервер проверяет сеть сам — без хеша резерв возвращается, только если транзакции перевода нет ни в блоке, ни в очереди узла (иначе 409 BROADCAST_DETECTED); с хешем перевод подтверждается, только если транзакция отправлена с адреса перевода и уже в блоке (иначе 409 TX_NOT_INCLUDED / TXHASH_MISMATCH, не хеш — 400 INVALID_TXHASH). Хеш EVM принимается с `0x` и без, в любом регистре */
4046
4143
  txHash?: string | null
4047
4144
  /** DEPRECATED: пишется в legacy-поле `fee` перевода как есть (свободный текст, единица не определена). На `networkFee` (комиссию сети) это поле не влияет */
4048
4145
  fee?: string | null
@@ -4053,6 +4150,7 @@ export interface ReconcileTransferBody {
4053
4150
  export interface ReconcileTransferResult {
4054
4151
  /** Статус перевода после сверки: confirmed (по хешу) | failed (резерв возвращён). rejected/cancelled — у закрытого перевода с невозвращённым резервом: резерв возвращён, статус прежний */
4055
4152
  status: "confirmed" | "failed" | "rejected" | "cancelled"
4153
+ /** Хеш транзакции перевода. У confirmed — всегда. У failed — null, кроме EVM-перевода, чья транзакция попала в блок, но отклонена контрактом (revert): перевода в сети не было, резерв возвращён, хеш оставлен как след */
4056
4154
  txHash: string | null
4057
4155
  }
4058
4156
 
@@ -4091,6 +4189,10 @@ export interface RegistryNetwork {
4091
4189
  logoUri: string | null
4092
4190
  /** Тип сети (свободная строка) */
4093
4191
  type: string | null
4192
+ /** Номер EVM-сети (EIP-155): Ethereum — 1. null — у не-EVM сетей. По нему подписывающий сервис выбирает сеть: путь у всех EVM-сетей один */
4193
+ chainId: number | null
4194
+ /** Тикер монеты, которой адрес сам платит за газ (ETH). null — газ не оплачивается с адреса (Tron: ресурсы покупает платформа). Монета газа — не актив учёта: её остаток — `GET …/addresses/{id}/gas` */
4195
+ nativeSymbol: string | null
4094
4196
  /** format: date-time */
4095
4197
  createdAt: string
4096
4198
  /** format: date-time */
@@ -4890,7 +4992,7 @@ export type WebhookResult = {
4890
4992
  receivedAsset: string
4891
4993
  } | {
4892
4994
  ignored: true
4893
- reason: "trx_events_disabled" | "address_not_found" | "token_not_registered"
4995
+ reason: "trx_events_disabled" | "native_events_disabled" | "address_not_found" | "token_not_registered" | "test_event" | "wrong_endpoint"
4894
4996
  } | {
4895
4997
  duplicate: true
4896
4998
  eventId: string
package/src/index.ts CHANGED
@@ -87,6 +87,7 @@ export {
87
87
  AddressesResource,
88
88
  type AddressFilters,
89
89
  type AddressFacet,
90
+ type AddressGasParams,
90
91
  type AddressesSummaryParams,
91
92
  type ListAddressesParams,
92
93
  type PendingApproval,
package/src/query-keys.ts CHANGED
@@ -11,6 +11,12 @@ export const queryKeys = {
11
11
  addresses: (code: string, filters?: Record<string, unknown>) =>
12
12
  ['v3', 'vault', code, 'addresses', filters ?? null] as const,
13
13
  address: (code: string, id: string) => ['v3', 'vault', code, 'address', id] as const,
14
+ /**
15
+ * Under the address's own key on purpose: invalidating `address(code, id)`
16
+ * drops its gas too, and after a transfer from the address both are stale.
17
+ */
18
+ addressGas: (code: string, id: string, transfer?: Record<string, unknown>) =>
19
+ ['v3', 'vault', code, 'address', id, 'gas', transfer ?? null] as const,
14
20
  transfer: (code: string, id: string) => ['v3', 'vault', code, 'transfer', id] as const,
15
21
  history: (code: string, filters?: Record<string, unknown>) =>
16
22
  ['v3', 'vault', code, 'history', filters ?? null] as const,
@@ -3,6 +3,7 @@ import type { Page, PageParams } from '../core/pagination.js'
3
3
  import { toGated, type Gated } from '../core/gated.js'
4
4
  import type { Address, AddressDetail } from './types.js'
5
5
  import type {
6
+ AddressGas,
6
7
  AddressesSummary,
7
8
  CreateAddressBody,
8
9
  CreateAddressResult,
@@ -75,6 +76,19 @@ export interface ListAddressesParams extends AddressFilters, PageParams {
75
76
  sort?: 'createdAt' | 'lastActivity' | undefined
76
77
  }
77
78
 
79
+ /**
80
+ * The transfer `gas()` should estimate the fee of. All three together or none:
81
+ * a partial set is 400 `GAS_QUERY_INCOMPLETE`.
82
+ */
83
+ export interface AddressGasParams {
84
+ /** The recipient. */
85
+ to?: string | undefined
86
+ /** Token code: `usdt_eth`. */
87
+ asset?: string | undefined
88
+ /** The amount in whole units of the token, as a decimal string — what `transfers.send` takes. */
89
+ amount?: string | undefined
90
+ }
91
+
78
92
  /** What `summary()` can count by. */
79
93
  export type AddressFacet = keyof AddressesSummary['facets']
80
94
 
@@ -139,6 +153,39 @@ export class AddressesResource {
139
153
  return this.#http.request<AddressDetail>('GET', `${this.#base}/${seg(addressId)}`)
140
154
  }
141
155
 
156
+ /**
157
+ * Who pays the network fee for transfers from this address, and whether
158
+ * there is enough to pay it.
159
+ *
160
+ * `payer: 'platform'` (TRON) — the platform buys the resources, nothing has
161
+ * to be kept on the address, and every other field is `null`.
162
+ * `payer: 'address'` (Ethereum) — the address pays itself, in the network's
163
+ * coin (`symbol`, ETH): without it a token transfer does not leave, however
164
+ * much of the token is there, and `transfers.send` answers 400
165
+ * `INSUFFICIENT_GAS`. Show `balance` next to the token balances and check
166
+ * `estimate.enough` before offering to send.
167
+ *
168
+ * THE COIN IS NOT AN ASSET OF THE VAULT. `balance` is read from the network
169
+ * at the moment of the call (`checkedAt`); it is not in the address's
170
+ * `balances[]`, a top-up of it does not arrive as a deposit, and it cannot
171
+ * be sent with `transfers.send`.
172
+ *
173
+ * With `to`, `asset` and `amount` the answer carries `estimate` — the
174
+ * CEILING of the fee for that transfer, computed the way sending checks it;
175
+ * what is charged is usually less. `estimate: null` with all three passed is
176
+ * not a refusal: the fee could not be computed — the node did not answer, or
177
+ * the address does not hold the token amount itself.
178
+ *
179
+ * Needs the `view` right on the address (404 otherwise). 409
180
+ * `NETWORK_NOT_READY` — the network is not set up for reading the chain;
181
+ * 502 `ONCHAIN_STATE_UNAVAILABLE` — the node did not answer, ask again.
182
+ */
183
+ gas(addressId: string, params: AddressGasParams = {}): Promise<AddressGas> {
184
+ return this.#http.request<AddressGas>('GET', `${this.#base}/${seg(addressId)}/gas`, {
185
+ query: { ...params },
186
+ })
187
+ }
188
+
142
189
  /**
143
190
  * 201 — the address is ready (`applied`); 202 — it went for approval and a
144
191
  * request came back (`pending`); 200 — a replay of `idempotencyKey`
@@ -157,9 +204,12 @@ export class AddressesResource {
157
204
  * rolled back) does not consume the key. The key is per member of the
158
205
  * vault.
159
206
  *
160
- * Only TRON has deposit monitoring, so an address on any other network of
161
- * the vault is refused with 400 `NETWORK_NOT_MONITORED` before anything is
162
- * asked of the signing service.
207
+ * An address is created only on a network whose deposits are monitored:
208
+ * TRON, and an EVM network (Ethereum) once the API is connected to its
209
+ * monitoring. On any other network of the vault it is refused with 400
210
+ * `NETWORK_NOT_MONITORED` before anything is asked of the signing service;
211
+ * 409 `NETWORK_NOT_READY` — an EVM network in a vault whose signing service
212
+ * cannot derive EVM addresses.
163
213
  */
164
214
  async create(input: CreateAddressBody): Promise<Gated<CreateAddressResult, PendingApproval>> {
165
215
  const res = await this.#http.requestRaw<unknown>('POST', this.#base, { body: input })
@@ -188,12 +188,22 @@ export class RegistriesResource {
188
188
  * A derivation path is written WITHOUT apostrophes — `m/44/195/…`, not
189
189
  * `m/44'/…`. The hardened marker is implied; writing it out produces a
190
190
  * different path and therefore different addresses.
191
+ *
192
+ * An EVM network (`type: 'EVM'`, `coinType: 60`) needs `chainId` — Ethereum
193
+ * is 1 — and takes `nativeSymbol`, the coin its addresses pay the fee in
194
+ * (`ETH`); both are refused on any other network. `slug` must be the
195
+ * network's name at the deposit monitoring, in lower case (`ethereum`):
196
+ * incoming payments are matched to the network by it.
191
197
  */
192
198
  createNetwork(input: CreateNetworkBody): Promise<Network> {
193
199
  return this.#http.request<Network>('POST', '/api/v1/networks', { body: input })
194
200
  }
195
201
 
196
- /** Administrators only. */
202
+ /**
203
+ * Administrators only. `chainId` can be set or changed only while the
204
+ * network has no addresses (409 otherwise): the same key on another chain is
205
+ * another account.
206
+ */
197
207
  updateNetwork(networkId: string, input: PatchNetworkBody): Promise<Network> {
198
208
  return this.#http.request<Network>('PATCH', `/api/v1/networks/${encodeURIComponent(networkId)}`, {
199
209
  body: input,
@@ -206,6 +216,21 @@ export class RegistriesResource {
206
216
  * The contract address is the key: an incoming payment is matched to a
207
217
  * token by it, so a wrong one means deposits land on the wrong asset or
208
218
  * nowhere at all.
219
+ *
220
+ * On an EVM network `decimals` is checked against the contract itself:
221
+ * the signing service converts an amount by the contract's `decimals()`,
222
+ * the ledger by the registry's, and one digit of difference sends ten times
223
+ * what was booked. 400 `TOKEN_DECIMALS_MISMATCH` (the contract's number is
224
+ * in `message`); 400 `INVALID_CONTRACT_ADDRESS` — not an address, or no
225
+ * token contract there; 400 `TOKEN_DECIMALS_UNSUPPORTED` — more than 9;
226
+ * 400 `EVM_NATIVE_NOT_SUPPORTED` — the network's coin (ETH) is not an asset
227
+ * and is not registered; 409 `NETWORK_NOT_READY` — the network has no
228
+ * `chainId` or no node to read from; 409 `ONCHAIN_STATE_UNAVAILABLE` — the
229
+ * node did not answer, the token was not created, try again.
230
+ *
231
+ * A token code is unique across networks, so USDT on Ethereum is a token of
232
+ * its own (`usdt_eth`): policies and limits written for `usdt` do not apply
233
+ * to it.
209
234
  */
210
235
  createToken(input: CreateTokenBody): Promise<TokenWithNetwork> {
211
236
  return this.#http.request<TokenWithNetwork>('POST', '/api/v1/tokens', { body: input })
@@ -76,6 +76,14 @@ export class TransfersResource {
76
76
  *
77
77
  * A key beginning with `draft:` is refused with 400 `BAD_REQUEST`: the
78
78
  * prefix is reserved for the transfers `transferDrafts.send()` creates.
79
+ *
80
+ * From an Ethereum address the fee is paid by the address itself, in ETH,
81
+ * and its transactions go out one at a time: 400 `INSUFFICIENT_GAS` (top up
82
+ * the address — `addresses.gas()` shows what is there), 409 `ADDRESS_BUSY`
83
+ * (an earlier transfer from it is not settled yet), 409
84
+ * `ONCHAIN_STATE_UNAVAILABLE` (the network did not answer). All three are
85
+ * definite refusals — the transfer is `failed` and the reserve is back — so
86
+ * a retry takes a NEW key.
79
87
  */
80
88
  async send(
81
89
  input: CreateTransferBody,
@@ -192,6 +200,18 @@ export class TransfersResource {
192
200
  * the saved hash in `details.txHash`. The other two cases never executed
193
201
  * and take no hash.
194
202
  *
203
+ * On Ethereum the server DOES check the chain. Without a hash the reserve
204
+ * is returned only if no transaction left the address since the transfer
205
+ * went to the signing service — 409 `BROADCAST_DETECTED` otherwise
206
+ * (`details.address`: find the hash in an explorer and send it). With a
207
+ * hash the transaction must be from the transfer's address, not older than
208
+ * the transfer and already in a block: 400 `INVALID_TXHASH`, 409
209
+ * `TX_NOT_INCLUDED`, 409 `TXHASH_MISMATCH`. A transaction the contract
210
+ * reverted settles the transfer as `failed` WITH that `txHash` and the
211
+ * reserve returned, so read `status` of the answer rather than assuming
212
+ * `confirmed`. 409 `ONCHAIN_STATE_UNAVAILABLE` — the chain could not be
213
+ * read, nothing moved, reconcile again later.
214
+ *
195
215
  * A FRESH transfer is refused on purpose — while execution may still be in
196
216
  * flight, intervening risks a SECOND broadcast, which costs more than
197
217
  * waiting.
package/src/version.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** SDK version, sent in the `user-agent` header. */
2
- export const SDK_VERSION = '0.21.0'
2
+ export const SDK_VERSION = '0.22.0'
3
3
 
4
4
  /** Default API base URL. */
5
5
  export const DEFAULT_BASE_URL = 'https://policy-engine-rest.ezig.workers.dev'