@anywalletkit/tokens 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.
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,54 @@
1
- # Temporary Holding Version
1
+ # @anywalletkit/tokens
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/tokens?label=npm)](https://www.npmjs.com/package/@anywalletkit/tokens)
4
+
5
+ Tokens users add themselves, by address and at their own risk: read the token from the chain, warn about what matters before it is saved, keep the list, and swap it through the engines that accept tokens outside the catalog. EVM contracts and Solana mints (Token-2022 included).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @anywalletkit/tokens
11
+ # or: pnpm add @anywalletkit/tokens · yarn add @anywalletkit/tokens
12
+ ```
13
+
14
+ On npm: [@anywalletkit/tokens](https://www.npmjs.com/package/@anywalletkit/tokens), published from the [release workflow](https://github.com/ultratestbro/anywalletkit/blob/main/RELEASING.md) with provenance.
15
+
16
+ Pure TypeScript; depends on `@anywalletkit/swap2-assets` (the catalog it checks against) and takes `@anywalletkit/core` types. Runs under Hermes.
17
+
18
+ ```ts
19
+ import { inspectToken, TokensTable, swapSource } from '@anywalletkit/tokens'
20
+
21
+ const found = await inspectToken(account, '0x6982508145454Ce325dDbE47a25d4ec3d2311933') // an EVM or Solana account
22
+ if (found.listed) {
23
+ // already in the catalog: nothing to add
24
+ } else {
25
+ found.assessment // { level: 'caution' | 'danger', risks: [{ code, level, message }] } — show before saving
26
+ const tokens = new TokensTable(myJsonStorage) // AsyncStorage / chrome.storage / memoryJsonStorage()
27
+ await tokens.load()
28
+ await tokens.add(found.token) // after the user accepted the warnings
29
+ }
30
+
31
+ // Swap a user token: the engine must opt in
32
+ const swaps = new RouterSwap2Protocol(account, { fromChain: 'eip155:1', providers, allowUnlistedTokens: true })
33
+ await swaps.quoteSwap2Routes({ ...swapSource(token), toToken: 'USDC', fromTokenAmount })
34
+ ```
35
+
36
+ ## What it checks
37
+
38
+ `inspectToken` calls the account's `getTokenInfo(address)` (`wallet-evm`, `wallet-solana`): decimals, symbol, name, supply and holder-relevant flags. A wallet, an NFT or a plain contract throws `NotATokenError`. `assessToken(info, chain)` then lists every warning, worst first:
39
+
40
+ - **danger**: `impersonation` (the symbol reads as a catalog token of the same chain, or as a native coin or major stablecoin anywhere, after folding Cyrillic / Greek look-alikes, `$` → S, `₮` → T, fullwidth and invisible characters), `permanent-delegate`, `transfer-hook`, `non-transferable`;
41
+ - **caution**: `unlisted` (always), `upgradeable`, `mint-authority`, `freeze-authority`, `transfer-fee`, `default-frozen`, `pausable`, `odd-characters`, `no-symbol`, `zero-supply`, `unusual-decimals`.
42
+
43
+ A user token's symbol and name are what the token says about itself: display them next to the address, never identify the token by them.
44
+
45
+ ## TokensTable
46
+
47
+ One JSON value in the app's storage. `load()` once (a failed read throws and leaves the table unloaded instead of empty), then `list(chain?)` / `get(chain, address)` synchronously; `add` / `remove` queue behind each other and a failed save leaves memory as stored. Catalog tokens, malformed entries and more than `maxTokens` (200) are refused; stored entries that do not validate are dropped on load. Solana is keyed by the catalog's `solana:mainnet`, whichever id the account reports.
48
+
49
+ ## Testing
50
+
51
+ - `pnpm test`: assessment rules (look-alikes, flags, levels), the table (persistence, refusals, failed reads and saves), `inspectToken`.
52
+ - `pnpm verify:live`: mainnet reads (PEPE, USDC, MKR, an NFT, BONK, JUP, a wallet) and quotes of tokens outside the catalog through the real router and providers — PEPE ⇄ USDC on Ethereum, PEPE → USDC on Base, BONK ⇄ USDC on Solana — refused without `allowUnlistedTokens`. Nothing is signed.
53
+
54
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,324 @@
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/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ TokensError: () => TokensError,
24
+ TokensTable: () => TokensTable,
25
+ assessToken: () => assessToken,
26
+ foldSymbol: () => foldSymbol,
27
+ inspectToken: () => inspectToken,
28
+ memoryJsonStorage: () => memoryJsonStorage,
29
+ swapSource: () => swapSource
30
+ });
31
+ module.exports = __toCommonJS(src_exports);
32
+
33
+ // src/assess.ts
34
+ var import_swap2_assets = require("@anywalletkit/swap2-assets");
35
+ var FLAG_RISKS = {
36
+ "upgradeable": { level: "caution", message: "The token's owner can replace its code." },
37
+ "mint-authority": { level: "caution", message: "The issuer can mint more at any time." },
38
+ "freeze-authority": { level: "caution", message: "The issuer can freeze your balance." },
39
+ "permanent-delegate": { level: "danger", message: "The issuer can move or burn the tokens in your wallet." },
40
+ "transfer-fee": { level: "caution", message: "Every transfer pays a fee to the issuer." },
41
+ "transfer-hook": { level: "danger", message: "A program of the issuer's choosing runs on every transfer: it can block selling." },
42
+ "non-transferable": { level: "danger", message: "It cannot be moved: not sent, not swapped." },
43
+ "default-frozen": { level: "caution", message: "New holders start frozen until the issuer lets them move it." },
44
+ "pausable": { level: "caution", message: "The issuer can pause every transfer." }
45
+ };
46
+ var CONFUSABLES = {
47
+ "\u0410": "A",
48
+ "\u0412": "B",
49
+ "\u0415": "E",
50
+ "\u041A": "K",
51
+ "\u041C": "M",
52
+ "\u041D": "H",
53
+ "\u041E": "O",
54
+ "\u0420": "P",
55
+ "\u0421": "C",
56
+ "\u0422": "T",
57
+ "\u0425": "X",
58
+ "\u0423": "Y",
59
+ "\u0406": "I",
60
+ "\u0408": "J",
61
+ "\u0405": "S",
62
+ "\u0500": "D",
63
+ "\u0430": "A",
64
+ "\u0432": "B",
65
+ "\u0435": "E",
66
+ "\u043A": "K",
67
+ "\u043C": "M",
68
+ "\u043D": "H",
69
+ "\u043E": "O",
70
+ "\u0440": "P",
71
+ "\u0441": "C",
72
+ "\u0442": "T",
73
+ "\u0445": "X",
74
+ "\u0443": "Y",
75
+ "\u0456": "I",
76
+ "\u0458": "J",
77
+ "\u0455": "S",
78
+ "\u0501": "D",
79
+ "\u0391": "A",
80
+ "\u0392": "B",
81
+ "\u0395": "E",
82
+ "\u0396": "Z",
83
+ "\u0397": "H",
84
+ "\u0399": "I",
85
+ "\u039A": "K",
86
+ "\u039C": "M",
87
+ "\u039D": "N",
88
+ "\u039F": "O",
89
+ "\u03A1": "P",
90
+ "\u03A4": "T",
91
+ "\u03A5": "Y",
92
+ "\u03A7": "X",
93
+ "\u03B1": "A",
94
+ "\u03B5": "E",
95
+ "\u03B9": "I",
96
+ "\u03BA": "K",
97
+ "\u03BD": "V",
98
+ "\u03BF": "O",
99
+ "\u03C1": "P",
100
+ "\u03C4": "T",
101
+ "\u03C5": "U",
102
+ "\u03C7": "X",
103
+ "$": "S",
104
+ "\u20AE": "T",
105
+ "\u20AC": "E",
106
+ "\xA2": "C",
107
+ "\u20BF": "B",
108
+ "\u039E": "E"
109
+ };
110
+ var INVISIBLE = /[­͏؜ᅟᅠ឴឵᠋-᠏​-‏‪-‮⁠-ㅤ︀-️ᅠ]/g;
111
+ function foldSymbol(text) {
112
+ let s = text.replace(INVISIBLE, "").replace(/\s+/g, "");
113
+ if (typeof s.normalize === "function") s = s.normalize("NFKC");
114
+ s = s.replace(/[\uFF01-\uFF5E]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 65248));
115
+ let out = "";
116
+ for (const ch of s) out += CONFUSABLES[ch] ?? ch;
117
+ return out.toUpperCase();
118
+ }
119
+ var MAJOR_TOKENS = ["USDT", "USDC", "DAI", "USDe", "USDS", "PYUSD", "FDUSD", "USD1", "USDG", "EURC", "WETH", "WBTC", "cbBTC", "stETH", "wstETH", "WSOL"];
120
+ var majors;
121
+ function majorSymbols() {
122
+ if (majors) return majors;
123
+ const m = /* @__PURE__ */ new Map();
124
+ for (const chain of import_swap2_assets.CC_SOURCE_CHAINS) for (const a of chain.assets) if (!a.contract && !m.has(foldSymbol(a.symbol))) m.set(foldSymbol(a.symbol), a.symbol);
125
+ for (const sym of MAJOR_TOKENS) if (!m.has(foldSymbol(sym))) m.set(foldSymbol(sym), sym);
126
+ majors = m;
127
+ return m;
128
+ }
129
+ function lookalikeOf(folded, chain) {
130
+ if (!folded) return void 0;
131
+ if (chain) {
132
+ const same = (0, import_swap2_assets.ccChain)((0, import_swap2_assets.catalogChainId)(chain))?.assets.find((a) => foldSymbol(a.symbol) === folded);
133
+ if (same) return same.symbol;
134
+ }
135
+ return majorSymbols().get(folded);
136
+ }
137
+ var PLAIN = /^[\x20-\x7E]*$/;
138
+ function assessToken(info, chain) {
139
+ const risks = [{ code: "unlisted", level: "caution", message: "Not in the wallet's token list. Anyone can create a token with any name and logo: check the address with the project itself." }];
140
+ const folded = foldSymbol(info.symbol);
141
+ const lookalike = lookalikeOf(folded, chain);
142
+ if (lookalike) {
143
+ risks.push({ code: "impersonation", level: "danger", message: `It calls itself ${JSON.stringify(info.symbol)}, like ${lookalike}, but it is a different token at a different address.` });
144
+ }
145
+ if (!PLAIN.test(info.symbol) || !PLAIN.test(info.name) || info.symbol !== info.symbol.replace(INVISIBLE, "") || info.name !== info.name.replace(INVISIBLE, "")) {
146
+ risks.push({ code: "odd-characters", level: "caution", message: "Its symbol or name uses characters that can look like other letters, or invisible ones." });
147
+ }
148
+ if (!info.symbol.trim()) risks.push({ code: "no-symbol", level: "caution", message: "The token reports no symbol." });
149
+ if (info.totalSupply === 0n) risks.push({ code: "zero-supply", level: "caution", message: "Nothing has been minted." });
150
+ if (info.decimals > 24) risks.push({ code: "unusual-decimals", level: "caution", message: `It uses ${info.decimals} decimals; amounts may display oddly.` });
151
+ for (const flag of info.flags) {
152
+ const r = FLAG_RISKS[flag];
153
+ if (r) risks.push({ code: flag, ...r });
154
+ }
155
+ risks.sort((a, b) => a.level === b.level ? 0 : a.level === "danger" ? -1 : 1);
156
+ return { level: risks.some((r) => r.level === "danger") ? "danger" : "caution", risks };
157
+ }
158
+
159
+ // src/table.ts
160
+ var import_swap2_assets2 = require("@anywalletkit/swap2-assets");
161
+ function memoryJsonStorage(initial = null) {
162
+ const clone = (v) => JSON.parse(JSON.stringify(v));
163
+ const s = {
164
+ value: initial,
165
+ async get() {
166
+ return s.value === null ? null : clone(s.value);
167
+ },
168
+ async set(value) {
169
+ s.value = clone(value);
170
+ }
171
+ };
172
+ return s;
173
+ }
174
+ var TokensError = class extends Error {
175
+ code;
176
+ constructor(code, message) {
177
+ super(message);
178
+ this.name = "TokensError";
179
+ this.code = code;
180
+ }
181
+ };
182
+ var sameAddress = (chain, a, b) => chain.startsWith("eip155:") ? a.toLowerCase() === b.toLowerCase() : a === b;
183
+ var FLAGS = /* @__PURE__ */ new Set(["upgradeable", "mint-authority", "freeze-authority", "permanent-delegate", "transfer-fee", "transfer-hook", "non-transferable", "default-frozen", "pausable"]);
184
+ function validEntry(t) {
185
+ if (!t || typeof t !== "object") return null;
186
+ const e = t;
187
+ if (typeof e.chain !== "string" || typeof e.address !== "string" || !(0, import_swap2_assets2.isTokenAddress)(e.chain, e.address)) return null;
188
+ if (typeof e.decimals !== "number" || !Number.isInteger(e.decimals) || e.decimals < 0 || e.decimals > 77) return null;
189
+ if (typeof e.symbol !== "string" || typeof e.name !== "string" || typeof e.standard !== "string" || typeof e.addedAt !== "number") return null;
190
+ if (!Array.isArray(e.flags) || !e.flags.every((f) => typeof f === "string" && FLAGS.has(f))) return null;
191
+ return {
192
+ chain: e.chain,
193
+ address: e.address,
194
+ symbol: e.symbol.slice(0, 128),
195
+ name: e.name.slice(0, 128),
196
+ decimals: e.decimals,
197
+ standard: e.standard,
198
+ flags: [...e.flags],
199
+ addedAt: e.addedAt
200
+ };
201
+ }
202
+ async function inspectToken(account, address, now = Date.now) {
203
+ let reported = account.chain;
204
+ if (reported === "eip155:unknown") {
205
+ if (typeof account.getChainId !== "function") throw new TokensError("unsupported-chain", "The account does not know its chain id; create it with chainId.");
206
+ reported = `eip155:${String(await account.getChainId())}`;
207
+ }
208
+ const chain = (0, import_swap2_assets2.catalogChainId)(reported);
209
+ if (!chain.startsWith("eip155:") && !chain.startsWith("solana:")) throw new TokensError("unsupported-chain", `Adding tokens is supported on EVM chains and Solana, not ${account.chain}.`);
210
+ const ref = address.trim();
211
+ if (!(0, import_swap2_assets2.isTokenAddress)(chain, ref)) throw new TokensError("bad-address", `${JSON.stringify(address)} is not a token address on ${chain}.`);
212
+ const listed = (0, import_swap2_assets2.ccAssetByToken)(chain, ref);
213
+ if (listed) return { listed };
214
+ if (typeof account.getTokenInfo !== "function") throw new TokensError("unsupported-chain", `This ${account.chain} account cannot read token info.`);
215
+ const info = await account.getTokenInfo(ref);
216
+ const token = {
217
+ chain,
218
+ address: info.address,
219
+ symbol: info.symbol.slice(0, 128),
220
+ name: info.name.slice(0, 128),
221
+ decimals: info.decimals,
222
+ standard: info.standard,
223
+ flags: [...info.flags],
224
+ addedAt: now()
225
+ };
226
+ return { info, assessment: assessToken(info, chain), token };
227
+ }
228
+ function swapSource(token) {
229
+ return { fromToken: token.address, fromTokenDecimals: token.decimals };
230
+ }
231
+ var TokensTable = class {
232
+ constructor(storage, options = {}) {
233
+ this.storage = storage;
234
+ this.maxTokens = options.maxTokens ?? 200;
235
+ }
236
+ storage;
237
+ _state = null;
238
+ _loading = null;
239
+ _writes = Promise.resolve();
240
+ listeners = /* @__PURE__ */ new Set();
241
+ maxTokens;
242
+ /** Read the stored list. Call once before the sync reads; a failed read throws and leaves the table unloaded. */
243
+ async load() {
244
+ await this.state();
245
+ }
246
+ /** Called after every successful write. Returns the unsubscribe function. */
247
+ subscribe(fn) {
248
+ this.listeners.add(fn);
249
+ return () => {
250
+ this.listeners.delete(fn);
251
+ };
252
+ }
253
+ /** The user's tokens, oldest first; only those on `chain` when given. */
254
+ list(chain) {
255
+ const s = this.loaded();
256
+ const want = chain === void 0 ? void 0 : (0, import_swap2_assets2.catalogChainId)(chain);
257
+ return s.tokens.filter((t) => want === void 0 || t.chain === want).map((t) => ({ ...t, flags: [...t.flags] }));
258
+ }
259
+ /** The user token at `address` on `chain`, if added. */
260
+ get(chain, address) {
261
+ const c = (0, import_swap2_assets2.catalogChainId)(chain);
262
+ const t = this.loaded().tokens.find((x) => x.chain === c && sameAddress(c, x.address, address));
263
+ return t ? { ...t, flags: [...t.flags] } : void 0;
264
+ }
265
+ /** Add (or refresh) a token — usually `inspection.token` after the user accepted the warnings. */
266
+ async add(token) {
267
+ const entry = validEntry({ ...token, chain: (0, import_swap2_assets2.catalogChainId)(token.chain) });
268
+ if (!entry) throw new TokensError("bad-token", "Not a valid token entry (address, decimals 0\u201377, symbol, name, standard, flags).");
269
+ if ((0, import_swap2_assets2.ccAssetByToken)(entry.chain, entry.address)) throw new TokensError("listed", `${entry.address} is already in the wallet's token list.`);
270
+ await this.update((s) => {
271
+ const rest = s.tokens.filter((t) => !(t.chain === entry.chain && sameAddress(entry.chain, t.address, entry.address)));
272
+ if (rest.length >= this.maxTokens) throw new TokensError("full", `At most ${this.maxTokens} tokens can be added.`);
273
+ return { v: 1, tokens: [...rest, entry] };
274
+ });
275
+ return { ...entry, flags: [...entry.flags] };
276
+ }
277
+ /** Remove a token. Returns whether it was there. */
278
+ async remove(chain, address) {
279
+ const c = (0, import_swap2_assets2.catalogChainId)(chain);
280
+ let removed = false;
281
+ await this.update((s) => {
282
+ const rest = s.tokens.filter((t) => !(t.chain === c && sameAddress(c, t.address, address)));
283
+ removed = rest.length !== s.tokens.length;
284
+ return { v: 1, tokens: rest };
285
+ });
286
+ return removed;
287
+ }
288
+ loaded() {
289
+ if (!this._state) throw new TokensError("not-loaded", "Call load() before reading the tokens table.");
290
+ return this._state;
291
+ }
292
+ async state() {
293
+ if (this._state) return this._state;
294
+ this._loading ??= (async () => {
295
+ let stored;
296
+ try {
297
+ stored = await this.storage.get();
298
+ } catch (e) {
299
+ this._loading = null;
300
+ throw e;
301
+ }
302
+ const tokens = stored && stored.v === 1 && Array.isArray(stored.tokens) ? stored.tokens.map(validEntry).filter((t) => t !== null) : [];
303
+ this._state = { v: 1, tokens };
304
+ return this._state;
305
+ })();
306
+ return this._loading;
307
+ }
308
+ update(change) {
309
+ const run = this._writes.then(async () => {
310
+ const next = change(await this.state());
311
+ await this.storage.set(next);
312
+ this._state = next;
313
+ for (const fn of this.listeners) {
314
+ try {
315
+ fn();
316
+ } catch {
317
+ }
318
+ }
319
+ });
320
+ this._writes = run.catch(() => void 0);
321
+ return run;
322
+ }
323
+ };
324
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/assess.ts","../src/table.ts"],"sourcesContent":["export { assessToken, foldSymbol, type TokenAssessment, type TokenRisk, type TokenRiskCode, type TokenRiskLevel } from './assess.js'\nexport {\n TokensTable, TokensError, inspectToken, swapSource, memoryJsonStorage,\n type JsonStorage, type TokensState, type UserToken, type TokenInspection, type TokensErrorCode,\n} from './table.js'\n","import type { TokenFlag, TokenInfo } from '@anywalletkit/core'\nimport { CC_SOURCE_CHAINS, catalogChainId, ccChain } from '@anywalletkit/swap2-assets'\n\n/** `danger`: the token can take or trap the user's money, or pretends to be another one. `caution`: worth knowing. */\nexport type TokenRiskLevel = 'danger' | 'caution'\n\n/**\n * Why a token deserves a warning:\n * - `unlisted`: always — the wallet's list does not include it, and anyone can deploy a token with any name and logo.\n * - `impersonation`: its symbol reads as a known token's (USDC, ETH, …), look-alike letters included.\n * - `odd-characters`: its symbol or name uses characters outside plain ASCII, or invisible ones.\n * - `no-symbol`: it reports no symbol.\n * - `zero-supply`: nothing has been minted.\n * - `unusual-decimals`: more than 24 decimals.\n * - a {@link TokenFlag} read from the chain (issuer powers, Token-2022 extensions).\n */\nexport type TokenRiskCode = 'unlisted' | 'impersonation' | 'odd-characters' | 'no-symbol' | 'zero-supply' | 'unusual-decimals' | TokenFlag\n\n/** One warning, worded for the person adding the token. */\nexport interface TokenRisk {\n code: TokenRiskCode\n level: TokenRiskLevel\n message: string\n}\n\n/** Every warning that applies, worst first, and the worst level. A user token is never \"safe\": `caution` is the floor. */\nexport interface TokenAssessment {\n level: TokenRiskLevel\n risks: TokenRisk[]\n}\n\nconst FLAG_RISKS: Readonly<Record<TokenFlag, { level: TokenRiskLevel; message: string }>> = {\n 'upgradeable': { level: 'caution', message: \"The token's owner can replace its code.\" },\n 'mint-authority': { level: 'caution', message: 'The issuer can mint more at any time.' },\n 'freeze-authority': { level: 'caution', message: 'The issuer can freeze your balance.' },\n 'permanent-delegate': { level: 'danger', message: 'The issuer can move or burn the tokens in your wallet.' },\n 'transfer-fee': { level: 'caution', message: 'Every transfer pays a fee to the issuer.' },\n 'transfer-hook': { level: 'danger', message: \"A program of the issuer's choosing runs on every transfer: it can block selling.\" },\n 'non-transferable': { level: 'danger', message: 'It cannot be moved: not sent, not swapped.' },\n 'default-frozen': { level: 'caution', message: 'New holders start frozen until the issuer lets them move it.' },\n 'pausable': { level: 'caution', message: 'The issuer can pause every transfer.' },\n}\n\n/** Letters that render like Latin capitals (Cyrillic, Greek) and currency signs used as letters. */\nconst CONFUSABLES: Readonly<Record<string, string>> = {\n 'А': 'A', 'В': 'B', 'Е': 'E', 'К': 'K', 'М': 'M', 'Н': 'H', 'О': 'O', 'Р': 'P', 'С': 'C', 'Т': 'T', 'Х': 'X', 'У': 'Y', 'І': 'I', 'Ј': 'J', 'Ѕ': 'S', 'Ԁ': 'D',\n 'а': 'A', 'в': 'B', 'е': 'E', 'к': 'K', 'м': 'M', 'н': 'H', 'о': 'O', 'р': 'P', 'с': 'C', 'т': 'T', 'х': 'X', 'у': 'Y', 'і': 'I', 'ј': 'J', 'ѕ': 'S', 'ԁ': 'D',\n 'Α': 'A', 'Β': 'B', 'Ε': 'E', 'Ζ': 'Z', 'Η': 'H', 'Ι': 'I', 'Κ': 'K', 'Μ': 'M', 'Ν': 'N', 'Ο': 'O', 'Ρ': 'P', 'Τ': 'T', 'Υ': 'Y', 'Χ': 'X',\n 'α': 'A', 'ε': 'E', 'ι': 'I', 'κ': 'K', 'ν': 'V', 'ο': 'O', 'ρ': 'P', 'τ': 'T', 'υ': 'U', 'χ': 'X',\n '$': 'S', '₮': 'T', '€': 'E', '¢': 'C', '₿': 'B', 'Ξ': 'E',\n}\n/** Zero-width, bidi and other invisible format characters. */\nconst INVISIBLE = /[­͏؜ᅟᅠ឴឵᠋-᠏​-‏‪-‮⁠-ㅤ︀-️ᅠ]/g\n\n/** A symbol folded the way a reader sees it: invisible characters gone, compatibility forms unified, look-alikes mapped, upper case. */\nexport function foldSymbol(text: string): string {\n let s = text.replace(INVISIBLE, '').replace(/\\s+/g, '')\n if (typeof s.normalize === 'function') s = s.normalize('NFKC')\n // Fullwidth ASCII by hand too: some Hermes builds ship without String.prototype.normalize.\n s = s.replace(/[\\uFF01-\\uFF5E]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xFEE0))\n let out = ''\n for (const ch of s) out += CONFUSABLES[ch] ?? ch\n return out.toUpperCase()\n}\n\n/** Symbols nobody should reuse on any chain: the big stablecoins and wrapped coins (natives are added from the catalog). */\nconst MAJOR_TOKENS = ['USDT', 'USDC', 'DAI', 'USDe', 'USDS', 'PYUSD', 'FDUSD', 'USD1', 'USDG', 'EURC', 'WETH', 'WBTC', 'cbBTC', 'stETH', 'wstETH', 'WSOL']\n\nlet majors: ReadonlyMap<string, string> | undefined\n/** Folded → display: every chain's native coin from the catalog, plus {@link MAJOR_TOKENS}. */\nfunction majorSymbols(): ReadonlyMap<string, string> {\n if (majors) return majors\n const m = new Map<string, string>()\n for (const chain of CC_SOURCE_CHAINS) for (const a of chain.assets) if (!a.contract && !m.has(foldSymbol(a.symbol))) m.set(foldSymbol(a.symbol), a.symbol)\n for (const sym of MAJOR_TOKENS) if (!m.has(foldSymbol(sym))) m.set(foldSymbol(sym), sym)\n majors = m\n return m\n}\n\n/** The known token a folded symbol reads as: any catalog token on the same chain, or a major one anywhere. */\nfunction lookalikeOf(folded: string, chain: string | undefined): string | undefined {\n if (!folded) return undefined\n if (chain) {\n const same = ccChain(catalogChainId(chain))?.assets.find((a) => foldSymbol(a.symbol) === folded)\n if (same) return same.symbol\n }\n return majorSymbols().get(folded)\n}\n\nconst PLAIN = /^[\\x20-\\x7E]*$/\n\n/**\n * Warnings for a token read with `getTokenInfo`, for a token the wallet's list does not include.\n * Pure: nothing is fetched. `impersonation` when its symbol (look-alike letters folded) reads as a\n * catalog token on the same `chain` — the real one would be in the list, this is another contract —\n * or as a native coin or major stablecoin anywhere. A bridged token of another chain's list (JUP on\n * Solana, listed on Unichain) is not flagged.\n */\nexport function assessToken(info: TokenInfo, chain?: string): TokenAssessment {\n const risks: TokenRisk[] = [{ code: 'unlisted', level: 'caution', message: \"Not in the wallet's token list. Anyone can create a token with any name and logo: check the address with the project itself.\" }]\n const folded = foldSymbol(info.symbol)\n const lookalike = lookalikeOf(folded, chain)\n if (lookalike) {\n risks.push({ code: 'impersonation', level: 'danger', message: `It calls itself ${JSON.stringify(info.symbol)}, like ${lookalike}, but it is a different token at a different address.` })\n }\n if (!PLAIN.test(info.symbol) || !PLAIN.test(info.name) || info.symbol !== info.symbol.replace(INVISIBLE, '') || info.name !== info.name.replace(INVISIBLE, '')) {\n risks.push({ code: 'odd-characters', level: 'caution', message: 'Its symbol or name uses characters that can look like other letters, or invisible ones.' })\n }\n if (!info.symbol.trim()) risks.push({ code: 'no-symbol', level: 'caution', message: 'The token reports no symbol.' })\n if (info.totalSupply === 0n) risks.push({ code: 'zero-supply', level: 'caution', message: 'Nothing has been minted.' })\n if (info.decimals > 24) risks.push({ code: 'unusual-decimals', level: 'caution', message: `It uses ${info.decimals} decimals; amounts may display oddly.` })\n for (const flag of info.flags) {\n const r = FLAG_RISKS[flag]\n if (r) risks.push({ code: flag, ...r })\n }\n risks.sort((a, b) => (a.level === b.level ? 0 : a.level === 'danger' ? -1 : 1))\n return { level: risks.some((r) => r.level === 'danger') ? 'danger' : 'caution', risks }\n}\n","import type { IWalletAccountReadOnly, TokenFlag, TokenInfo } from '@anywalletkit/core'\nimport { catalogChainId, ccAssetByToken, isTokenAddress, type CcAsset } from '@anywalletkit/swap2-assets'\nimport { assessToken, type TokenAssessment } from './assess.js'\n\n/** One JSON value under one key — the shape every small store needs (AsyncStorage, chrome.storage, memory). */\nexport interface JsonStorage<T> {\n /** The stored value, or `null` on first run. */\n get(): Promise<T | null>\n /** Persist the value. */\n set(value: T): Promise<void>\n}\n\n/** In-memory storage for tests and smoke runs. */\nexport function memoryJsonStorage<T>(initial: T | null = null): JsonStorage<T> & { value: T | null } {\n const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T\n const s = {\n value: initial,\n async get() { return s.value === null ? null : clone(s.value) },\n async set(value: T) { s.value = clone(value) },\n }\n return s\n}\n\n/** A token the user added. `symbol` and `name` are what the token reports: display them, never match on them. */\nexport interface UserToken {\n /** CAIP-2 chain id, the catalog's key (`solana:mainnet`, `eip155:1`). */\n chain: string\n /** Contract (EVM, checksummed as read) or mint (Solana). The token's identity. */\n address: string\n symbol: string\n name: string\n decimals: number\n /** `erc20`, `spl` or `spl-token-2022`. */\n standard: string\n /** Facts read from the chain when it was added. */\n flags: TokenFlag[]\n /** When the user added it (ms since epoch). */\n addedAt: number\n}\n\n/** What {@link TokensTable} stores. */\nexport interface TokensState {\n v: 1\n tokens: UserToken[]\n}\n\n/** Codes of {@link TokensError}. */\nexport type TokensErrorCode = 'not-loaded' | 'unsupported-chain' | 'bad-address' | 'listed' | 'bad-token' | 'full'\n\n/** A refusal from the tokens table or {@link inspectToken}, with a machine-readable `code`. */\nexport class TokensError extends Error {\n readonly code: TokensErrorCode\n constructor(code: TokensErrorCode, message: string) {\n super(message)\n this.name = 'TokensError'\n this.code = code\n }\n}\n\nconst sameAddress = (chain: string, a: string, b: string) => (chain.startsWith('eip155:') ? a.toLowerCase() === b.toLowerCase() : a === b)\nconst FLAGS: ReadonlySet<string> = new Set<TokenFlag>(['upgradeable', 'mint-authority', 'freeze-authority', 'permanent-delegate', 'transfer-fee', 'transfer-hook', 'non-transferable', 'default-frozen', 'pausable'])\n\n/** A stored entry as it must be, or null (a hand-edited or corrupted entry is dropped, never trusted). */\nfunction validEntry(t: unknown): UserToken | null {\n if (!t || typeof t !== 'object') return null\n const e = t as Record<string, unknown>\n if (typeof e.chain !== 'string' || typeof e.address !== 'string' || !isTokenAddress(e.chain, e.address)) return null\n if (typeof e.decimals !== 'number' || !Number.isInteger(e.decimals) || e.decimals < 0 || e.decimals > 77) return null\n if (typeof e.symbol !== 'string' || typeof e.name !== 'string' || typeof e.standard !== 'string' || typeof e.addedAt !== 'number') return null\n if (!Array.isArray(e.flags) || !e.flags.every((f) => typeof f === 'string' && FLAGS.has(f))) return null\n return {\n chain: e.chain, address: e.address, symbol: e.symbol.slice(0, 128), name: e.name.slice(0, 128), decimals: e.decimals,\n standard: e.standard, flags: [...e.flags] as TokenFlag[], addedAt: e.addedAt,\n }\n}\n\n/** The result of looking a token up before adding it. */\nexport type TokenInspection =\n | { listed: CcAsset }\n | { listed?: undefined; info: TokenInfo; assessment: TokenAssessment; token: UserToken }\n\n/**\n * Read a token from the chain through `account` (its chain decides where) and assess it. A token the\n * catalog already lists comes back as `{ listed }`: nothing to add. Otherwise the token, ready for\n * {@link TokensTable.add}, and the warnings to show first. Throws {@link TokensError}\n * (`unsupported-chain`, `bad-address`) or the chain package's `NotATokenError`.\n */\nexport async function inspectToken(\n account: Pick<IWalletAccountReadOnly, 'chain' | 'getTokenInfo'> & { getChainId?: () => Promise<number | bigint> },\n address: string,\n now: () => number = Date.now,\n): Promise<TokenInspection> {\n let reported = account.chain\n // An EVM account created without a chain id reports 'eip155:unknown' until it has asked its RPC:\n // ask now, or the catalog check (already listed? a look-alike of this chain's tokens?) would miss.\n if (reported === 'eip155:unknown') {\n if (typeof account.getChainId !== 'function') throw new TokensError('unsupported-chain', 'The account does not know its chain id; create it with chainId.')\n reported = `eip155:${String(await account.getChainId())}`\n }\n const chain = catalogChainId(reported)\n if (!chain.startsWith('eip155:') && !chain.startsWith('solana:')) throw new TokensError('unsupported-chain', `Adding tokens is supported on EVM chains and Solana, not ${account.chain}.`)\n const ref = address.trim()\n if (!isTokenAddress(chain, ref)) throw new TokensError('bad-address', `${JSON.stringify(address)} is not a token address on ${chain}.`)\n const listed = ccAssetByToken(chain, ref)\n if (listed) return { listed }\n if (typeof account.getTokenInfo !== 'function') throw new TokensError('unsupported-chain', `This ${account.chain} account cannot read token info.`)\n const info = await account.getTokenInfo(ref)\n const token: UserToken = {\n chain, address: info.address, symbol: info.symbol.slice(0, 128), name: info.name.slice(0, 128), decimals: info.decimals,\n standard: info.standard, flags: [...info.flags], addedAt: now(),\n }\n return { info, assessment: assessToken(info, chain), token }\n}\n\n/**\n * The swap options that name a user token as the source: its address and decimals. Pass them to an\n * engine created with `allowUnlistedTokens: true`.\n */\nexport function swapSource(token: Pick<UserToken, 'address' | 'decimals'>): { fromToken: string; fromTokenDecimals: number } {\n return { fromToken: token.address, fromTokenDecimals: token.decimals }\n}\n\n/**\n * The user's own tokens, over any JSON storage: load once at cold start, then read synchronously.\n * Writes queue behind each other; a failed save leaves memory as stored. Tokens the catalog lists are\n * refused (they are already there), and so are addresses that are not EVM contracts or Solana mints.\n */\nexport class TokensTable {\n private _state: TokensState | null = null\n private _loading: Promise<TokensState> | null = null\n private _writes: Promise<unknown> = Promise.resolve()\n private readonly listeners = new Set<() => void>()\n readonly maxTokens: number\n\n constructor(private readonly storage: JsonStorage<TokensState>, options: { maxTokens?: number } = {}) {\n this.maxTokens = options.maxTokens ?? 200\n }\n\n /** Read the stored list. Call once before the sync reads; a failed read throws and leaves the table unloaded. */\n async load(): Promise<void> {\n await this.state()\n }\n\n /** Called after every successful write. Returns the unsubscribe function. */\n subscribe(fn: () => void): () => void {\n this.listeners.add(fn)\n return () => { this.listeners.delete(fn) }\n }\n\n /** The user's tokens, oldest first; only those on `chain` when given. */\n list(chain?: string): UserToken[] {\n const s = this.loaded()\n const want = chain === undefined ? undefined : catalogChainId(chain)\n return s.tokens.filter((t) => want === undefined || t.chain === want).map((t) => ({ ...t, flags: [...t.flags] }))\n }\n\n /** The user token at `address` on `chain`, if added. */\n get(chain: string, address: string): UserToken | undefined {\n const c = catalogChainId(chain)\n const t = this.loaded().tokens.find((x) => x.chain === c && sameAddress(c, x.address, address))\n return t ? { ...t, flags: [...t.flags] } : undefined\n }\n\n /** Add (or refresh) a token — usually `inspection.token` after the user accepted the warnings. */\n async add(token: UserToken): Promise<UserToken> {\n const entry = validEntry({ ...token, chain: catalogChainId(token.chain) })\n if (!entry) throw new TokensError('bad-token', 'Not a valid token entry (address, decimals 0–77, symbol, name, standard, flags).')\n if (ccAssetByToken(entry.chain, entry.address)) throw new TokensError('listed', `${entry.address} is already in the wallet's token list.`)\n await this.update((s) => {\n const rest = s.tokens.filter((t) => !(t.chain === entry.chain && sameAddress(entry.chain, t.address, entry.address)))\n if (rest.length >= this.maxTokens) throw new TokensError('full', `At most ${this.maxTokens} tokens can be added.`)\n return { v: 1, tokens: [...rest, entry] }\n })\n return { ...entry, flags: [...entry.flags] }\n }\n\n /** Remove a token. Returns whether it was there. */\n async remove(chain: string, address: string): Promise<boolean> {\n const c = catalogChainId(chain)\n let removed = false\n await this.update((s) => {\n const rest = s.tokens.filter((t) => !(t.chain === c && sameAddress(c, t.address, address)))\n removed = rest.length !== s.tokens.length\n return { v: 1, tokens: rest }\n })\n return removed\n }\n\n private loaded(): TokensState {\n if (!this._state) throw new TokensError('not-loaded', 'Call load() before reading the tokens table.')\n return this._state\n }\n\n private async state(): Promise<TokensState> {\n if (this._state) return this._state\n this._loading ??= (async () => {\n let stored: TokensState | null\n try {\n stored = await this.storage.get()\n } catch (e) {\n // A failed read is not an empty list: the next write would erase the user's tokens.\n this._loading = null\n throw e\n }\n const tokens = stored && stored.v === 1 && Array.isArray(stored.tokens)\n ? stored.tokens.map(validEntry).filter((t): t is UserToken => t !== null)\n : []\n this._state = { v: 1, tokens }\n return this._state\n })()\n return this._loading\n }\n\n private update(change: (s: TokensState) => TokensState): Promise<void> {\n const run = this._writes.then(async () => {\n const next = change(await this.state())\n await this.storage.set(next)\n this._state = next\n for (const fn of this.listeners) {\n try { fn() } catch { /* a listener's failure is its own */ }\n }\n })\n this._writes = run.catch(() => undefined)\n return run\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,0BAA0D;AA8B1D,IAAM,aAAsF;AAAA,EAC1F,eAAe,EAAE,OAAO,WAAW,SAAS,0CAA0C;AAAA,EACtF,kBAAkB,EAAE,OAAO,WAAW,SAAS,wCAAwC;AAAA,EACvF,oBAAoB,EAAE,OAAO,WAAW,SAAS,sCAAsC;AAAA,EACvF,sBAAsB,EAAE,OAAO,UAAU,SAAS,yDAAyD;AAAA,EAC3G,gBAAgB,EAAE,OAAO,WAAW,SAAS,2CAA2C;AAAA,EACxF,iBAAiB,EAAE,OAAO,UAAU,SAAS,mFAAmF;AAAA,EAChI,oBAAoB,EAAE,OAAO,UAAU,SAAS,6CAA6C;AAAA,EAC7F,kBAAkB,EAAE,OAAO,WAAW,SAAS,+DAA+D;AAAA,EAC9G,YAAY,EAAE,OAAO,WAAW,SAAS,uCAAuC;AAClF;AAGA,IAAM,cAAgD;AAAA,EACpD,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