@anywalletkit/protocol-swap2-core 0.0.0-stage → 0.3.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.
- package/LICENSE +202 -0
- package/README.md +18 -2
- package/dist/activity.cjs +137 -0
- package/dist/activity.cjs.map +1 -0
- package/dist/activity.d.cts +66 -0
- package/dist/activity.d.ts +66 -0
- package/dist/activity.js +25 -0
- package/dist/activity.js.map +1 -0
- package/dist/chunk-4H2JVYXT.js +82 -0
- package/dist/chunk-4H2JVYXT.js.map +1 -0
- package/dist/chunk-55J6XMHW.js +1 -0
- package/dist/chunk-55J6XMHW.js.map +1 -0
- package/dist/chunk-62XJXMGD.js +1016 -0
- package/dist/chunk-62XJXMGD.js.map +1 -0
- package/dist/chunk-IVR3SREQ.js +72 -0
- package/dist/chunk-IVR3SREQ.js.map +1 -0
- package/dist/chunk-J4WXUNK2.js +121 -0
- package/dist/chunk-J4WXUNK2.js.map +1 -0
- package/dist/chunk-KIAQXIBG.js +43 -0
- package/dist/chunk-KIAQXIBG.js.map +1 -0
- package/dist/chunk-KNBYYSYS.js +65 -0
- package/dist/chunk-KNBYYSYS.js.map +1 -0
- package/dist/chunk-SKV5BVXK.js +43 -0
- package/dist/chunk-SKV5BVXK.js.map +1 -0
- package/dist/chunk-VNVBGY7U.js +40 -0
- package/dist/chunk-VNVBGY7U.js.map +1 -0
- package/dist/errors.cjs +92 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +49 -0
- package/dist/errors.d.ts +49 -0
- package/dist/errors.js +27 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.cjs +1447 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +94 -0
- package/dist/index.js.map +1 -0
- package/dist/remote.cjs +121 -0
- package/dist/remote.cjs.map +1 -0
- package/dist/remote.d.cts +54 -0
- package/dist/remote.d.ts +54 -0
- package/dist/remote.js +8 -0
- package/dist/remote.js.map +1 -0
- package/dist/slippage.cjs +60 -0
- package/dist/slippage.cjs.map +1 -0
- package/dist/slippage.d.cts +55 -0
- package/dist/slippage.d.ts +55 -0
- package/dist/slippage.js +9 -0
- package/dist/slippage.js.map +1 -0
- package/dist/swap2/base.cjs +1079 -0
- package/dist/swap2/base.cjs.map +1 -0
- package/dist/swap2/base.d.cts +264 -0
- package/dist/swap2/base.d.ts +264 -0
- package/dist/swap2/base.js +22 -0
- package/dist/swap2/base.js.map +1 -0
- package/dist/swap2/single.cjs +1167 -0
- package/dist/swap2/single.cjs.map +1 -0
- package/dist/swap2/single.d.cts +20 -0
- package/dist/swap2/single.d.ts +20 -0
- package/dist/swap2/single.js +10 -0
- package/dist/swap2/single.js.map +1 -0
- package/dist/types.cjs +19 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +232 -0
- package/dist/types.d.ts +232 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/util.cjs +63 -0
- package/dist/util.cjs.map +1 -0
- package/dist/util.d.cts +23 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.js +17 -0
- package/dist/util.js.map +1 -0
- package/dist/validate.cjs +63 -0
- package/dist/validate.cjs.map +1 -0
- package/dist/validate.d.cts +7 -0
- package/dist/validate.d.ts +7 -0
- package/dist/validate.js +7 -0
- package/dist/validate.js.map +1 -0
- package/package.json +99 -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,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @anywalletkit/protocol-swap2-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The swap2 engine: one interface for swaps and bridges ("swap2"), and the execution safety every swap2 provider package relies on.
|
|
4
|
+
|
|
5
|
+
- **`BaseSwap2Protocol` / `SingleProviderSwap2`** — a `Swap2Protocol` (from `@anywalletkit/core`) over a provider. It quotes, binds the execution to the quote, runs approvals, sends, and resumes status by id (`getSwap2Status`, `claimSwap2` for two-phase routes).
|
|
6
|
+
- **Safety checks.** Quote validation, a minimum-output floor, fee caps, a review gate before signing, and refusals that name their reason. Status ids look like `awk1.<provider>.<intent>[.<hash>]` (`SWAP2_ID_PREFIX`).
|
|
7
|
+
- **`remoteProvider`** — runs a provider on your server (API keys, shared state) while the app keeps the keys and signs.
|
|
8
|
+
- **Errors** — `Swap2Error` and its subclasses (quote, validation, execution, fee limit, status…).
|
|
9
|
+
- **Activity helpers** — what `describeActivity` implementations share.
|
|
10
|
+
|
|
11
|
+
Providers live in their own packages: `@anywalletkit/protocol-swap2-near-intents`, `-lifi`, `-thorchain`, `-omniston`, `-cctp`, `-usdt0`, `-chainflip`, `-jupiter`, `-uniswap`, `-balancer`, `-wrap`. `@anywalletkit/protocol-swap2-router` auctions several of them.
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pnpm add @anywalletkit/protocol-swap2-core
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Docs: [Swaps](https://docs.anywallet.tech/guides/swaps/)
|
|
18
|
+
|
|
19
|
+
Apache-2.0
|
|
@@ -0,0 +1,137 @@
|
|
|
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
|
+
assetLabel: () => assetLabel,
|
|
24
|
+
assetMetaFor: () => assetMetaFor,
|
|
25
|
+
callSelector: () => callSelector,
|
|
26
|
+
calledContract: () => calledContract,
|
|
27
|
+
callsContract: () => callsContract,
|
|
28
|
+
chainLabel: () => chainLabel,
|
|
29
|
+
describeSwapLike: () => describeSwapLike,
|
|
30
|
+
matchesCall: () => matchesCall,
|
|
31
|
+
ownerAssets: () => ownerAssets,
|
|
32
|
+
shortAddress: () => shortAddress
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(activity_exports);
|
|
35
|
+
var import_core = require("@anywalletkit/core");
|
|
36
|
+
var import_swap2_assets = require("@anywalletkit/swap2-assets");
|
|
37
|
+
function calledContract(tx) {
|
|
38
|
+
const to = tx.call?.to ?? tx.to;
|
|
39
|
+
if (!to) return null;
|
|
40
|
+
return to.startsWith("0x") ? to.toLowerCase() : to;
|
|
41
|
+
}
|
|
42
|
+
function callSelector(tx) {
|
|
43
|
+
const explicit = tx.call?.selector;
|
|
44
|
+
if (explicit && /^0x[0-9a-fA-F]{8}$/.test(explicit)) return explicit.toLowerCase();
|
|
45
|
+
const data = tx.call?.data;
|
|
46
|
+
if (data && /^0x[0-9a-fA-F]{8}/.test(data)) return data.slice(0, 10).toLowerCase();
|
|
47
|
+
return void 0;
|
|
48
|
+
}
|
|
49
|
+
function callsContract(tx, contract) {
|
|
50
|
+
const to = calledContract(tx);
|
|
51
|
+
if (!to) return false;
|
|
52
|
+
return to.startsWith("0x") ? to === contract.toLowerCase() : to === contract;
|
|
53
|
+
}
|
|
54
|
+
function matchesCall(tx, contracts, selectors) {
|
|
55
|
+
const to = calledContract(tx);
|
|
56
|
+
if (!to) return false;
|
|
57
|
+
let hit = false;
|
|
58
|
+
for (const c of contracts) {
|
|
59
|
+
if ((c.startsWith("0x") ? c.toLowerCase() : c) === to) {
|
|
60
|
+
hit = true;
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (!hit) return false;
|
|
65
|
+
if (!selectors) return true;
|
|
66
|
+
const want = /* @__PURE__ */ new Set();
|
|
67
|
+
for (const s of selectors) want.add(s.toLowerCase());
|
|
68
|
+
if (want.size === 0) return true;
|
|
69
|
+
const sel = callSelector(tx);
|
|
70
|
+
return sel !== void 0 && want.has(sel);
|
|
71
|
+
}
|
|
72
|
+
function chainLabel(caip2) {
|
|
73
|
+
return (0, import_swap2_assets.ccChain)(caip2)?.label ?? caip2;
|
|
74
|
+
}
|
|
75
|
+
function shortAddress(a) {
|
|
76
|
+
return a.length > 14 ? `${a.slice(0, 6)}\u2026${a.slice(-4)}` : a;
|
|
77
|
+
}
|
|
78
|
+
function assetMetaFor(tx) {
|
|
79
|
+
const fromTransfers = /* @__PURE__ */ new Map();
|
|
80
|
+
for (const t of tx.transfers) {
|
|
81
|
+
const key = t.token === null ? null : t.token.startsWith("0x") ? t.token.toLowerCase() : t.token;
|
|
82
|
+
if (fromTransfers.has(key)) continue;
|
|
83
|
+
const meta = {};
|
|
84
|
+
if (t.symbol !== void 0) meta.symbol = t.symbol;
|
|
85
|
+
if (t.decimals !== void 0) meta.decimals = t.decimals;
|
|
86
|
+
if (meta.symbol !== void 0 || meta.decimals !== void 0) fromTransfers.set(key, meta);
|
|
87
|
+
}
|
|
88
|
+
return (token) => {
|
|
89
|
+
const key = token === null ? null : token.startsWith("0x") ? token.toLowerCase() : token;
|
|
90
|
+
const known = fromTransfers.get(key);
|
|
91
|
+
if (known?.symbol !== void 0 && known.decimals !== void 0) return known;
|
|
92
|
+
const cat = (0, import_swap2_assets.ccAssetByToken)(tx.chain, token ?? "");
|
|
93
|
+
if (!cat) return known;
|
|
94
|
+
const meta = { symbol: known?.symbol ?? cat.symbol, decimals: known?.decimals ?? cat.decimals };
|
|
95
|
+
return meta;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function assetLabel(tx, a) {
|
|
99
|
+
if (a.symbol) return a.symbol;
|
|
100
|
+
if (a.token === null) return (0, import_swap2_assets.ccAssetByToken)(tx.chain, "")?.symbol ?? "native";
|
|
101
|
+
return shortAddress(a.token);
|
|
102
|
+
}
|
|
103
|
+
function ownerAssets(tx, ctx) {
|
|
104
|
+
return (0, import_core.splitNet)((0, import_core.netTransfers)(tx, ctx.own), assetMetaFor(tx));
|
|
105
|
+
}
|
|
106
|
+
function lead(tx, assets) {
|
|
107
|
+
const a = assets.find((x) => x.symbol) ?? assets[0];
|
|
108
|
+
return a ? assetLabel(tx, a) : void 0;
|
|
109
|
+
}
|
|
110
|
+
function describeSwapLike(tx, ctx, o) {
|
|
111
|
+
const { assetsIn, assetsOut } = ownerAssets(tx, ctx);
|
|
112
|
+
const inLabel = lead(tx, assetsIn);
|
|
113
|
+
const outLabel = lead(tx, assetsOut);
|
|
114
|
+
let kind;
|
|
115
|
+
if (o.kind === "auto") kind = assetsIn.length > 0 && assetsOut.length > 0 ? "swap" : "bridge";
|
|
116
|
+
else kind = o.kind;
|
|
117
|
+
let title = o.title;
|
|
118
|
+
if (title === void 0) {
|
|
119
|
+
const received = inLabel ? `Received ${inLabel}${o.inSuffix ? ` ${o.inSuffix}` : ""}` : void 0;
|
|
120
|
+
if (kind === "bridge") {
|
|
121
|
+
if (outLabel) title = `${o.outVerb ?? "Bridged"} ${outLabel}`;
|
|
122
|
+
else if (received) title = received;
|
|
123
|
+
} else if (outLabel && inLabel) title = `Swapped ${outLabel} \u2192 ${inLabel}`;
|
|
124
|
+
else if (outLabel) title = `${o.outVerb ?? "Swapped"} ${outLabel}`;
|
|
125
|
+
else if (received) title = received;
|
|
126
|
+
if (title === void 0) {
|
|
127
|
+
if (tx.status === "failed") title = `Failed ${kind}`;
|
|
128
|
+
else return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const counterparty = o.counterparty ?? tx.call?.to ?? tx.to ?? void 0;
|
|
132
|
+
const extra = { protocol: o.protocol, assetsIn, assetsOut };
|
|
133
|
+
if (o.subtitle !== void 0) extra.subtitle = o.subtitle;
|
|
134
|
+
if (counterparty !== void 0) extra.counterparty = counterparty;
|
|
135
|
+
return (0, import_core.activityBase)(tx, kind, title, extra);
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=activity.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/activity.ts"],"sourcesContent":["/**\n * Shared `describeActivity` plumbing for the swap2 provider modules.\n *\n * A provider recognizes one of its own transactions offline (contract called +\n * 4-byte selector, or a known counterparty on non-EVM chains) and this file\n * turns the chain-normalized `ChainTx` into the wallet-facing `ActivityItem`:\n * net asset movement for the owner's addresses, symbols / decimals from the\n * transfers themselves or the swap2-assets catalog, and a \"Swapped X → Y\" /\n * \"Bridged X\" / \"Received X\" title. Pure and synchronous, like the hook itself.\n */\nimport {\n activityBase,\n netTransfers,\n splitNet,\n type ActivityAsset,\n type ActivityItem,\n type ActivityKind,\n type ChainTx,\n type DescribeActivityContext,\n} from \"@anywalletkit/core\";\nimport {ccAssetByToken, ccChain} from \"@anywalletkit/swap2-assets\";\n\n/** The contract a transaction invoked (EVM `to`, Solana program, TON destination), lowercase for EVM. */\nexport function calledContract(tx: ChainTx): string | null {\n const to = tx.call?.to ?? tx.to;\n if (!to) return null;\n return to.startsWith(\"0x\") ? to.toLowerCase() : to;\n}\n\n/** 4-byte selector of an EVM call (`0x`-prefixed, lowercase), from `call.selector` or the calldata. */\nexport function callSelector(tx: ChainTx): string | undefined {\n const explicit = tx.call?.selector;\n if (explicit && /^0x[0-9a-fA-F]{8}$/.test(explicit)) return explicit.toLowerCase();\n const data = tx.call?.data;\n if (data && /^0x[0-9a-fA-F]{8}/.test(data)) return data.slice(0, 10).toLowerCase();\n return undefined;\n}\n\n/** Does `tx` call `contract` (case-insensitive for EVM)? */\nexport function callsContract(tx: ChainTx, contract: string): boolean {\n const to = calledContract(tx);\n if (!to) return false;\n return to.startsWith(\"0x\") ? to === contract.toLowerCase() : to === contract;\n}\n\n/** Does `tx` call one of `contracts` with one of `selectors` (any selector when the set is empty)? */\nexport function matchesCall(tx: ChainTx, contracts: Iterable<string>, selectors?: Iterable<string>): boolean {\n const to = calledContract(tx);\n if (!to) return false;\n let hit = false;\n for (const c of contracts) {\n if ((c.startsWith(\"0x\") ? c.toLowerCase() : c) === to) {\n hit = true;\n break;\n }\n }\n if (!hit) return false;\n if (!selectors) return true;\n const want = new Set<string>();\n for (const s of selectors) want.add(s.toLowerCase());\n if (want.size === 0) return true;\n const sel = callSelector(tx);\n return sel !== undefined && want.has(sel);\n}\n\n/** Human label of a chain for subtitles (\"Base\", \"Ethereum\"), falling back to the CAIP-2 id. */\nexport function chainLabel(caip2: string): string {\n return ccChain(caip2)?.label ?? caip2;\n}\n\n/** `0x1234…abcd` for an address the catalog does not name. */\nexport function shortAddress(a: string): string {\n return a.length > 14 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;\n}\n\n/**\n * Symbol / decimals per token: what the transfers already carry first, then the\n * swap2-assets catalog for the chain (native asset = `token === null`).\n */\nexport function assetMetaFor(tx: ChainTx): (token: string | null) => Partial<ActivityAsset> | undefined {\n const fromTransfers = new Map<string | null, Partial<ActivityAsset>>();\n for (const t of tx.transfers) {\n const key = t.token === null ? null : t.token.startsWith(\"0x\") ? t.token.toLowerCase() : t.token;\n if (fromTransfers.has(key)) continue;\n const meta: Partial<ActivityAsset> = {};\n if (t.symbol !== undefined) meta.symbol = t.symbol;\n if (t.decimals !== undefined) meta.decimals = t.decimals;\n if (meta.symbol !== undefined || meta.decimals !== undefined) fromTransfers.set(key, meta);\n }\n return (token) => {\n const key = token === null ? null : token.startsWith(\"0x\") ? token.toLowerCase() : token;\n const known = fromTransfers.get(key);\n if (known?.symbol !== undefined && known.decimals !== undefined) return known;\n const cat = ccAssetByToken(tx.chain, token ?? \"\");\n if (!cat) return known;\n const meta: Partial<ActivityAsset> = {symbol: known?.symbol ?? cat.symbol, decimals: known?.decimals ?? cat.decimals};\n return meta;\n };\n}\n\n/** Symbol for a title: the asset's symbol, the chain's native coin, or a shortened address. */\nexport function assetLabel(tx: ChainTx, a: ActivityAsset): string {\n if (a.symbol) return a.symbol;\n if (a.token === null) return ccAssetByToken(tx.chain, \"\")?.symbol ?? \"native\";\n return shortAddress(a.token);\n}\n\n/** Net movement for the owner, split into what left and what arrived, with symbols. */\nexport function ownerAssets(tx: ChainTx, ctx: DescribeActivityContext): {assetsIn: ActivityAsset[]; assetsOut: ActivityAsset[]} {\n return splitNet(netTransfers(tx, ctx.own), assetMetaFor(tx));\n}\n\n/** The largest-looking leg for a title: first asset, preferring one with a symbol. */\nfunction lead(tx: ChainTx, assets: ActivityAsset[]): string | undefined {\n const a = assets.find((x) => x.symbol) ?? assets[0];\n return a ? assetLabel(tx, a) : undefined;\n}\n\n/** Labels a swap module passes when describing its own transactions in the activity feed. */\nexport interface SwapActivityOptions {\n /** Registry module name (`module.json` → `name`). */\n protocol: string;\n /** Venue label for the subtitle, e.g. \"LI.FI\", \"Uniswap v3 · Base\". */\n subtitle?: string;\n /**\n * What the transaction is. `swap` / `bridge` get the automatic title\n * (\"Swapped A → B\", \"Bridged A\", \"Received A\"); `auto` picks `swap` when both\n * legs netted on this chain and `bridge` otherwise.\n */\n kind: ActivityKind | \"auto\";\n /** Override the computed title. */\n title?: string;\n /** Override the counterparty (default: the contract called). */\n counterparty?: string;\n /** Verb for a one-legged outbound item (default \"Bridged\"). */\n outVerb?: string;\n /** Suffix for a one-legged inbound item, e.g. \"via CCTP\" → \"Received USDC via CCTP\". */\n inSuffix?: string;\n}\n\n/**\n * Build the item once the caller has decided the transaction is this module's.\n * Returns null only when the owner moved nothing and no title was given — a\n * recognized call that touched none of the owner's balances is not activity.\n */\nexport function describeSwapLike(tx: ChainTx, ctx: DescribeActivityContext, o: SwapActivityOptions): ActivityItem | null {\n const {assetsIn, assetsOut} = ownerAssets(tx, ctx);\n const inLabel = lead(tx, assetsIn);\n const outLabel = lead(tx, assetsOut);\n let kind: ActivityKind;\n if (o.kind === \"auto\") kind = assetsIn.length > 0 && assetsOut.length > 0 ? \"swap\" : \"bridge\";\n else kind = o.kind;\n let title = o.title;\n if (title === undefined) {\n const received = inLabel ? `Received ${inLabel}${o.inSuffix ? ` ${o.inSuffix}` : \"\"}` : undefined;\n if (kind === \"bridge\") {\n // A bridge leg names what left; an inbound dust refund (gas rebate, surplus) is not the destination asset.\n if (outLabel) title = `${o.outVerb ?? \"Bridged\"} ${outLabel}`;\n else if (received) title = received;\n } else if (outLabel && inLabel) title = `Swapped ${outLabel} → ${inLabel}`;\n else if (outLabel) title = `${o.outVerb ?? \"Swapped\"} ${outLabel}`;\n else if (received) title = received;\n if (title === undefined) {\n if (tx.status === \"failed\") title = `Failed ${kind}`;\n else return null;\n }\n }\n const counterparty = o.counterparty ?? tx.call?.to ?? tx.to ?? undefined;\n const extra: Partial<ActivityItem> = {protocol: o.protocol, assetsIn, assetsOut};\n if (o.subtitle !== undefined) extra.subtitle = o.subtitle;\n if (counterparty !== undefined) extra.counterparty = counterparty;\n return activityBase(tx, kind, title, extra);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,kBASO;A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ChainTx, ActivityAsset, DescribeActivityContext, ActivityItem } from '@anywalletkit/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Shared `describeActivity` plumbing for the swap2 provider modules.
|
|
5
|
+
*
|
|
6
|
+
* A provider recognizes one of its own transactions offline (contract called +
|
|
7
|
+
* 4-byte selector, or a known counterparty on non-EVM chains) and this file
|
|
8
|
+
* turns the chain-normalized `ChainTx` into the wallet-facing `ActivityItem`:
|
|
9
|
+
* net asset movement for the owner's addresses, symbols / decimals from the
|
|
10
|
+
* transfers themselves or the swap2-assets catalog, and a "Swapped X → Y" /
|
|
11
|
+
* "Bridged X" / "Received X" title. Pure and synchronous, like the hook itself.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** The contract a transaction invoked (EVM `to`, Solana program, TON destination), lowercase for EVM. */
|
|
15
|
+
declare function calledContract(tx: ChainTx): string | null;
|
|
16
|
+
/** 4-byte selector of an EVM call (`0x`-prefixed, lowercase), from `call.selector` or the calldata. */
|
|
17
|
+
declare function callSelector(tx: ChainTx): string | undefined;
|
|
18
|
+
/** Does `tx` call `contract` (case-insensitive for EVM)? */
|
|
19
|
+
declare function callsContract(tx: ChainTx, contract: string): boolean;
|
|
20
|
+
/** Does `tx` call one of `contracts` with one of `selectors` (any selector when the set is empty)? */
|
|
21
|
+
declare function matchesCall(tx: ChainTx, contracts: Iterable<string>, selectors?: Iterable<string>): boolean;
|
|
22
|
+
/** Human label of a chain for subtitles ("Base", "Ethereum"), falling back to the CAIP-2 id. */
|
|
23
|
+
declare function chainLabel(caip2: string): string;
|
|
24
|
+
/** `0x1234…abcd` for an address the catalog does not name. */
|
|
25
|
+
declare function shortAddress(a: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* Symbol / decimals per token: what the transfers already carry first, then the
|
|
28
|
+
* swap2-assets catalog for the chain (native asset = `token === null`).
|
|
29
|
+
*/
|
|
30
|
+
declare function assetMetaFor(tx: ChainTx): (token: string | null) => Partial<ActivityAsset> | undefined;
|
|
31
|
+
/** Symbol for a title: the asset's symbol, the chain's native coin, or a shortened address. */
|
|
32
|
+
declare function assetLabel(tx: ChainTx, a: ActivityAsset): string;
|
|
33
|
+
/** Net movement for the owner, split into what left and what arrived, with symbols. */
|
|
34
|
+
declare function ownerAssets(tx: ChainTx, ctx: DescribeActivityContext): {
|
|
35
|
+
assetsIn: ActivityAsset[];
|
|
36
|
+
assetsOut: ActivityAsset[];
|
|
37
|
+
};
|
|
38
|
+
/** Labels a swap module passes when describing its own transactions in the activity feed. */
|
|
39
|
+
interface SwapActivityOptions {
|
|
40
|
+
/** Registry module name (`module.json` → `name`). */
|
|
41
|
+
protocol: string;
|
|
42
|
+
/** Venue label for the subtitle, e.g. "LI.FI", "Uniswap v3 · Base". */
|
|
43
|
+
subtitle?: string;
|
|
44
|
+
/**
|
|
45
|
+
* What the transaction is. `swap` / `bridge` get the automatic title
|
|
46
|
+
* ("Swapped A → B", "Bridged A", "Received A"); `auto` picks `swap` when both
|
|
47
|
+
* legs netted on this chain and `bridge` otherwise.
|
|
48
|
+
*/
|
|
49
|
+
kind: ActivityKind | "auto";
|
|
50
|
+
/** Override the computed title. */
|
|
51
|
+
title?: string;
|
|
52
|
+
/** Override the counterparty (default: the contract called). */
|
|
53
|
+
counterparty?: string;
|
|
54
|
+
/** Verb for a one-legged outbound item (default "Bridged"). */
|
|
55
|
+
outVerb?: string;
|
|
56
|
+
/** Suffix for a one-legged inbound item, e.g. "via CCTP" → "Received USDC via CCTP". */
|
|
57
|
+
inSuffix?: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Build the item once the caller has decided the transaction is this module's.
|
|
61
|
+
* Returns null only when the owner moved nothing and no title was given — a
|
|
62
|
+
* recognized call that touched none of the owner's balances is not activity.
|
|
63
|
+
*/
|
|
64
|
+
declare function describeSwapLike(tx: ChainTx, ctx: DescribeActivityContext, o: SwapActivityOptions): ActivityItem | null;
|
|
65
|
+
|
|
66
|
+
export { type SwapActivityOptions, assetLabel, assetMetaFor, callSelector, calledContract, callsContract, chainLabel, describeSwapLike, matchesCall, ownerAssets, shortAddress };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { ActivityKind, ChainTx, ActivityAsset, DescribeActivityContext, ActivityItem } from '@anywalletkit/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Shared `describeActivity` plumbing for the swap2 provider modules.
|
|
5
|
+
*
|
|
6
|
+
* A provider recognizes one of its own transactions offline (contract called +
|
|
7
|
+
* 4-byte selector, or a known counterparty on non-EVM chains) and this file
|
|
8
|
+
* turns the chain-normalized `ChainTx` into the wallet-facing `ActivityItem`:
|
|
9
|
+
* net asset movement for the owner's addresses, symbols / decimals from the
|
|
10
|
+
* transfers themselves or the swap2-assets catalog, and a "Swapped X → Y" /
|
|
11
|
+
* "Bridged X" / "Received X" title. Pure and synchronous, like the hook itself.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** The contract a transaction invoked (EVM `to`, Solana program, TON destination), lowercase for EVM. */
|
|
15
|
+
declare function calledContract(tx: ChainTx): string | null;
|
|
16
|
+
/** 4-byte selector of an EVM call (`0x`-prefixed, lowercase), from `call.selector` or the calldata. */
|
|
17
|
+
declare function callSelector(tx: ChainTx): string | undefined;
|
|
18
|
+
/** Does `tx` call `contract` (case-insensitive for EVM)? */
|
|
19
|
+
declare function callsContract(tx: ChainTx, contract: string): boolean;
|
|
20
|
+
/** Does `tx` call one of `contracts` with one of `selectors` (any selector when the set is empty)? */
|
|
21
|
+
declare function matchesCall(tx: ChainTx, contracts: Iterable<string>, selectors?: Iterable<string>): boolean;
|
|
22
|
+
/** Human label of a chain for subtitles ("Base", "Ethereum"), falling back to the CAIP-2 id. */
|
|
23
|
+
declare function chainLabel(caip2: string): string;
|
|
24
|
+
/** `0x1234…abcd` for an address the catalog does not name. */
|
|
25
|
+
declare function shortAddress(a: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* Symbol / decimals per token: what the transfers already carry first, then the
|
|
28
|
+
* swap2-assets catalog for the chain (native asset = `token === null`).
|
|
29
|
+
*/
|
|
30
|
+
declare function assetMetaFor(tx: ChainTx): (token: string | null) => Partial<ActivityAsset> | undefined;
|
|
31
|
+
/** Symbol for a title: the asset's symbol, the chain's native coin, or a shortened address. */
|
|
32
|
+
declare function assetLabel(tx: ChainTx, a: ActivityAsset): string;
|
|
33
|
+
/** Net movement for the owner, split into what left and what arrived, with symbols. */
|
|
34
|
+
declare function ownerAssets(tx: ChainTx, ctx: DescribeActivityContext): {
|
|
35
|
+
assetsIn: ActivityAsset[];
|
|
36
|
+
assetsOut: ActivityAsset[];
|
|
37
|
+
};
|
|
38
|
+
/** Labels a swap module passes when describing its own transactions in the activity feed. */
|
|
39
|
+
interface SwapActivityOptions {
|
|
40
|
+
/** Registry module name (`module.json` → `name`). */
|
|
41
|
+
protocol: string;
|
|
42
|
+
/** Venue label for the subtitle, e.g. "LI.FI", "Uniswap v3 · Base". */
|
|
43
|
+
subtitle?: string;
|
|
44
|
+
/**
|
|
45
|
+
* What the transaction is. `swap` / `bridge` get the automatic title
|
|
46
|
+
* ("Swapped A → B", "Bridged A", "Received A"); `auto` picks `swap` when both
|
|
47
|
+
* legs netted on this chain and `bridge` otherwise.
|
|
48
|
+
*/
|
|
49
|
+
kind: ActivityKind | "auto";
|
|
50
|
+
/** Override the computed title. */
|
|
51
|
+
title?: string;
|
|
52
|
+
/** Override the counterparty (default: the contract called). */
|
|
53
|
+
counterparty?: string;
|
|
54
|
+
/** Verb for a one-legged outbound item (default "Bridged"). */
|
|
55
|
+
outVerb?: string;
|
|
56
|
+
/** Suffix for a one-legged inbound item, e.g. "via CCTP" → "Received USDC via CCTP". */
|
|
57
|
+
inSuffix?: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Build the item once the caller has decided the transaction is this module's.
|
|
61
|
+
* Returns null only when the owner moved nothing and no title was given — a
|
|
62
|
+
* recognized call that touched none of the owner's balances is not activity.
|
|
63
|
+
*/
|
|
64
|
+
declare function describeSwapLike(tx: ChainTx, ctx: DescribeActivityContext, o: SwapActivityOptions): ActivityItem | null;
|
|
65
|
+
|
|
66
|
+
export { type SwapActivityOptions, assetLabel, assetMetaFor, callSelector, calledContract, callsContract, chainLabel, describeSwapLike, matchesCall, ownerAssets, shortAddress };
|
package/dist/activity.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assetLabel,
|
|
3
|
+
assetMetaFor,
|
|
4
|
+
callSelector,
|
|
5
|
+
calledContract,
|
|
6
|
+
callsContract,
|
|
7
|
+
chainLabel,
|
|
8
|
+
describeSwapLike,
|
|
9
|
+
matchesCall,
|
|
10
|
+
ownerAssets,
|
|
11
|
+
shortAddress
|
|
12
|
+
} from "./chunk-J4WXUNK2.js";
|
|
13
|
+
export {
|
|
14
|
+
assetLabel,
|
|
15
|
+
assetMetaFor,
|
|
16
|
+
callSelector,
|
|
17
|
+
calledContract,
|
|
18
|
+
callsContract,
|
|
19
|
+
chainLabel,
|
|
20
|
+
describeSwapLike,
|
|
21
|
+
matchesCall,
|
|
22
|
+
ownerAssets,
|
|
23
|
+
shortAddress
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=activity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import {
|
|
2
|
+
anySignal,
|
|
3
|
+
timeoutSignal
|
|
4
|
+
} from "./chunk-SKV5BVXK.js";
|
|
5
|
+
|
|
6
|
+
// src/remote.ts
|
|
7
|
+
function remoteProvider(opts) {
|
|
8
|
+
const name = opts.name;
|
|
9
|
+
if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error("swap2-remote: invalid provider name");
|
|
10
|
+
const baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
11
|
+
if (!baseUrl) throw new Error("swap2-remote: baseUrl is required");
|
|
12
|
+
const supportsRoute = opts.supportsRoute;
|
|
13
|
+
const enabled = opts.enabled;
|
|
14
|
+
const headers = Object.freeze({ ...opts.headers });
|
|
15
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
16
|
+
const timeoutMs = opts.timeoutMs ?? 12e3;
|
|
17
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 6e4) {
|
|
18
|
+
throw new Error("swap2-remote: timeoutMs must be an integer between 1 and 60000");
|
|
19
|
+
}
|
|
20
|
+
async function call(action, body, signal) {
|
|
21
|
+
const timeout = timeoutSignal(timeoutMs);
|
|
22
|
+
const requestSignal = signal ? anySignal([signal, timeout]) : timeout;
|
|
23
|
+
const res = await doFetch(`${baseUrl}/${action}`, {
|
|
24
|
+
method: "POST",
|
|
25
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
26
|
+
// UnsignedTx carries bigint fields (value, gasLimit) — JSON.stringify
|
|
27
|
+
// throws on them ("Do not know how to serialize a BigInt", seen
|
|
28
|
+
// 2026-10-10 on a Solana → Base preflight). Wire them as decimal strings.
|
|
29
|
+
body: JSON.stringify({ provider: name, ...body }, (_k, v) => typeof v === "bigint" ? v.toString() : v),
|
|
30
|
+
signal: requestSignal
|
|
31
|
+
});
|
|
32
|
+
if (!res.ok) {
|
|
33
|
+
const text = await res.text().catch(() => "");
|
|
34
|
+
throw new Error(`swap2-remote ${name}/${action}: ${res.status} ${text.slice(0, 300)}`);
|
|
35
|
+
}
|
|
36
|
+
return await res.json();
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
name,
|
|
40
|
+
// The browser side has no dark-flag env; the backend enforces its own
|
|
41
|
+
// flags — a disabled provider simply quotes null / rejects build.
|
|
42
|
+
enabled: () => enabled ? enabled() : true,
|
|
43
|
+
supportsRoute(from, to) {
|
|
44
|
+
return supportsRoute ? supportsRoute(from, to) : true;
|
|
45
|
+
},
|
|
46
|
+
async getQuote(params, signal) {
|
|
47
|
+
const out = await call("quote", { params }, signal);
|
|
48
|
+
if (out && typeof out === "object" && "noQuote" in out) {
|
|
49
|
+
throw new Error(String(out.noQuote).slice(0, 300));
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
},
|
|
53
|
+
async buildDeposit(quote) {
|
|
54
|
+
return call("build", { quote });
|
|
55
|
+
},
|
|
56
|
+
async preflightDeposit(quote, tx) {
|
|
57
|
+
await call("preflight", { quote, tx });
|
|
58
|
+
},
|
|
59
|
+
async trackIntent(ref) {
|
|
60
|
+
return call("track", { ref });
|
|
61
|
+
},
|
|
62
|
+
async notifyDeposit(intentId, txHash) {
|
|
63
|
+
await call("notify", { intentId, txHash });
|
|
64
|
+
},
|
|
65
|
+
async registerSignedOrder(intentId, signature) {
|
|
66
|
+
await call("register", { intentId, signature });
|
|
67
|
+
},
|
|
68
|
+
async buildClaim(ref) {
|
|
69
|
+
const out = await call("claim", { ref });
|
|
70
|
+
if (!out || typeof out !== "object" || !("to" in out)) return null;
|
|
71
|
+
return out;
|
|
72
|
+
},
|
|
73
|
+
...opts.supportsChain ? { supportsChain: opts.supportsChain.bind(opts) } : {},
|
|
74
|
+
...opts.supportsChainPair ? { supportsChainPair: opts.supportsChainPair.bind(opts) } : {},
|
|
75
|
+
...opts.supportsSameChain !== void 0 ? { supportsSameChain: opts.supportsSameChain } : {}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export {
|
|
80
|
+
remoteProvider
|
|
81
|
+
};
|
|
82
|
+
//# sourceMappingURL=chunk-4H2JVYXT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/remote.ts"],"sourcesContent":["import type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"./types.js\";\nimport {anySignal, timeoutSignal} from \"./util.js\";\n\n/**\n * HTTP-proxied `CrossChainProvider`: forwards every provider call to a backend\n * that runs the real provider. This is how a BROWSER context (e.g. a wallet's\n * signing worker) executes the full swap2 layer — account binding,\n * approvals, cell-body guards, id/status lifecycle — while provider secrets\n * (API JWTs, affiliate config) and non-CORS REST endpoints stay server-side.\n *\n * Wire protocol: POST {baseUrl}/{action} with a JSON body, one action per\n * provider method:\n * quote {provider, params: QuoteParams} → Quote | null\n * build {provider, quote: Quote} → UnsignedTx\n * preflight {provider, quote: Quote, tx: UnsignedTx} → {}\n * track {provider, ref: IntentRef} → IntentStatus\n * notify {provider, intentId, txHash} → {}\n * register {provider, intentId, signature} → {}\n * claim {provider, ref: IntentRef} → UnsignedTx | null\n * supports {provider, from, to} → {supported: boolean}\n *\n * `supportsRoute`/`enabled` need a SYNC answer, so they are config: pass the\n * routes the backend advertises via `supports`, or leave the default\n * allow-and-let-quote-decide behavior (a null quote is a clean miss).\n */\nexport interface RemoteProviderOptions {\n /** Provider name the backend multiplexes on (e.g. \"near-intents\"). */\n name: string;\n /** Endpoint prefix, e.g. \"/api/v2/swap2\" (same-origin) or absolute URL. */\n baseUrl: string;\n /** Sync capability gate; defaults to true (the backend quote decides). */\n supportsRoute?: (from: Asset, to: Asset) => boolean;\n /** Optional synchronous dark flag for accurate client-side discovery. */\n enabled?: () => boolean;\n /** Optional chain-level discovery hooks mirrored from the backend. */\n supportsChain?: (caip2: string) => boolean;\n supportsChainPair?: (fromChain: string, toChain: string) => boolean;\n /** Explicit opt-in when the backend can execute same-chain swaps. */\n supportsSameChain?: boolean;\n /** Defaults to globalThis.fetch — injectable for tests. */\n fetchImpl?: typeof fetch;\n /** Extra headers (e.g. auth) attached to every call. */\n headers?: Record<string, string>;\n /** Per-request fail-closed timeout. Defaults to 12 seconds. */\n timeoutMs?: number;\n}\n\n/**\n * A provider that runs on your server: quotes, deposits and tracking go to `baseUrl`, so API keys\n * and affiliate settings never ship in the app. The engine still validates every quote and\n * transaction locally before signing.\n */\nexport function remoteProvider(opts: RemoteProviderOptions): CrossChainProvider {\n const name = opts.name;\n if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error(\"swap2-remote: invalid provider name\");\n const baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n if (!baseUrl) throw new Error(\"swap2-remote: baseUrl is required\");\n const supportsRoute = opts.supportsRoute;\n const enabled = opts.enabled;\n const headers = Object.freeze({...opts.headers});\n const doFetch = opts.fetchImpl ?? fetch;\n const timeoutMs = opts.timeoutMs ?? 12_000;\n if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 60_000) {\n throw new Error(\"swap2-remote: timeoutMs must be an integer between 1 and 60000\");\n }\n\n async function call<T>(action: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<T> {\n const timeout = timeoutSignal(timeoutMs);\n const requestSignal = signal ? anySignal([signal, timeout]) : timeout;\n const res = await doFetch(`${baseUrl}/${action}`, {\n method: \"POST\",\n headers: {...headers, \"content-type\": \"application/json\"},\n // UnsignedTx carries bigint fields (value, gasLimit) — JSON.stringify\n // throws on them (\"Do not know how to serialize a BigInt\", seen\n // 2026-10-10 on a Solana → Base preflight). Wire them as decimal strings.\n body: JSON.stringify({provider: name, ...body}, (_k, v) => (typeof v === \"bigint\" ? v.toString() : v)),\n signal: requestSignal,\n });\n if (!res.ok) {\n // Surface the backend's message — provider errors are actionable\n // (\"quote expired\", \"route unsupported\"), not just status codes.\n const text = await res.text().catch(() => \"\");\n throw new Error(`swap2-remote ${name}/${action}: ${res.status} ${text.slice(0, 300)}`);\n }\n return (await res.json()) as T;\n }\n\n return {\n name,\n // The browser side has no dark-flag env; the backend enforces its own\n // flags — a disabled provider simply quotes null / rejects build.\n enabled: () => enabled ? enabled() : true,\n supportsRoute(from: Asset, to: Asset): boolean {\n return supportsRoute ? supportsRoute(from, to) : true;\n },\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const out = await call<Quote | {noQuote: string} | null>(\"quote\", {params}, signal);\n if (out && typeof out === \"object\" && \"noQuote\" in out) {\n // The backend forwarded the venue's own refusal — throw it so the\n // router records a REASON instead of an anonymous null.\n throw new Error(String((out as {noQuote: unknown}).noQuote).slice(0, 300));\n }\n return out;\n },\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n return call<UnsignedTx>(\"build\", {quote});\n },\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n await call<Record<string, never>>(\"preflight\", {quote, tx});\n },\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n return call<IntentStatus>(\"track\", {ref});\n },\n async notifyDeposit(intentId: string, txHash: string): Promise<void> {\n await call<Record<string, never>>(\"notify\", {intentId, txHash});\n },\n async registerSignedOrder(intentId: string, signature: string): Promise<void> {\n await call<Record<string, never>>(\"register\", {intentId, signature});\n },\n async buildClaim(ref: IntentRef): Promise<UnsignedTx | null> {\n const out = await call<UnsignedTx | null | Record<string, never>>(\"claim\", {ref});\n // A backend without the action (older deploy) answers {} — treat as \"not ready\".\n if (!out || typeof out !== \"object\" || !(\"to\" in out)) return null;\n return out as UnsignedTx;\n },\n ...(opts.supportsChain ? {supportsChain: opts.supportsChain.bind(opts)} : {}),\n ...(opts.supportsChainPair ? {supportsChainPair: opts.supportsChainPair.bind(opts)} : {}),\n ...(opts.supportsSameChain !== undefined ? {supportsSameChain: opts.supportsSameChain} : {}),\n };\n}\n"],"mappings":";;;;;;AAoDO,SAAS,eAAe,MAAiD;AAC9E,QAAM,OAAO,KAAK;AAClB,MAAI,CAAC,mBAAmB,KAAK,IAAI,EAAG,OAAM,IAAI,MAAM,qCAAqC;AACzF,QAAM,UAAU,KAAK,QAAQ,QAAQ,QAAQ,EAAE;AAC/C,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,mCAAmC;AACjE,QAAM,gBAAgB,KAAK;AAC3B,QAAM,UAAU,KAAK;AACrB,QAAM,UAAU,OAAO,OAAO,EAAC,GAAG,KAAK,QAAO,CAAC;AAC/C,QAAM,UAAU,KAAK,aAAa;AAClC,QAAM,YAAY,KAAK,aAAa;AACpC,MAAI,CAAC,OAAO,UAAU,SAAS,KAAK,aAAa,KAAK,YAAY,KAAQ;AACxE,UAAM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