@atumlabs/payment-gateway-client 2.1.0 → 3.0.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,120 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [3.0.0] - 2026-09-16
11
+
12
+ > **Read this before upgrading if the gateway has been accepting your asset identifiers.**
13
+ > They are now validated locally, on both entry points and on both legs of the payment. One rule
14
+ > is stricter than the gateway's, the EIP-55 checksum on a mixed-case EVM token address, so a
15
+ > value the gateway resolves fine can be refused before the request is even built. See Breaking.
16
+ >
17
+ > A second break sits there too. A blank `pinnedAddress` is now rejected rather than skipping the
18
+ > sender check, so a caller that defaults that field to an empty string has to pass the sender
19
+ > address instead, or omit the field to skip the check on purpose.
20
+
21
+ Quote-requests now carry the same idempotency contract as payments: one `request_id`
22
+ identifies one batch, re-sending it recovers that batch, and reusing it for a different
23
+ corridor is refused rather than silently served.
24
+
25
+ ### Breaking
26
+ - Asset identifiers are validated on every entry point. `prepareQuoteRequest` built no deposit and so applied no address rules at all, and `preparePaymentRequest` applied them only to the source, since only the source reached a chain library. Both legs of both entry points are now checked, so a value that used to be forwarded can now be refused locally, with the messages under Fixed: a malformed or wrongly-checksummed EVM token address, a placeholder such as `erc20:0x6`, a native `slip44` asset, a malformed Tron or Solana token reference, or a hex `eip155` chain id. Every segment is also checked against the character set the PaymentRequest schema publishes, so a stray space is refused here rather than remotely.
27
+ - **A mixed-case EVM token address whose EIP-55 checksum does not hold is refused on the destination leg too, and that is deliberate.** The gateway tolerates such a destination on purpose: `blockchain.AssetIdentifier.Equal` folds the case of an eip155 token address with `EqualFold`, the token registry lowercases before it looks a token up, and `payment-gw/internal/canonical` folds a destination it could not parse rather than refusing it, precisely so two spellings of one destination cannot refuse a legitimate retry. The settler lowercases before it checksums, so a wrong checksum settles fine. This rule therefore buys no settlement safety. It is typo protection while the request is still being built, kept fatal because a mistyped token address is cheap to catch here and expensive to discover once a payout has landed on it. It is narrow on purpose: the destination account is not checked, so this is not a claim that the client validates the receive side. A caller that can rewrite the value should send the all-lowercase form of the destination, which makes no checksum claim, is accepted, and is the same twenty bytes. A caller whose corridor is composed inside a library that builds the request for it, as in `mppx-atum-escrow`, has nothing to rewrite, and the lowercasing belongs there.
28
+ - **Behaviour change.** An empty `pinnedAddress` is now rejected before anything is signed or submitted, on both signing providers. It previously counted as omitting the field, so the check that the sender is the signer's own address was skipped: the Turnkey path forwarded the pin only when truthy, and the private-key path gated its key-derivation check the same way. What that produced depended on the caller. `send-payment` derives the depositor from the same `<sender>` argument, so the payment went out with an empty source account for the gateway to reject. An SDK caller that supplies `depositor` and `pinnedAddress` separately got a valid, settleable payment whose sender was never checked against the wallet or the key, which is the case this closes. A call that previously proceeded now throws, so a caller defaulting the field to `''` needs to fall back to the sender address instead. Omitting `pinnedAddress` still skips the check as before.
29
+ - `prepareQuoteRequest` now **requires** `requestId`, and `requestIdPrefix` is gone. It
30
+ previously generated an id when you omitted one, on the grounds that the id was only a
31
+ correlation handle there — which is no longer true, because it is now the idempotency key.
32
+ Generating one for you meant a rebuilt retry quietly opened a **second** batch and left the
33
+ first unreachable. `preparePaymentRequest` has always required it; the two now match. The requirement is
34
+ enforced at runtime as well as in the type, so an untyped JavaScript caller or an empty
35
+ string throws rather than sending a request with no idempotency key. Pass
36
+ your own stable id, and reuse it to retry. The `request-quote` CLI is unaffected: it
37
+ generates an id when `--request-id` is omitted and prints it back, exactly as `send-payment`
38
+ does.
39
+ - `QuoteRequestResponse.idempotent_replay` and `QuoteRequestAccepted.idempotent_replay` are new
40
+ **required** fields. Reading a response is simpler, not harder — the flag is always present,
41
+ so `false` means `false` rather than "maybe an older gateway".
42
+ - **The error `domain` value `SOLVER_GATEWAY` is now `SETTLER_GATEWAY`.** It names the service that runs the settler auction, which is a settler gateway; the old name was left over from earlier terminology and was the only place the word "solver" still reached callers. Code that switches on `AtumError.domain` and has a `'SOLVER_GATEWAY'` case must rename it — nothing else about the error changes, and `domain` is diagnostic metadata rather than something the payment flow branches on, so most callers are unaffected. The public `code` and `message` on an error are unchanged: the internal codes behind this domain already mapped to the public `SERVICE_BUSY` and `INTERNAL_ERROR`, and still do.
43
+
44
+ ### Added
45
+ - **`ensureSourceApproval` and `needsSourceApproval`**, so the Permit2 prerequisite this package has always stated can now be satisfied from it. Paying from EVM or Tron needs a one-off approval of the source token for Permit2; without it a payment is built correctly, signed correctly, accepted by the gateway, and then reverts on-chain at settlement — the most expensive way to learn about a missing allowance. Until now the README and `send-payment --help` named the requirement and offered no way to meet it. `ensureSourceApproval` reads the current allowance and sends an approval only if it falls short; `needsSourceApproval` answers the same question read-only, spending no gas, so a payer can be warned before being asked to sign. Solana reports that no approval is needed rather than doing nothing, since its deposit authorizes the transfer itself. **This is the first part of this package that broadcasts a transaction and spends gas.** Everything else builds and signs offline, and that has not changed: you pass a connected ethers signer (or a TronWeb instance for Tron), so the package still never chooses an RPC endpoint or holds a key. An approval is unlimited by default, so later payments need no further transaction; `approvalAmount` bounds it instead, at the cost of having to renew it as Permit2 consumes it — pair a bound with `requiredAllowance` across repeated payments, or the bound stops covering itself as soon as the first charge is decremented from it. Waiting for the approval to confirm is bounded by `confirmation.timeoutMs` (one minute by default) rather than indefinite, and `onSubmitted` hands you the transaction hash the moment it is broadcast. Tokens that refuse to overwrite a non-zero allowance — mainnet USDT most notably — are reset to zero first, but only where the token actually demands it. An approval is refused outright when the signer you pass does not hold the `owner` account whose allowance was read: an approval only ever applies to the account that sends it, so a mismatched signer would approve that account, hand back a transaction hash that reads as success, and leave the owner exactly as unable to pay as before. The read-only `needsSourceApproval` is unaffected, since asking whether a payer is ready without holding their keys is a legitimate preflight. `isUnconfirmed` ships alongside them for telling a broadcast-but-unseen approval apart from one that failed: the wait for a confirmation is bounded, and reaching that bound is not a failure, so the two need opposite responses. `approve-permit2` reports an unconfirmed run as `{"unconfirmed": true, "txHash": ...}` on stdout rather than as a bare non-zero exit indistinguishable from a revert. These helpers raise an allowance and never lower one, so `--amount` below an allowance the wallet already holds leaves it alone and says so.
46
+ - **`approve-permit2`**, a command that performs that approval. `approve-permit2 <sender> <sourceAsset> --rpc-url <url>` takes the same CAIP-19 asset string as `send-payment`, and `--check` reports whether an approval is needed without sending anything or needing a key. It is a separate command rather than a flag on `send-payment` because it is a different kind of act: it spends gas, once per wallet and token, and is worth doing deliberately and ahead of time rather than as a side effect of paying. The private key comes from `PRIVATE_KEY` or an interactive prompt and is never accepted as a flag, which would put it in shell history and in the process list. EVM and Tron; Tron additionally needs `tronweb`, an optional peer dependency, so that EVM-only installs do not carry it. The result JSON goes to stdout, like the other commands. The allowance is read before a key is ever requested, so an already-approved wallet — which is every wallet after the first run — never has to produce a secret to learn there was nothing to do, and the key is checked against `<sender>` before anything is sent, so a mismatched key cannot approve the wrong account and report success.
47
+ - **`send-payment --prepare-only` and `send-payment --submit <file>`** split the single-shot command in two. `--prepare-only` builds and signs a payment request, prints it to stdout, and stops without submitting; `--submit` sends one that was prepared earlier (`-` reads stdin, so the two pipe together). Together they turn the single-shot command into an inspect-then-approve flow: the printed document is byte-for-byte what that run would have POSTed, so it can be read and reviewed before any money moves. Treat it like a signed cheque: it is a signed authorization rather than a draft and `--submit` needs no key, so delete the file once the payment is sent or abandoned. Re-preparing under the same `request_id` targets the same payment and cannot pay twice, but does not reproduce the same bytes: the deadlines are stamped from the clock on each run and the signature covers them. Two things to know. `--prepare-only` still calls the gateway, which is where the corridor addresses come from, so it is not an offline signing mode. And the exit-code table describes a *submitted* payment, so it does not apply under `--prepare-only`, where `0` means the request was built and signed and no payment exists — do not chain a payment-conditional step off such a run. If you intend to submit later, widen the quote window with `--quote-deadline-seconds` — but by tens of seconds, not minutes. A prepared document is submittable only while its window is open (the default is 10 seconds), and that same window is the settler auction: the gateway waits it out before selecting, and settler quotes expire on their own, so an over-long window ends in a terminal `QUOTES_EXPIRED`. `--submit` signs nothing and needs no private key, takes no corridor arguments, refuses the options that only shape a request being built rather than ignoring them, and reports with the same exit codes and streams as an ordinary run; it supports `--wait` the same way. The two flags are mutually exclusive, and a short invocation now names both forms rather than reporting a missing argument.
48
+ - The Permit2 approval prerequisite now appears at the top of `send-payment --help`, above the arguments and options, instead of in the last paragraph. It is the most common cause of a payment that is built and signed correctly and still fails to settle, and it was previously about a hundred lines below the usage line. The contract addresses stay at the end of the help, where the prerequisite points.
49
+ - **`waitForTerminalStatus` and `isTerminalStatus` are exported**, so following a submitted payment to its end is one call rather than a hand-written loop. A submission usually comes back `pending`, so waiting is the ordinary path, and the previous answer — write your own poll — put the burden of getting it right on every caller. A failed status check does not end the wait: a blip while a payment is settling is the worst moment to stop looking, so failures are counted in `errorCount`, reported through `onError`, and polling continues to the budget. The outcome reports `timedOut` so a caller can tell "still in flight" from "finished", which a bare loop cannot. This is the same helper behind the `send-payment --wait` flag, so the command-line tools and the SDK now agree by construction. `isTerminalStatus` is the single definition of which states are final, so a caller no longer keeps its own copy of that list in step with the contract. `budgetMs` is optional and in milliseconds, defaulting to `DEFAULT_WAIT_BUDGET_MS` (one minute); the seconds-based constant behind the command line's `--wait-seconds` stays internal, so there is one unit on the public surface and no way to pass 60 where 60000 was meant. An optional `signal` ends the wait early for a caller that must stop on shutdown or when its request is cancelled, and the outcome reports `aborted` — which always implies `timedOut`, so an interrupted wait can never be read as a settled payment. Also exported: `DEFAULT_WAIT_BUDGET_MS`, `DEFAULT_POLL_INTERVAL_MS`, `StatusSnapshot`, `WaitOutcome`, `WaitParams`.
50
+ - **`ErrorResponse.payment_id`**, alongside the existing `request_id`. The two ids are independent and either can be absent: `request_id` correlates the HTTP call, and `payment_id` names the payment the error was raised against. It closes a real mislabel. A settlement failure on `POST /v1/payments` was returning the payment id in `request_id`, because that was the only id field the shape had, so a caller who trusted the field name and looked the value up as a request id found nothing. Read `getErrorResponse(err)?.payment_id` and reconcile with `GET /v1/payments/{paymentId}/status` before retrying, because a failed settlement leaves the on-chain outcome unguaranteed. The field is absent whenever the error is not about a specific payment, which is every validation or authentication failure raised before a payment exists.
51
+ - `parseAssetIdentifier` and `assetChainId` are exported, so a caller can apply the same parsing and canonicalization the CLIs do.
52
+ - `timeoutMs` and `syncWaitTimeoutMs` on the client config, for callers whose gateway is slower than the defaults (30s for a promptly-answered request, 120s for one the gateway holds open). The two are separate because some endpoints are held open on purpose, bounded by the gateway's own `quote_sync_wait_seconds` and `payment_sync_wait_seconds`, so one budget cannot serve both: too short aborts a settling payment, too long leaves an unresponsive gateway hanging. An interceptor that sets `timeout` still takes precedence, for a per-request override. New exports: `GatewayTimeoutError`, `isGatewayTimeoutError`, `PaymentGatewayClientConfig`, `RequestTimeouts`, `DEFAULT_REQUEST_TIMEOUT_MS`, `DEFAULT_SYNC_WAIT_TIMEOUT_MS`.
53
+ - `createQuoteRequest` returns **`409` `IDEMPOTENCY_TERMS_MISMATCH`** when a `request_id` is
54
+ reused with different economics (accounts, assets, or amounts), instead of returning the
55
+ first batch. Without it you could receive quotes priced for the corridor you asked for
56
+ earlier, and awarding one of those settles a payment on that corridor.
57
+ - `idempotent_replay` on both quote-request responses tells you whether you were handed an
58
+ existing batch or a newly opened one.
59
+
60
+ ### Changed
61
+ - `resolveTurnkeyAddresses` takes its Turnkey config without `pinnedAddress`. That call lists the wallet's accounts and verifies nothing, so a pin handed to it was ignored. Passing one inline is now a compile error instead of a check that never ran. A caller reusing one whole `TurnkeyConfig` for both this call and signing is unaffected.
62
+ - The CLIs no longer print the full gateway defaults listing when a chain-defaults lookup fails. The failure itself names the chain and carries the gateway's error, and the client no longer makes the second `/defaults` request that fetched the listing.
63
+ - Re-sending a quote-request whose `quote_deadline` has already passed now returns the original
64
+ batch instead of `400 QUOTE_DEADLINE_NOT_FUTURE`. The collection window is short, so a retry
65
+ after a lost response almost always carries an expired deadline — previously that made the
66
+ `quote_request_id` unrecoverable even though the batch existed and held quotes. Deadlines are
67
+ exempt from the idempotency comparison, on this endpoint as on payments.
68
+ - Note the window itself is not extended: it belongs to the batch, so asking again with a later
69
+ `quote_deadline` returns the batch's own window.
70
+ - `docs/idempotency.md` is reorganised around the shared contract rather than the payment
71
+ endpoint, with the endpoint-specific parts (the on-chain settlement guarantee, payment status)
72
+ labelled as such.
73
+ - The `409 IDEMPOTENCY_TERMS_MISMATCH` message no longer says a *payment* exists. It previously
74
+ read "already used for a payment with different terms", which is wrong on quote-requests —
75
+ nothing is charged there and no payment exists for the caller to go looking for. It now says
76
+ "already used for a different request". This affects the payments path too: the wording is
77
+ slightly less specific there, in exchange for being correct on both. The `code` and the docs
78
+ link are unchanged, so nothing a client branches on has moved.
79
+ - The asynchronous (202) quote-request response now says plainly that its `status` field is a
80
+ constant rather than a report of the batch's state: on an idempotent replay the window may
81
+ already have closed and it will still read `collecting`. Points at
82
+ `GET /v1/payments/quote-requests/{quoteRequestId}` instead. Documentation only.
83
+
84
+ ### Fixed
85
+ - A malformed asset identifier is reported with the offending value and what to correct, instead of surfacing as a chain-library error. A missing `/` between the chain and the token says `Invalid asset identifier "<value>": expected CAIP-19 "<chain>/<type>:<address>", e.g. eip155:421614/erc20:0x...` where it previously threw `TypeError: Cannot read properties of undefined (reading 'split')`. An empty token or a stray slash says `Invalid token address in asset "<value>".`, and a mixed-case address whose EIP-55 checksum does not hold says `Token address "<addr>" has an invalid checksum. Fix the capitalization or use the all-lowercase form.` Those were `invalid address` and `bad address checksum` respectively, from `ethers`. Two cases name their real cause rather than the address they were also reported as: a hex `eip155` chain id says `Invalid eip155 chain id "0x66eee" in asset "<value>": use the decimal chain id (421614), not hex.` and any other non-decimal reference says `Invalid eip155 chain id "<reference>" in asset "<value>": an eip155 chain id is decimal, e.g. 421614.`, while a native asset says `Asset "<value>" is a native asset (slip44) and has no contract to deposit. Use the wrapped token's erc20 identifier.`
86
+ - An identifier whose CAIP-2 namespace is not lowercase (`EIP155:42161/...`) is routed rather than refused as an unsupported chain. Both namespaces are canonicalized to lowercase in the request the client builds and in the deposit it signs, which is what the PaymentRequest schema requires, so such a request is no longer rejected by the gateway either.
87
+ - A Tron chain reference is folded with the namespaces, mirroring the protocol's own `manifest.CanonicalizeCAIP2`, so `TRON:MAINNET/trc20:...` routes instead of failing inside the sender_auth SDK with `no Permit2 address known for Tron network`. A Solana reference is still left alone: it is base58, and its cluster name is UTF-8 encoded into the escrow's on-chain `cluster_id`, so folding it would change the signing domain.
88
+ - A failed chain-defaults lookup reports the gateway's own `code`, `message` and `request_id` instead of the HTTP status text, which reduced every cause to `Bad Request`.
89
+ - A non-integer value for `--quote-deadline-seconds`, `--fulfillment-deadline-seconds` or `--wait-seconds` (for example `1.5`, `1e3`, `0x10`, or plain text) now prints the one-line reason and exits `1`, instead of a full Node stack trace. The CLIs already refused to run with such a value and the exit code is unchanged; only the output is. The option parser runs before the command's error handling, so what it threw had been escaping uncaught.
90
+ - A whitespace-only `pinnedAddress` was not skipped but reported as an address mismatch, so the error named a padded value rather than the actual problem. It now gets the same up-front rejection as an empty one.
91
+ - `send-payment` validates `<sender>` before prompting for a private key, so a blank argument no longer costs the user an entered secret first.
92
+ - Gateway requests now time out instead of hanging. The client had no network timeout: the chain-defaults call used a bare `fetch` with no abort signal and the HTTP client set none, so a gateway that accepted the connection and never replied left the CLI waiting indefinitely with nothing on stdout or stderr. Requests now abort and raise a `GatewayTimeoutError` reading `Gateway at <url> did not respond within <n>s`. The abort covers the response body as well as the headers, so a gateway that returns `200` and then stalls is caught too, as is one that answers a chain-defaults failure and then stalls the error body the message is read from.
93
+ - **The Solana signing format in the published types was wrong.** `SignedMessage.message` was documented as a base64-encoded message on Solana, where the value the network verifies is the hex-encoded message hash with a `0x` prefix, as it is on EVM and Tron. A caller following the type's own documentation produced a signature that could not be recovered, and the request was refused with nothing in the message pointing at the encoding. The description now matches the format that is signed and verified. Types and runtime behaviour are unchanged; only what the types say about them.
94
+ - `SenderAuthMessageScheme` documents `EVM_PERMIT2_ESCROW`. The value has always been accepted and appeared in the type's union, but the accompanying description listed only the other three, so the one scheme that pairs a gasless approval with escrow support read as undocumented.
95
+ - `SenderAuth.verifiable_credential` is marked deprecated in the published type, which it already was in the format that is signed. Credentials belong in the holder-signed `PaymentRequestEnvelope`; the inner request carries none, and its Data Integrity signature excludes this field. A caller still populating it can see that from the type now rather than only from the signing schema.
96
+
97
+ ## [2.2.0] - 2026-08-04
98
+
99
+ > **Read this before upgrading if you script `send-payment`.** Its exit codes now
100
+ > distinguish a settled payment from one still settling and one that failed, where every
101
+ > accepted submission previously exited `0`. See the first entry under Changed.
102
+ >
103
+ > One typed-API change: three fields on `PaymentResponse` are no longer optional. This makes
104
+ > reading a response simpler, not harder — see Changed.
105
+
106
+ ### Added
107
+ - `send-payment --wait` keeps checking a submitted payment until it settles or fails, instead of reporting it as still pending. `--wait-seconds <n>` sets how long (default 60). With `--wait` the JSON on stdout is printed once the wait ends and reports the payment as of the last check — so it carries the settled `status` and the `fulfillment_confirmation`, rather than the `pending` the submit returned. Without `--wait`, output is unchanged. The bound is a client-side convenience: giving up does not affect the payment, and re-submitting the same `request_id` or reading the status endpoint picks up wherever it got to. A settlement that stalls never becomes terminal on its own, so no bound can promise a terminal answer.
108
+ - `send-payment` and `payment-status` now print a one-line outcome summary to stderr saying what the payment's state means for a re-attempt: a pending payment is collected by re-submitting the **same** `request_id`, while a terminally failed one keeps its id and needs a **new** one. The JSON on stdout is unchanged.
109
+ - Documented in `docs/idempotency.md` and the README: what the `409` compares, that deadlines and the signature are exempt from it, `idempotent_replay`, how to read `status`, and that a direct caller may either poll the status endpoint or re-submit.
110
+
111
+ ### Changed
112
+ - **Behaviour change — `send-payment` exit codes.** Previously any accepted submission exited `0`. Now `0` means `completed`, `2` means `pending`, and `3` means `failed`/`cancelled`; `1` continues to mean the payment could not be submitted. Previously a still-settling payment and a terminally failed one both exited `0`, so `send-payment ... && <next step>` ran the next step for a payment that had not settled — including when re-submitting a `request_id` whose payment had already failed. Scripts that treat `0` as "submitted" should treat `0` and `2` as "submitted"; scripts that mean "settled" now get that from `0` alone. `payment-status` is unaffected: as a lookup, its exit code reports whether the lookup worked.
113
+ - `--request-id`'s help text now states the consequence of omitting it: an id is generated, which makes every bare re-run a separate payment rather than a retry.
114
+ - **`PaymentResponse.payment_id`, `.status` and `.idempotent_replay` are now required** in the typed API, matching what the gateway has always sent. They were typed optional, so TypeScript reported them as possibly `undefined` and reading `idempotent_replay` meant writing `=== true` to satisfy the compiler for a value that is always present. Existing code keeps compiling — a narrowed type only removes checks — unless it constructs a `PaymentResponse` itself, as a test fixture might, in which case all three now have to be supplied.
115
+
116
+
117
+
118
+ ### Fixed
119
+ - Corrected the idempotency documentation. The 2.1.0 note below said that reusing a `request_id` with different terms returns the original payment and silently drops the new terms. The gateway rejects it with `409` `IDEMPOTENCY_TERMS_MISMATCH`, so an integrator following the old text would neither expect nor handle that error.
120
+ - `IDEMPOTENCY_TERMS_MISMATCH`'s message described the compared terms as "source, destination, or fulfillment_amount", which had become incomplete — `max_source_amount` is compared too. It now names the categories ("accounts, assets, or amounts") rather than enumerating fields, so it stays accurate as the payment schema grows. The docs describe the comparison the same way, and point at the error's own `message` for which category differed.
121
+
8
122
  ## [2.1.0] - 2026-07-31
9
123
 
10
124
  ### Added