@anywalletkit/protocol-swap2-0x 0.0.0-stage → 0.1.1

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 (60) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +172 -2
  3. package/dist/activity.cjs +168 -0
  4. package/dist/activity.cjs.map +1 -0
  5. package/dist/activity.d.cts +18 -0
  6. package/dist/activity.d.ts +18 -0
  7. package/dist/activity.js +11 -0
  8. package/dist/activity.js.map +1 -0
  9. package/dist/chains.cjs +88 -0
  10. package/dist/chains.cjs.map +1 -0
  11. package/dist/chains.d.cts +64 -0
  12. package/dist/chains.d.ts +64 -0
  13. package/dist/chains.js +27 -0
  14. package/dist/chains.js.map +1 -0
  15. package/dist/chunk-AOJSV3QG.js +498 -0
  16. package/dist/chunk-AOJSV3QG.js.map +1 -0
  17. package/dist/chunk-F6QOUZC7.js +24 -0
  18. package/dist/chunk-F6QOUZC7.js.map +1 -0
  19. package/dist/chunk-HDMLWKPW.js +38 -0
  20. package/dist/chunk-HDMLWKPW.js.map +1 -0
  21. package/dist/chunk-MBQ2WFQW.js +207 -0
  22. package/dist/chunk-MBQ2WFQW.js.map +1 -0
  23. package/dist/chunk-MMOBCJEO.js +68 -0
  24. package/dist/chunk-MMOBCJEO.js.map +1 -0
  25. package/dist/chunk-VSYAAW22.js +323 -0
  26. package/dist/chunk-VSYAAW22.js.map +1 -0
  27. package/dist/index.cjs +1098 -0
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.cts +13 -0
  30. package/dist/index.d.ts +13 -0
  31. package/dist/index.js +102 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/protocol.cjs +879 -0
  34. package/dist/protocol.cjs.map +1 -0
  35. package/dist/protocol.d.cts +20 -0
  36. package/dist/protocol.d.ts +20 -0
  37. package/dist/protocol.js +11 -0
  38. package/dist/protocol.js.map +1 -0
  39. package/dist/provider.cjs +865 -0
  40. package/dist/provider.cjs.map +1 -0
  41. package/dist/provider.d.cts +84 -0
  42. package/dist/provider.d.ts +84 -0
  43. package/dist/provider.js +18 -0
  44. package/dist/provider.js.map +1 -0
  45. package/dist/remote.cjs +609 -0
  46. package/dist/remote.cjs.map +1 -0
  47. package/dist/remote.d.cts +93 -0
  48. package/dist/remote.d.ts +93 -0
  49. package/dist/remote.js +21 -0
  50. package/dist/remote.js.map +1 -0
  51. package/dist/settler-BpRGkBVV.d.ts +196 -0
  52. package/dist/settler-KDFcfsKv.d.cts +196 -0
  53. package/dist/settler.cjs +352 -0
  54. package/dist/settler.cjs.map +1 -0
  55. package/dist/settler.d.cts +4 -0
  56. package/dist/settler.d.ts +4 -0
  57. package/dist/settler.js +42 -0
  58. package/dist/settler.js.map +1 -0
  59. package/module.json +22 -0
  60. package/package.json +98 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # @anywalletkit/protocol-swap2-0x
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@anywalletkit/protocol-swap2-0x?label=npm)](https://www.npmjs.com/package/@anywalletkit/protocol-swap2-0x)
4
+
5
+ [0x Swap API v2](https://docs.0x.org/docs/api/swap-permit2) as a same-chain swap2 provider for Any Wallet Kit, through the Permit2 flow. Exact-input swaps on Ethereum, Base, Arbitrum, Optimism, Polygon, Avalanche and BNB Smart Chain. Written from the 0x API and the Settler contracts; it uses no 0x package.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @anywalletkit/protocol-swap2-0x @anywalletkit/core
11
+ # or: pnpm add @anywalletkit/protocol-swap2-0x @anywalletkit/core · yarn add @anywalletkit/protocol-swap2-0x @anywalletkit/core
12
+ ```
13
+
14
+ On npm: [@anywalletkit/protocol-swap2-0x](https://www.npmjs.com/package/@anywalletkit/protocol-swap2-0x), published from the [release workflow](https://github.com/ultratestbro/anywalletkit/blob/main/RELEASING.md) with provenance.
15
+
16
+ ## The API key
17
+
18
+ 0x wants a key on every request. A key cannot ship inside a mobile app or an extension, so the module has two modes:
19
+
20
+ - **Remote (apps).** Your backend runs `zeroExProvider` with the key behind the swap2 handler. The app uses `zeroExRemoteProvider`, which holds no key and re-checks every quote and every transaction on the device, as described below. A backend that is wrong or compromised cannot move the swap anywhere else.
21
+ - **Local, with a key: servers only** (a backend, scripts, an integrator's own service). `zeroExProvider({ apiKey: () => … })` or `ZeroExSwap2Protocol` talk to 0x directly. Under React Native (Hermes or JSC) building either with a key throws, pointing to the remote mode: the key would ship in the app bundle, and React Native's fetch follows redirects with the key header whatever `redirect` says.
22
+
23
+ The key is best passed as a getter, read at request time (a string is accepted too), and is sent only in the `0x-api-key` header, to an `https://` origin. Redirects are refused (`redirect: "error"`), and an answer that came through one anyway, or from another origin than `baseUrl`, is not used (`policy_refused`). It is never put in a URL, a quote, an error or a log line.
24
+
25
+ The SDK reads no environment. By convention apps and backends name the switch and the key `ZEROEX_ENABLED` (dark unless set) and `ZEROEX_API_KEY`, as the routes canary and `verify:live` here do.
26
+
27
+ ## How a swap goes
28
+
29
+ 1. `GET /swap/permit2/price` for an indicative quote, `GET /swap/permit2/quote` for a live one (`chainId`, `sellToken`, `buyToken`, `sellAmount`, `taker`, `recipient`, `slippageBps`).
30
+ 2. The account signs one EIP-712 `PermitTransferFrom` for this swap. Typed data only: the account needs `signTypedData`, and there is no raw-hash path. This comes first, so an account that cannot or will not sign costs no approval.
31
+ 3. If the token's allowance to Permit2 is below the input, the engine approves **Permit2** for exactly the input (USDT is reset first on mainnet; the approval is revoked if the swap does not go out). A standing allowance that covers the input is left as it is; a smaller one is replaced and, if the swap does not go out, set to 0. No allowance is ever given to a 0x contract.
32
+ 4. The signature is appended to the calldata as 0x specifies (`data ++ uint256(length) ++ signature`), the signed call is estimated from the account, and then sent to the Settler with the account's own gas estimate (the quoted gas limit is not used).
33
+
34
+ Selling the native coin needs no approval and no signature: the call carries the amount as value. It too is dry-run from the account right before the broadcast and sent with the account's own gas estimate, never the quoted limit (the provider declares `ownGasEstimate`). A dry run that reverts refuses the swap (`simulation_failed`); one the account's RPC does not answer is asked once more and then refused as `upstream_unavailable`.
35
+
36
+ ## What is checked before anything is signed
37
+
38
+ **The Settler comes from the chain, not from the API.** 0x replaces its Settler contracts regularly. The module reads the Settler in force (`ownerOf(2)`) and the one it replaced (`prev(2)`) from 0x's on-chain registry `0x00000000000004533Fe15556B1E086BB1A72cEae` through your RPC, and accepts a transaction only when its target is one of the two. The answer is held to bounds the RPC cannot move:
39
+ - it must be an address the registry deploys Settlers to — `CREATE3(registry, feature 2, this chain, nonce)`, computed on the device (`zeroExSettlerNonce`) — so an RPC cannot name an arbitrary contract or account;
40
+ - that deployment must sit inside the window the chain table pins: no older than the previous Settler live when the table was pinned (`previousLiveNonce`; an older, replaced Settler is refused) and no newer than the one in force then (`newestLiveNonce`; Base: 22 and 21 on 2026-11-15) plus, for a token sale, a margin of two (`ZEROEX_SETTLER_NONCE_MARGIN`);
41
+ - a **native-coin sale goes only to the pinned current or previous Settler**, never into the margin: its value is sent to the address as it is, and whether a deployment inside the margin exists is only the RPC's word. A token sale may use the margin, since its permit can be spent only with the account itself as the caller;
42
+ - a newer deployment is refused with what to do (update the package, or raise the pins once the deployment is checked) — native sales from the day 0x deploys it, token sales once it is past the margin. The watch job reports every new deployment (`ownerOf(2)` per chain in `watch.json`) and `verify:live` fails as long as the registry names anything but the pinned pair, so the pins are raised promptly;
43
+ - there must be a contract at that address (`eth_getCode`, through the same RPC): a deployment that does not exist yet would strand what is sent to it.
44
+
45
+ A live quote therefore needs `rpcUrls` for its chain. The read is cached for five minutes (`settlerMaxAgeMs`) and repeated right before the broadcast — in remote mode on the device, before the backend's own preflight is asked — so a Settler paused, replaced or removed while the review screen is open is refused with nothing sent. A live quote in remote mode is held to exactly the set its own request read, however long the backend takes, and a native sale's quote stays valid for at most two minutes (`ZEROEX_MAX_NATIVE_QUOTE_SECONDS`; a token sale's is bounded by its permit).
46
+
47
+ **The Permit2 payload is rebuilt locally.** The API's typed data is read strictly and compared with the request; what the account signs is rebuilt from local constants:
48
+ - domain: `Permit2`, the chain of the swap, the canonical Permit2 address;
49
+ - type: `PermitTransferFrom` and nothing else (no witness, no `PermitSingle`);
50
+ - token: the token being sold; amount: exactly the input, not more;
51
+ - spender: the Settler the transaction calls, which is one from the registry;
52
+ - deadline: in the future and no further than ten minutes away (0x signs five minutes ahead).
53
+
54
+ **The transaction is decoded.** The calldata must be the Settler's `execute(AllowedSlippage, bytes[], bytes32)`:
55
+ - `to` is a registry Settler inside the pinned window (for a native sale, one of the two pinned); the chain id matches; the value is zero for a token sale and exactly the input for a native sale;
56
+ - the slippage tuple pays **the recipient of this swap**, in **the token asked for**, at least **the quoted minimum** — and the quoted minimum is within the requested slippage of the quoted output and not below the caller's floor;
57
+ - for a token sale, the first action is one of the Settler's Permit2 payments, it pulls the sold token for the input amount with the same nonce and deadline as the signed payload, and the place for the signature is the very end of the calldata;
58
+ - for a native sale, the first action is `NATIVE_CHECK`. The Settler spends a Permit2 signature only in its first action and pulls from the caller, so this keeps an earlier, unspent permit of the account (one whose swap reverted) from being spent inside what looks like a plain native sale;
59
+ - 0x names canonical Permit2 as `allowanceTarget` on every answer, native sales included; anything else is refused, and a native sale's transaction carries no allowance target at all;
60
+ - the gas limit is bounded, and the allowance target is the canonical Permit2.
61
+
62
+ Anything else is refused, with the reason, before an approval or a signature.
63
+
64
+ **What this gives.** The Settler checks the slippage tuple itself at the end of `execute`: the swap reverts, or the recipient receives at least the minimum of the buy token. The permit can move only the input amount of the sold token, only to that Settler, only once, and the only Permit2 payment the call can make is that permit. So the most a wrong answer can cost is the input of this swap (and gas), and only by reverting or by filling at the minimum.
65
+
66
+ One exception to "at least the minimum": the Settler measures its own balance of the buy token before the last transfer, so a buy token that takes a fee on transfer arrives short of it. Quotes for tokens 0x flags as taxed (`tokenMetadata.buyToken`) are refused; a tax 0x does not report (or reports as null) is not caught here.
67
+
68
+ **What is still taken from the API.**
69
+ - The route and the price above the minimum. A better fill than the minimum is not guaranteed by any check here: 0x's routes end in a `POSITIVE_SLIPPAGE` action that keeps the surplus above the quoted amount for 0x (it is in the calldata), and a route could set that line at the minimum.
70
+ - The fee amounts and the gas estimate it reports.
71
+ - The actions after the first one (the route itself), the recipient argument inside the first action (where the Settler sends the pulled tokens on its way through the route) and `zidAndAffiliate`. These decide how the swap is filled, not what the recipient must receive.
72
+ - The device trusts its own RPC for the registry read, within the bounds above: the RPC can name only a genuine 0x deployment inside the pinned window, and within the margin (token sales only) it is trusted to say truthfully whether a contract is there.
73
+
74
+ In remote mode the same checks run on the device (`zeroExPins` → `verifyQuote`, `verifyBuild`, pinned call targets and spender, and the fresh registry read in `preflightDeposit`), so the list above is what the app trusts in its backend and in 0x together. Keep the app's `rpcUrls` out of the backend's hands where you can: the registry read is what the device trusts for "which contract is the Settler", and the CREATE3, pin and code checks bound it to deployed 0x Settlers — for native value, to the two pinned ones.
75
+
76
+ **Signing policies.** The engine's permit names the Settler as spender, and the Settler rotates. A kit allowlist must list Permit2, the token and the Settlers in force, and wallet-evm's `describeTypedData` should know them as `knownSpenders` rather than a fixed address. `zeroExKnownSpenders(provider, chainId)` gives that map (`{ [settler]: "0x Settler" }`) from the resolver the provider itself reads through (`provider.settlerResolver`):
77
+
78
+ ```ts
79
+ const zeroex = zeroExRemoteProvider({ baseUrl, rpcUrls })
80
+ const knownSpenders = await zeroExKnownSpenders(zeroex, 8453)
81
+ describeTypedData(typed, { chainId: 8453, account, knownSpenders })
82
+ // kit allowlist: [PERMIT2_ADDRESS, token, ...Object.keys(knownSpenders)]
83
+ ```
84
+
85
+ It is empty when the registry cannot be read, so the permit is then described as a grant to an unknown spender. `extension-kit` shows the permit on the swap sheet and pre-approves exactly it and the signed call.
86
+
87
+ ## Fees
88
+
89
+ 0x reports its fees in the answer, and a quote whose fees cannot be read is refused rather than shown as free.
90
+
91
+ | In the 0x answer | In the quote |
92
+ |---|---|
93
+ | `fees.zeroExFee` — 0x's own fee, taken on-chain out of the trade; `buyAmount` is already net of it | `protocol`, `included: true` |
94
+ | `fees.integratorFee` / `integratorFees` | none is requested; an answer that carries one is refused |
95
+ | `fees.gasFee` (gasless trades only) | `network`, `included: true` |
96
+ | `totalNetworkFee`, or `gas × gasPrice` | `network`, `included: false` (paid by the account in the native coin) |
97
+
98
+ 0x also keeps positive slippage (the part of a fill above the quoted amount): it is not a line in the answer's fees but the calldata's `POSITIVE_SLIPPAGE` action, which sends the surplus above the quoted amount to 0x. The quoted amount and the minimum are what the checks hold the swap to.
99
+
100
+ ## Configure
101
+
102
+ ```ts
103
+ import { zeroExProvider } from '@anywalletkit/protocol-swap2-0x'
104
+
105
+ // on your server only: under React Native a provider with a key throws
106
+ const zeroex = zeroExProvider({
107
+ apiKey: () => process.env.ZEROEX_API_KEY,
108
+ rpcUrls: { 8453: ['https://base.example/rpc'] }, // needed for live quotes: the Settler registry is read here
109
+ })
110
+ ```
111
+
112
+ ```ts
113
+ import { zeroExRemoteProvider } from '@anywalletkit/protocol-swap2-0x/remote'
114
+
115
+ // in the app: no key, the checks stay on the device
116
+ const zeroex = zeroExRemoteProvider({
117
+ baseUrl: 'https://your-backend.example/api/swap2',
118
+ rpcUrls: { 8453: ['https://base.example/rpc'] },
119
+ })
120
+ ```
121
+
122
+ | Option | Default | Meaning |
123
+ |---|---|---|
124
+ | `enabled` | `true` | `false` takes the provider out of the auction (wire it to `ZEROEX_ENABLED`). |
125
+ | `apiKey` | none | The 0x key (local mode, servers only — refused under React Native): a getter (preferred) or a string. Without one the provider serves no route. |
126
+ | `baseUrl` | `https://api.0x.org` | API origin (local mode), or your swap2 backend (remote mode). `https` only. |
127
+ | `rpcUrls` | none | `{ chainId: [url…] }` — registry reads and receipts. Required for live quotes. |
128
+ | `chains` | the seven chains above | Chain table: `{ chainId: { name, registry, newestLiveNonce, previousLiveNonce, wrappedNative } }` merged over the defaults; `null` removes a chain. `newestLiveNonce` and `previousLiveNonce` (required) are the Settler deployments the registry names as current and previous when you pin the entry (`pnpm verify:live` prints both): native sales go only to these two, token sales also to the next two deployments once they hold code, nothing older than the previous one. |
129
+ | `defaultSlippageBps` | `50` | Used when the caller passes none. Keep it the same on the backend and in the app. |
130
+ | `quoteTtlMs` | `45000` | How long a quote is offered; never past the Permit2 deadline, and a native sale's never past two minutes. |
131
+ | `timeoutMs` | `10000` | Per API request. |
132
+ | `excludedSources` | none | Liquidity sources 0x must not route through, by their names in 0x's `/sources` list. A name 0x does not know refuses the quote (it would not be excluded). |
133
+ | `settlerMaxAgeMs` | `300000` (5 minutes) | How long a registry read is reused. |
134
+
135
+ `ZeroExSwap2Protocol` (`/protocol`) is the same provider as a stand-alone swap2 protocol over one account.
136
+
137
+ ## Not supported
138
+
139
+ - **AllowanceHolder.** 0x's docs now recommend the AllowanceHolder flow (an allowance to the AllowanceHolder contract, one transaction, no signature) for most integrations. This module implements the Permit2 flow: the allowance stays with Permit2 and each swap is authorized by its own exact, expiring signature. AllowanceHolder is pinned only so it can be told apart and refused as an allowance target.
140
+ - The Gasless API, cross-chain swaps, exact-output swaps.
141
+ - Wrapping and unwrapping (native ↔ wrapped native): 0x answers those with a call to the token, not to a Settler.
142
+ - Buy tokens that tax transfers, a first action that is not a known Permit2 payment (including RFQ fills as the first action), and the older calldata layout with the signature placed inside the action. They are refused, not attempted.
143
+
144
+ ## Refusals
145
+
146
+ Every refusal reads `zeroex: <what was found>` and reaches `onRefusal(text, info)` with a `Swap2RefusalReason` in `info` (thrown errors carry it for `refusalOf`; `zeroExPins().reasonOf` classifies the remote verifiers' texts). A malformed request and the caller's own abort stay unclassified.
147
+
148
+ | What was found | Reason |
149
+ |---|---|
150
+ | HTTP 429 | `rate_limited` (with `retryAfterMs` from Retry-After) |
151
+ | HTTP 401 / 403, no key configured | `key_rejected` |
152
+ | 5xx, an unreachable API, an answer that cannot be read (amounts, fees, transaction) | `upstream_unavailable` |
153
+ | no liquidity | `insufficient_liquidity` |
154
+ | 0x's own error names | the closest reason (`TOKEN_NOT_SUPPORTED` → `unsupported_pair`, `INPUT_INVALID` → `no_route`, …) |
155
+ | a chain or pair 0x does not serve, wrapping, a buy token that taxes transfers | `unsupported_pair` |
156
+ | a paused registry | `chain_halted` |
157
+ | another Settler; a Settler outside the pinned window, without code, or — for a native sale — not one of the two pinned; another Permit2 spender, domain or allowance target | `vault_mismatch` |
158
+ | another recipient | `recipient_mismatch` |
159
+ | what the swap is held to deliver: a transaction value other than the input (a native sale) or zero (a token sale), the slippage check's buy token or minimum, a quoted minimum outside the requested slippage or below the caller's floor, a Permit2 payload for another token or amount | `price_check_failed` |
160
+ | what the answer itself says: other tokens or another sell amount than the ones asked for, a first action that pulls another token, amount or permit; an integrator fee nobody asked for, an excluded source 0x does not know, an answer that came through a redirect, a native-sale quote valid for more than two minutes, and anything else the checks refuse | `policy_refused` |
161
+ | a passed deadline, a Permit2 deadline too close to sign against | `quote_expired` |
162
+
163
+ ## Checks
164
+
165
+ ```sh
166
+ pnpm test # unit, probes, and every recorded real 0x answer (fixtures/quotes)
167
+ ZEROEX_LIVE=1 ZEROEX_API_KEY=… pnpm test # also live quotes from api.0x.org (read-only)
168
+ pnpm verify:live # registry, Settlers (code, the pinned current / previous pair), Permit2 on all seven chains; with ZEROEX_API_KEY also live corridors
169
+ ```
170
+
171
+ ## License
172
+
173
+ Apache-2.0
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/activity.ts
21
+ var activity_exports = {};
22
+ __export(activity_exports, {
23
+ ZEROEX_MODULE: () => ZEROEX_MODULE,
24
+ describeZeroExActivity: () => describeZeroExActivity
25
+ });
26
+ module.exports = __toCommonJS(activity_exports);
27
+ var import_activity = require("@anywalletkit/protocol-swap2-core/activity");
28
+
29
+ // src/chains.ts
30
+ var import_util = require("@anywalletkit/protocol-swap2-core/util");
31
+ var ZEROEX_SETTLER_REGISTRY = "0x00000000000004533Fe15556B1E086BB1A72cEae";
32
+ var ZEROEX_TAKER_FEATURE = 2;
33
+ var ZEROEX_SETTLER_NONCE_MARGIN = 2;
34
+ var ZEROEX_SETTLER_MAX_NONCE = 1024;
35
+ var chain = (name, wrappedNative, newestLiveNonce, previousLiveNonce) => Object.freeze({ name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative });
36
+ var ZEROEX_CHAINS = Object.freeze({
37
+ 1: chain("Ethereum", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", 21, 20),
38
+ 10: chain("Optimism", "0x4200000000000000000000000000000000000006", 21, 20),
39
+ 56: chain("BNB Smart Chain", "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", 23, 22),
40
+ 137: chain("Polygon", "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", 20, 19),
41
+ 8453: chain("Base", "0x4200000000000000000000000000000000000006", 22, 21),
42
+ 42161: chain("Arbitrum", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", 20, 19),
43
+ 43114: chain("Avalanche", "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", 20, 19)
44
+ });
45
+ function zeroExChainId(caip2) {
46
+ return typeof caip2 === "string" && /^eip155:[1-9][0-9]{0,15}$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
47
+ }
48
+ function zeroExChain(chains, chainId) {
49
+ return Number.isSafeInteger(chainId) && Object.prototype.hasOwnProperty.call(chains, chainId) ? chains[chainId] : void 0;
50
+ }
51
+
52
+ // src/settler.ts
53
+ var import_viem = require("viem");
54
+ var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
55
+ var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
56
+ var SETTLER_EXECUTE_SELECTOR = "0x1fff991f";
57
+ var PERMIT = "((address,uint256),uint256,uint256)";
58
+ var SETTLER_PERMIT_ACTIONS = Object.freeze({
59
+ "0xc1fb425e": Object.freeze({ name: "TRANSFER_FROM", signature: `TRANSFER_FROM(address,${PERMIT},bytes)`, sigWord: 5 }),
60
+ "0x3036d6a6": Object.freeze({ name: "UNISWAPV3_VIP", signature: `UNISWAPV3_VIP(address,${PERMIT},bytes,bytes,uint256)`, sigWord: 6 }),
61
+ "0x6a92dacb": Object.freeze({ name: "UNISWAPV4_VIP", signature: `UNISWAPV4_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
62
+ "0x441d2492": Object.freeze({ name: "PANCAKE_INFINITY_VIP", signature: `PANCAKE_INFINITY_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
63
+ "0x4150c86c": Object.freeze({ name: "BALANCERV3_VIP", signature: `BALANCERV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
64
+ "0x10cd6343": Object.freeze({ name: "EKUBOV3_VIP", signature: `EKUBOV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
65
+ "0x0bcce50f": Object.freeze({ name: "CURVE_TRICRYPTO_VIP", signature: `CURVE_TRICRYPTO_VIP(address,${PERMIT},uint80,bytes,uint256)`, sigWord: 6 })
66
+ });
67
+ var ZeroExTransactionError = class extends Error {
68
+ constructor(why, reason) {
69
+ super(`zeroex: ${why}`);
70
+ this.name = "ZeroExTransactionError";
71
+ if (reason) (0, import_errors.withReason)(this, reason);
72
+ }
73
+ };
74
+ var refuse = (why, reason) => new ZeroExTransactionError(why, reason);
75
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
76
+ var ZEROEX_SETTLER_SHIM_INIT_HASH = "0x3bf3f97f0be1e2c00023033eefeb4fc062ac552ff36778b17060d90b6764902f";
77
+ var ZEROEX_SETTLER_LOOKAHEAD = 16;
78
+ var tokenCeiling = (chain2) => chain2.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN;
79
+ function zeroExSettlerAddress(chainId, nonce, registry = ZEROEX_SETTLER_REGISTRY) {
80
+ if (!Number.isSafeInteger(chainId) || chainId <= 0 || !Number.isSafeInteger(nonce) || nonce <= 0) throw new Error("zeroex: a Settler address needs a positive chain id and nonce");
81
+ const salt = (0, import_viem.pad)((0, import_viem.numberToHex)(BigInt(ZEROEX_TAKER_FEATURE) << 128n | BigInt(chainId) << 64n | BigInt(nonce)), { size: 32 });
82
+ const shim = (0, import_viem.getContractAddress)({ opcode: "CREATE2", from: registry, salt, bytecodeHash: ZEROEX_SETTLER_SHIM_INIT_HASH });
83
+ return (0, import_viem.getContractAddress)({ opcode: "CREATE", from: shim, nonce: 1n });
84
+ }
85
+ var derived = /* @__PURE__ */ new Map();
86
+ function zeroExSettlerNonce(chainId, address, registry = ZEROEX_SETTLER_REGISTRY, maxNonce) {
87
+ if (typeof address !== "string" || !ADDRESS.test(address) || !Number.isSafeInteger(chainId) || chainId <= 0 || !ADDRESS.test(registry)) return null;
88
+ const pinned = zeroExChain(ZEROEX_CHAINS, chainId);
89
+ const bound = Math.min(maxNonce ?? (pinned ? tokenCeiling(pinned) : 0), ZEROEX_SETTLER_MAX_NONCE + ZEROEX_SETTLER_NONCE_MARGIN + ZEROEX_SETTLER_LOOKAHEAD);
90
+ if (!Number.isSafeInteger(bound) || bound < 1) return null;
91
+ const key = `${registry.toLowerCase()}:${chainId}`;
92
+ let list = derived.get(key);
93
+ if (!list) derived.set(key, list = []);
94
+ const want = address.toLowerCase();
95
+ const hit = list.indexOf(want);
96
+ if (hit >= 0) return hit < bound ? hit + 1 : null;
97
+ while (list.length < bound) {
98
+ const next = zeroExSettlerAddress(chainId, list.length + 1, registry).toLowerCase();
99
+ list.push(next);
100
+ if (next === want) return list.length;
101
+ }
102
+ return null;
103
+ }
104
+ var DEFAULT_SETTLER_MAX_AGE_MS = 5 * 6e4;
105
+ var MAX_CALLDATA_BYTES = 65536;
106
+ var MAX_ACTIONS = 256;
107
+ var ACTIONS_OFFSET = 160;
108
+ function decodeSettlerExecute(data) {
109
+ if (typeof data !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data)) throw refuse("the transaction data is not hex bytes", "policy_refused");
110
+ if (data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw refuse("the transaction data is larger than any 0x swap", "policy_refused");
111
+ if (data.length < 10 || data.slice(0, 10).toLowerCase() !== SETTLER_EXECUTE_SELECTOR) throw refuse("the transaction does not call Settler.execute", "policy_refused");
112
+ const body = data.slice(10).toLowerCase();
113
+ const bodyLength = body.length / 2;
114
+ const word = (offset) => {
115
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset + 32 > bodyLength) throw refuse("the Settler call is cut short", "policy_refused");
116
+ return body.slice(offset * 2, offset * 2 + 64);
117
+ };
118
+ const address = (offset, what) => {
119
+ const w = word(offset);
120
+ if (!/^0{24}/.test(w)) throw refuse(`the Settler call's ${what} is not an address`, "policy_refused");
121
+ return (0, import_viem.getAddress)(`0x${w.slice(24)}`);
122
+ };
123
+ const small = (offset, what) => {
124
+ const w = word(offset);
125
+ if (!/^0{56}/.test(w)) throw refuse(`the Settler call's ${what} is out of range`, "policy_refused");
126
+ return parseInt(w.slice(56), 16);
127
+ };
128
+ const recipient = address(0, "recipient");
129
+ const buyToken = address(32, "buy token");
130
+ const minAmountOut = BigInt(`0x${word(64)}`);
131
+ if (small(96, "action array offset") !== ACTIONS_OFFSET) throw refuse("the Settler call does not place its actions where the ABI does", "policy_refused");
132
+ const zidAndAffiliate = `0x${word(128)}`;
133
+ const count = small(ACTIONS_OFFSET, "action count");
134
+ if (count < 1 || count > MAX_ACTIONS) throw refuse(`the Settler call carries ${count} actions`, "policy_refused");
135
+ const table = ACTIONS_OFFSET + 32;
136
+ const actions = [];
137
+ for (let i = 0; i < count; i++) {
138
+ const offset = small(table + 32 * i, "action offset");
139
+ const at = table + offset;
140
+ if (offset < 32 * count || at + 36 > bodyLength) throw refuse(`action ${i} of the Settler call lies outside the data`, "policy_refused");
141
+ const declaredLength = small(at, "action length");
142
+ if (declaredLength < 4) throw refuse(`action ${i} of the Settler call has no selector`, "policy_refused");
143
+ if (i > 0 && at + 32 + declaredLength > bodyLength) throw refuse(`action ${i} of the Settler call runs past the data`, "policy_refused");
144
+ actions.push(Object.freeze({ selector: `0x${body.slice((at + 32) * 2, (at + 36) * 2)}`, argsStart: at + 36, declaredLength }));
145
+ }
146
+ return Object.freeze({ recipient, buyToken, minAmountOut, zidAndAffiliate, actions: Object.freeze(actions), bodyLength, word });
147
+ }
148
+
149
+ // src/activity.ts
150
+ var ZEROEX_MODULE = "@anywalletkit/protocol-swap2-0x";
151
+ function describeZeroExActivity(tx, ctx) {
152
+ const chainId = zeroExChainId(tx.chain);
153
+ const chain2 = zeroExChain(ZEROEX_CHAINS, chainId);
154
+ if (!chain2) return null;
155
+ if ((0, import_activity.callSelector)(tx) !== SETTLER_EXECUTE_SELECTOR) return null;
156
+ const target = tx.call?.to ?? tx.to;
157
+ if (typeof target !== "string" || zeroExSettlerNonce(chainId, target, chain2.registry, chain2.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN) === null) return null;
158
+ const data = tx.call?.data;
159
+ if (typeof data === "string" && data.length > 10) {
160
+ try {
161
+ decodeSettlerExecute(data);
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+ return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: ZEROEX_MODULE, subtitle: `0x \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "swap" });
167
+ }
168
+ //# sourceMappingURL=activity.cjs.map