@usebutr/wallet-standard-shared 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,11 +1,10 @@
1
- import { Account, ChainBase, WalletAdapter } from "@usebutr/core";
2
-
1
+ import { Account, ChainBase, ConnectorEvent, WalletAdapter, buildAccount } from "@usebutr/core";
3
2
  //#region src/types.d.ts
4
3
  /**
5
4
  * Minimal type surface for the Wallet Standard protocol that every
6
5
  * platform-specific package (`@usebutr/svm`, `@usebutr/sui`,
7
6
  * `@usebutr/bitcoin`) shares. Declared inline so butr stays
8
- * self-contained at the type level — the actual `@wallet-standard/app`
7
+ * self-contained at the type level; the actual `@wallet-standard/app`
9
8
  * package is dynamic-imported at runtime, and apps that don't enable
10
9
  * Wallet Standard discovery never resolve it.
11
10
  *
@@ -18,7 +17,8 @@ import { Account, ChainBase, WalletAdapter } from "@usebutr/core";
18
17
  type WalletStandardWalletAccount = {
19
18
  address: string;
20
19
  chains: ReadonlyArray<string>;
21
- features: ReadonlyArray<string>; /** Public key bytes — Wallet Standard ships these as Uint8Array. */
20
+ features: ReadonlyArray<string>;
21
+ /** Public key bytes; Wallet Standard ships these as Uint8Array. */
22
22
  publicKey?: Uint8Array;
23
23
  };
24
24
  type WalletStandardWallet = {
@@ -72,17 +72,14 @@ type StandardEventsFeature = {
72
72
  declare const slugify: (platformPrefix: string, name: string) => string;
73
73
  /**
74
74
  * Read a Wallet Standard feature off a wallet, returning `undefined`
75
- * when absent. The caller narrows the unknown payload to the
76
- * platform-specific feature shape at use sites.
75
+ * when absent. `features` is a reverse-DNS-keyed registry typed
76
+ * `Record<string, unknown>` by the spec, so the caller declares the
77
+ * concrete feature shape it expects; this accessor is the single
78
+ * boundary where that dynamism is acknowledged. The `T` parameter is
79
+ * intentionally caller-supplied (not inferable) and the assertion is
80
+ * unavoidable for an untyped registry.
77
81
  */
78
82
  declare const getFeature: <T>(wallet: WalletStandardWallet, name: string) => T | undefined;
79
- /**
80
- * Build butr's `Account` shape from a Wallet Standard account address
81
- * and a resolved `ChainBase`. The composite id (`<chain>:<address>`)
82
- * is what butr's reducer uses to compare accounts across refreshes,
83
- * so keep this format identical across platforms.
84
- */
85
- declare const buildAccount: (address: string, chain: ChainBase) => Account;
86
83
  /**
87
84
  * Pick the first address out of a wallet's accounts array, returning
88
85
  * `null` when the wallet currently exposes none.
@@ -98,12 +95,81 @@ declare const pickFirstAddress: (accounts: ReadonlyArray<WalletStandardWalletAcc
98
95
  */
99
96
  declare const pickAccountByAddress: (accounts: ReadonlyArray<WalletStandardWalletAccount>, address: string) => WalletStandardWalletAccount | undefined;
100
97
  //#endregion
98
+ //#region src/adapter-core.d.ts
99
+ type WalletStandardCoreInput = {
100
+ /** CAIP-2 prefix including its colon (`solana:`, `sui:`, `bip122:`). */
101
+ chainPrefix: string;
102
+ /** Stable adapter id. Each platform package owns its own slug prefix. */
103
+ id: string;
104
+ /** How this adapter names itself in errors (`Bitcoin`, `SVM`, `Sui`). */
105
+ label: string;
106
+ /** CAIP-2 namespace without its colon. */
107
+ namespace: string;
108
+ /** How the chain family reads in errors (`Bitcoin`, `Solana`, `Sui`). */
109
+ platform: string;
110
+ /** Chain ids worth preferring over a bare prefix match. Matched against
111
+ * the wallet's own ordering, so a wallet listing `mainnet-beta` before
112
+ * `mainnet` keeps the chain it advertised first. */
113
+ preferredChainIds: ReadonlyArray<string>;
114
+ /** Called with a function that pushes a synthetic `disconnected` event
115
+ * to all current subscribers. The discovery layer invokes it on Wallet
116
+ * Standard `unregister`. */
117
+ registerDisconnector?: (emit: () => void) => void;
118
+ /** Re-point the active chain when the wallet reports a `chains` change.
119
+ * Polkadot opts out: its wallets advertise a single relay chain, so a
120
+ * re-point would only ever move the adapter off the chain it resolved. */
121
+ trackChainChanges: boolean;
122
+ wallet: WalletStandardWallet;
123
+ };
124
+ type WalletStandardCore = {
125
+ /** Chains the wallet advertises in this namespace; feeds capability gating. */
126
+ chainCount: number;
127
+ connect: (opts?: {
128
+ silent?: boolean;
129
+ }) => Promise<void>;
130
+ /** Active CAIP-2 chain id, for features that take a per-call `chain`. */
131
+ currentChainId: () => string;
132
+ disconnect: () => Promise<void>;
133
+ getAccount: () => Promise<Account | null>;
134
+ getAccounts: () => Promise<Array<Account>>;
135
+ getSigner: () => Promise<unknown>;
136
+ /** Whether the wallet advertises `standard:events`; feeds capability gating. */
137
+ hasEvents: boolean;
138
+ icon: string | undefined;
139
+ id: string;
140
+ name: string;
141
+ /** Wallet Standard account a call should route through: the one matching
142
+ * `account`, else the wallet's first exposed account. */
143
+ resolveAccount: (account?: {
144
+ walletAddress: string;
145
+ }) => WalletStandardWalletAccount;
146
+ subscribe: (listener: (event: ConnectorEvent) => void) => () => void;
147
+ switchChain: (chain: ChainBase) => Promise<void>;
148
+ /** butr chain for the active chain id, for responses that mint their own
149
+ * `Account` (Sign-In-With-Solana) rather than going through `getAccounts`. */
150
+ toChain: () => ChainBase;
151
+ };
152
+ /**
153
+ * Session plumbing every Wallet Standard platform adapter repeats: chain
154
+ * resolution, the connect/disconnect handshake, account reads, the local
155
+ * listener set that lets `switchChain` synthesise `accountChanged`, and
156
+ * the `standard:events` bridge. Returns `null` for wallets butr can't
157
+ * drive (no chain in this namespace, or no `standard:connect`), which is
158
+ * the same `null` each platform adapter returns to its caller.
159
+ *
160
+ * Platform packages keep what genuinely differs: which features they read
161
+ * off the wallet, how they encode transactions and messages, and their
162
+ * balance units. `getSigner` hands back the raw Wallet Standard wallet so
163
+ * consumers can wrap it in their own signing library.
164
+ */
165
+ declare const createWalletStandardCore: ({ chainPrefix, id, label, namespace, platform, preferredChainIds, registerDisconnector, trackChainChanges, wallet }: WalletStandardCoreInput) => WalletStandardCore | null;
166
+ //#endregion
101
167
  //#region src/discovery.d.ts
102
168
  /**
103
169
  * Callback supplied by per-platform discovery to build a `WalletAdapter`
104
170
  * out of a Wallet Standard wallet announcement.
105
171
  *
106
- * Returns `null` when the wallet doesn't advertise this platform — that
172
+ * Returns `null` when the wallet doesn't advertise this platform; that
107
173
  * lets a multi-chain wallet (e.g. Phantom: SVM + EVM + Sui + Bitcoin)
108
174
  * produce one adapter per platform without each builder needing to know
109
175
  * about the others.
@@ -119,7 +185,7 @@ type WalletStandardAdapterBuilder = (wallet: WalletStandardWallet, registerDisco
119
185
  * into butr `WalletAdapter`s using a per-platform `build` callback.
120
186
  *
121
187
  * **Shared machinery** every platform package needs:
122
- * - Dynamic import of `@wallet-standard/app` (optional peer dep —
188
+ * - Dynamic import of `@wallet-standard/app` (optional peer dep;
123
189
  * failure to resolve quietly disables discovery so consumers who
124
190
  * don't install it pay nothing).
125
191
  * - Cancellation: the returned unsubscribe is safe to call before the
@@ -136,10 +202,10 @@ type WalletStandardAdapterBuilder = (wallet: WalletStandardWallet, registerDisco
136
202
  * - The capability resolver, the feature decoding, the chain coercion.
137
203
  *
138
204
  * Disconnectors are keyed by the wallet object itself (identity equality),
139
- * not by adapter id — Wallet Standard's `register` / `unregister` emit
205
+ * not by adapter id; Wallet Standard's `register` / `unregister` emit
140
206
  * the same wallet object, so identity is the cheapest stable key.
141
207
  */
142
208
  declare const discoverWalletStandard: (onAdapter: (adapter: WalletAdapter) => void, build: WalletStandardAdapterBuilder) => (() => void);
143
209
  //#endregion
144
- export { type StandardConnectFeature, type StandardDisconnectFeature, type StandardEventsFeature, type StandardEventsListener, type WalletStandardAdapterBuilder, type WalletStandardAppModule, type WalletStandardWallet, type WalletStandardWalletAccount, type WalletsApp, buildAccount, discoverWalletStandard, getFeature, pickAccountByAddress, pickFirstAddress, slugify };
210
+ export { type StandardConnectFeature, type StandardDisconnectFeature, type StandardEventsFeature, type StandardEventsListener, type WalletStandardAdapterBuilder, type WalletStandardAppModule, type WalletStandardCore, type WalletStandardWallet, type WalletStandardWalletAccount, type WalletsApp, buildAccount, createWalletStandardCore, discoverWalletStandard, getFeature, pickAccountByAddress, pickFirstAddress, slugify };
145
211
  //# sourceMappingURL=index.d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oBAAA,GACJ,QAAA,EAAU,aAAA,CAAc,2BAAA,GACxB,OAAA,aACC,2BAAA;;;;;;;;;;;;;;;;;KC1CE,4BAAA,IACH,MAAA,EAAQ,oBAAA,EACR,oBAAA,GAAuB,IAAA,0BACpB,aAAa;;;AFNM;AAAA;;;;;;;;;;;;;;;;;;;;;;cEiClB,sBAAA,GACJ,SAAA,GAAY,OAAA,EAAS,aAAA,WACrB,KAAA,EAAO,4BAA4B"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/primitives.ts","../src/adapter-core.ts","../src/discovery.ts"],"mappings":";;;;;;;;;;;;;;;;KAeK;EACH;EACA,QAAQ;EACR,UAAU;;EAEV,YAAY;;KAGT;EACH,UAAU,cAAc;EACxB,QAAQ;;;EAGR,UAAU,SAAS;EACnB;EACA;EACA;;KAGG;EACH,WAAW,cAAc;EACzB,KACE,kCACA,cAAc,SAAS,cAAc;;KAIpC;EACH,kBAAkB;;KAGf;EACH,UAAU;IAAU;QAAuB;IACzC,UAAU,cAAc;;;KAIvB;EACH,kBAAkB;;KAGf,0BAA0B;EAC7B,WAAW,cAAc;EACzB,SAAS;EACT,WAAW;;KAGR;EACH,KAAK,iBAAiB,UAAU;;;;;;;;;;;;;;;cClD5B,UAAW,wBAAwB;;;;;;;;;;cAkBnC,aAAc,GAAG,QAAQ,sBAAsB,iBAAe;;;;;cAa9D,mBAAoB,UAAU,cAAc;;;;;;;;;cAa5C,uBACJ,UAAU,cAAc,8BACxB,oBACC;;;KChDE;;EAEH;;EAEA;;EAEA;;EAEA;;EAEA;;;;EAIA,mBAAmB;;;;EAInB,wBAAwB;;;;EAIxB;EACA,QAAQ;;KAGL;;EAEH;EACA,UAAU;IAAS;QAAuB;;EAE1C;EACA,kBAAkB;EAClB,kBAAkB,QAAQ;EAC1B,mBAAmB,QAAQ,MAAM;EACjC,iBAAiB;;EAEjB;EACA;EACA;EACA;;;EAGA,iBAAiB;IAAY;QAA4B;EACzD,YAAY,WAAW,OAAO;EAC9B,cAAc,OAAO,cAAc;;;EAGnC,eAAe;;;;;;;;;;;;;;;cAgBX,6BAA4B,aAAA,IAAA,OAAA,WAAA,UAAA,mBAAA,sBAAA,mBAAA,UAU/B,4BAA0B;;;;;;;;;;;;;;;;;KCjExB,gCACH,QAAQ,sBACR,uBAAuB,8BACpB;;;;;;;;;;;;;;;;;;;;;;;;;;cA2BC,yBACJ,YAAY,SAAS,wBACrB,OAAO"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { logWarn } from "@usebutr/core";
1
+ import { buildAccount, buildAccount as buildAccount$1, logWarn, sanitizeIcon } from "@usebutr/core";
2
2
 
3
3
  //#region src/primitives.ts
4
4
  /**
@@ -17,31 +17,25 @@ const slugify = (platformPrefix, name) => {
17
17
  };
18
18
  /**
19
19
  * Read a Wallet Standard feature off a wallet, returning `undefined`
20
- * when absent. The caller narrows the unknown payload to the
21
- * platform-specific feature shape at use sites.
20
+ * when absent. `features` is a reverse-DNS-keyed registry typed
21
+ * `Record<string, unknown>` by the spec, so the caller declares the
22
+ * concrete feature shape it expects; this accessor is the single
23
+ * boundary where that dynamism is acknowledged. The `T` parameter is
24
+ * intentionally caller-supplied (not inferable) and the assertion is
25
+ * unavoidable for an untyped registry.
22
26
  */
23
27
  const getFeature = (wallet, name) => {
24
28
  const feature = wallet.features[name];
25
- return feature ? feature : void 0;
29
+ if (typeof feature !== "object" || feature === null) return;
30
+ return feature;
26
31
  };
27
32
  /**
28
- * Build butr's `Account` shape from a Wallet Standard account address
29
- * and a resolved `ChainBase`. The composite id (`<chain>:<address>`)
30
- * is what butr's reducer uses to compare accounts across refreshes,
31
- * so keep this format identical across platforms.
32
- */
33
- const buildAccount = (address, chain) => ({
34
- chain,
35
- id: `${chain.id}:${address}`,
36
- walletAddress: address
37
- });
38
- /**
39
33
  * Pick the first address out of a wallet's accounts array, returning
40
34
  * `null` when the wallet currently exposes none.
41
35
  */
42
36
  const pickFirstAddress = (accounts) => {
43
37
  const first = accounts[0];
44
- return first ? first.address : null;
38
+ return first === void 0 ? null : first.address;
45
39
  };
46
40
  /**
47
41
  * Look up a wallet account by address, falling back to the first
@@ -53,6 +47,130 @@ const pickFirstAddress = (accounts) => {
53
47
  */
54
48
  const pickAccountByAddress = (accounts, address) => accounts.find((a) => a.address === address) ?? accounts[0];
55
49
 
50
+ //#endregion
51
+ //#region src/adapter-core.ts
52
+ /**
53
+ * Session plumbing every Wallet Standard platform adapter repeats: chain
54
+ * resolution, the connect/disconnect handshake, account reads, the local
55
+ * listener set that lets `switchChain` synthesise `accountChanged`, and
56
+ * the `standard:events` bridge. Returns `null` for wallets butr can't
57
+ * drive (no chain in this namespace, or no `standard:connect`), which is
58
+ * the same `null` each platform adapter returns to its caller.
59
+ *
60
+ * Platform packages keep what genuinely differs: which features they read
61
+ * off the wallet, how they encode transactions and messages, and their
62
+ * balance units. `getSigner` hands back the raw Wallet Standard wallet so
63
+ * consumers can wrap it in their own signing library.
64
+ */
65
+ const createWalletStandardCore = ({ chainPrefix, id, label, namespace, platform, preferredChainIds, registerDisconnector, trackChainChanges, wallet }) => {
66
+ const pickChain = (chains) => chains.find((c) => preferredChainIds.includes(c)) ?? chains.find((c) => c.startsWith(chainPrefix)) ?? null;
67
+ const initialChainId = pickChain(wallet.chains);
68
+ if (initialChainId === null) return null;
69
+ const connect = getFeature(wallet, "standard:connect");
70
+ if (connect === void 0) return null;
71
+ const disconnect = getFeature(wallet, "standard:disconnect");
72
+ const events = getFeature(wallet, "standard:events");
73
+ let currentChainId = initialChainId;
74
+ const toChain = () => ({
75
+ id: currentChainId,
76
+ name: wallet.name,
77
+ namespace,
78
+ reference: currentChainId.slice(chainPrefix.length)
79
+ });
80
+ const listeners = /* @__PURE__ */ new Set();
81
+ const notifyAccountChanged = () => {
82
+ if (wallet.accounts.length === 0) return;
83
+ const chain = toChain();
84
+ const built = wallet.accounts.map((a) => buildAccount$1(a.address, chain));
85
+ const first = built[0];
86
+ if (first === void 0) return;
87
+ for (const listener of listeners) listener({
88
+ account: first,
89
+ accounts: built,
90
+ type: "accountChanged"
91
+ });
92
+ };
93
+ registerDisconnector?.(() => {
94
+ for (const listener of listeners) listener({ type: "disconnected" });
95
+ });
96
+ return {
97
+ chainCount: wallet.chains.filter((c) => c.startsWith(chainPrefix)).length,
98
+ async connect(opts) {
99
+ await connect.connect(opts?.silent === true ? { silent: true } : void 0);
100
+ },
101
+ currentChainId: () => currentChainId,
102
+ async disconnect() {
103
+ if (disconnect !== void 0) try {
104
+ await disconnect.disconnect();
105
+ } catch (error) {
106
+ logWarn(`[butr] ${label} Wallet Standard disconnect threw:`, error);
107
+ }
108
+ },
109
+ getAccount: () => {
110
+ const address = pickFirstAddress(wallet.accounts);
111
+ return Promise.resolve(address === null ? null : buildAccount$1(address, toChain()));
112
+ },
113
+ getAccounts: () => {
114
+ const chain = toChain();
115
+ return Promise.resolve(wallet.accounts.map((a) => buildAccount$1(a.address, chain)));
116
+ },
117
+ getSigner: () => Promise.resolve(wallet),
118
+ hasEvents: Boolean(events),
119
+ icon: sanitizeIcon(wallet.icon),
120
+ id,
121
+ name: wallet.name,
122
+ resolveAccount: (account) => {
123
+ const wsAccount = account ? pickAccountByAddress(wallet.accounts, account.walletAddress) : wallet.accounts[0];
124
+ if (wsAccount === void 0) throw new Error("No connected account");
125
+ return wsAccount;
126
+ },
127
+ subscribe(listener) {
128
+ listeners.add(listener);
129
+ let unsubWallet = null;
130
+ if (events !== void 0) {
131
+ const unsub = events.on("change", (changes) => {
132
+ if (trackChainChanges && changes.chains !== void 0) {
133
+ const next = pickChain(changes.chains);
134
+ if (next !== null) currentChainId = next;
135
+ }
136
+ if (changes.accounts !== void 0) {
137
+ if (changes.accounts.length === 0) {
138
+ listener({ type: "disconnected" });
139
+ return;
140
+ }
141
+ const chain = toChain();
142
+ const built = changes.accounts.map((a) => buildAccount$1(a.address, chain));
143
+ const first = built[0];
144
+ if (first === void 0) return;
145
+ listener({
146
+ account: first,
147
+ accounts: built,
148
+ type: "accountChanged"
149
+ });
150
+ return;
151
+ }
152
+ if (trackChainChanges && changes.chains !== void 0) notifyAccountChanged();
153
+ });
154
+ unsubWallet = () => {
155
+ unsub();
156
+ };
157
+ }
158
+ return () => {
159
+ listeners.delete(listener);
160
+ unsubWallet?.();
161
+ };
162
+ },
163
+ switchChain: (chain) => {
164
+ if (chain.namespace !== namespace) throw new Error(`${label} adapter received non-${platform} chain "${chain.id}". Pass a chain with namespace "${namespace}".`);
165
+ if (!wallet.chains.includes(chain.id)) throw new Error(`Wallet ${wallet.name} does not advertise chain "${chain.id}". Available: ${wallet.chains.join(", ")}`);
166
+ currentChainId = chain.id;
167
+ notifyAccountChanged();
168
+ return Promise.resolve();
169
+ },
170
+ toChain
171
+ };
172
+ };
173
+
56
174
  //#endregion
57
175
  //#region src/discovery.ts
58
176
  let warnedMissingApp = false;
@@ -61,7 +179,7 @@ let warnedMissingApp = false;
61
179
  * into butr `WalletAdapter`s using a per-platform `build` callback.
62
180
  *
63
181
  * **Shared machinery** every platform package needs:
64
- * - Dynamic import of `@wallet-standard/app` (optional peer dep —
182
+ * - Dynamic import of `@wallet-standard/app` (optional peer dep;
65
183
  * failure to resolve quietly disables discovery so consumers who
66
184
  * don't install it pay nothing).
67
185
  * - Cancellation: the returned unsubscribe is safe to call before the
@@ -78,7 +196,7 @@ let warnedMissingApp = false;
78
196
  * - The capability resolver, the feature decoding, the chain coercion.
79
197
  *
80
198
  * Disconnectors are keyed by the wallet object itself (identity equality),
81
- * not by adapter id — Wallet Standard's `register` / `unregister` emit
199
+ * not by adapter id; Wallet Standard's `register` / `unregister` emit
82
200
  * the same wallet object, so identity is the cheapest stable key.
83
201
  */
84
202
  const discoverWalletStandard = (onAdapter, build) => {
@@ -87,7 +205,9 @@ const discoverWalletStandard = (onAdapter, build) => {
87
205
  (async () => {
88
206
  let mod;
89
207
  try {
90
- mod = await import("@wallet-standard/app");
208
+ const imported = await import("@wallet-standard/app");
209
+ if (typeof imported !== "object" || imported === null || !("getWallets" in imported) || typeof imported.getWallets !== "function") throw new Error("@wallet-standard/app has no getWallets export");
210
+ mod = imported;
91
211
  } catch (error) {
92
212
  if (!warnedMissingApp) {
93
213
  warnedMissingApp = true;
@@ -133,5 +253,5 @@ const discoverWalletStandard = (onAdapter, build) => {
133
253
  };
134
254
 
135
255
  //#endregion
136
- export { buildAccount, discoverWalletStandard, getFeature, pickAccountByAddress, pickFirstAddress, slugify };
256
+ export { buildAccount, createWalletStandardCore, discoverWalletStandard, getFeature, pickAccountByAddress, pickFirstAddress, slugify };
137
257
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/primitives.ts","../src/discovery.ts"],"sourcesContent":["import type { Account, ChainBase } from \"@usebutr/core\";\n\nimport type { WalletStandardWallet, WalletStandardWalletAccount } from \"./types\";\n\n/**\n * Convert a wallet name into a stable kebab-case adapter id, scoped by\n * a platform prefix so adapters from different platforms (Phantom SVM,\n * Phantom Sui, Phantom BTC) coexist in the pool without colliding on\n * the shared `getWallets()` bus.\n *\n * @example\n * slugify(\"svm\", \"Phantom\") // \"wallet-standard:svm-phantom\"\n * slugify(\"sui\", \"Sui Wallet\") // \"wallet-standard:sui-sui-wallet\"\n * slugify(\"btc\", \"Phantom\") // \"wallet-standard:btc-phantom\"\n */\nconst slugify = (platformPrefix: string, name: string): string => {\n const slug = name\n .trim()\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/gv, \"-\");\n return `wallet-standard:${platformPrefix}-${slug}`;\n};\n\n/**\n * Read a Wallet Standard feature off a wallet, returning `undefined`\n * when absent. The caller narrows the unknown payload to the\n * platform-specific feature shape at use sites.\n */\nconst getFeature = <T>(wallet: WalletStandardWallet, name: string): T | undefined => {\n const feature = wallet.features[name];\n return feature ? (feature as T) : undefined;\n};\n\n/**\n * Build butr's `Account` shape from a Wallet Standard account address\n * and a resolved `ChainBase`. The composite id (`<chain>:<address>`)\n * is what butr's reducer uses to compare accounts across refreshes,\n * so keep this format identical across platforms.\n */\nconst buildAccount = (address: string, chain: ChainBase): Account => ({\n chain,\n id: `${chain.id}:${address}`,\n walletAddress: address,\n});\n\n/**\n * Pick the first address out of a wallet's accounts array, returning\n * `null` when the wallet currently exposes none.\n */\nconst pickFirstAddress = (accounts: ReadonlyArray<WalletStandardWalletAccount>): string | null => {\n const first = accounts[0];\n return first ? first.address : null;\n};\n\n/**\n * Look up a wallet account by address, falling back to the first\n * exposed account when the requested address isn't present.\n *\n * Used by per-call routing in `sendTx` / `signMessage`: callers pass\n * an `account` from `ConnectedWallet.accounts` to sign with a non-\n * active address; the wallet's `accounts[]` is the source of truth.\n */\nconst pickAccountByAddress = (\n accounts: ReadonlyArray<WalletStandardWalletAccount>,\n address: string,\n): WalletStandardWalletAccount | undefined =>\n accounts.find((a) => a.address === address) ?? accounts[0];\n\nexport { buildAccount, getFeature, pickAccountByAddress, pickFirstAddress, slugify };\n","import type { WalletAdapter } from \"@usebutr/core\";\nimport { logWarn } from \"@usebutr/core\";\n\nimport type { WalletStandardAppModule, WalletStandardWallet } from \"./types\";\n\n// Warn once per process: every platform calls this, so a missing optional peer\n// dep would otherwise log one identical line per chain.\nlet warnedMissingApp = false;\n\n/**\n * Callback supplied by per-platform discovery to build a `WalletAdapter`\n * out of a Wallet Standard wallet announcement.\n *\n * Returns `null` when the wallet doesn't advertise this platform — that\n * lets a multi-chain wallet (e.g. Phantom: SVM + EVM + Sui + Bitcoin)\n * produce one adapter per platform without each builder needing to know\n * about the others.\n *\n * The second argument is a hook the builder calls during construction\n * to wire a synthetic `disconnected` event into its subscriber set.\n * The discovery loop fires the registered emitter when Wallet Standard\n * announces `unregister` for that wallet.\n */\ntype WalletStandardAdapterBuilder = (\n wallet: WalletStandardWallet,\n registerDisconnector: (emit: () => void) => void,\n) => WalletAdapter | null;\n\n/**\n * Subscribe to Wallet Standard announcements and turn matching wallets\n * into butr `WalletAdapter`s using a per-platform `build` callback.\n *\n * **Shared machinery** every platform package needs:\n * - Dynamic import of `@wallet-standard/app` (optional peer dep —\n * failure to resolve quietly disables discovery so consumers who\n * don't install it pay nothing).\n * - Cancellation: the returned unsubscribe is safe to call before the\n * dynamic import has resolved.\n * - Dedupe by adapter id, so re-announcements don't double-emit.\n * - `unregister` integration: when an extension is removed mid-session,\n * fire the disconnector the builder registered so connected pool\n * entries on the consumer side tear down cleanly.\n *\n * **What's platform-specific** lives entirely in `build`:\n * - Which `wallet.chains` to accept.\n * - Which features to gate on.\n * - The `id` slug prefix (use `slugify(prefix, wallet.name)`).\n * - The capability resolver, the feature decoding, the chain coercion.\n *\n * Disconnectors are keyed by the wallet object itself (identity equality),\n * not by adapter id — Wallet Standard's `register` / `unregister` emit\n * the same wallet object, so identity is the cheapest stable key.\n */\nconst discoverWalletStandard = (\n onAdapter: (adapter: WalletAdapter) => void,\n build: WalletStandardAdapterBuilder,\n): (() => void) => {\n let cancelled = false;\n let internalUnsub: (() => void) | null = null;\n\n void (async () => {\n let mod: WalletStandardAppModule;\n try {\n mod = (await import(\"@wallet-standard/app\")) as unknown as WalletStandardAppModule;\n } catch (error) {\n if (!warnedMissingApp) {\n warnedMissingApp = true;\n logWarn(\n \"[butr] Wallet Standard wallet discovery is disabled: `@wallet-standard/app` could not be loaded. Install it (`npm i @wallet-standard/app`) to detect Wallet Standard wallets.\",\n error,\n );\n }\n return;\n }\n if (cancelled) {\n return;\n }\n\n const seenIds = new Set<string>();\n // wallet object → emitter that pushes synthetic `disconnected` to\n // this wallet's adapter's subscribers. Identity-keyed so the\n // unregister handler can find the right emitter cheaply.\n const disconnectors = new Map<WalletStandardWallet, () => void>();\n\n const tryAdd = (wallet: WalletStandardWallet) => {\n const adapter = build(wallet, (emit) => {\n disconnectors.set(wallet, emit);\n });\n if (!adapter || seenIds.has(adapter.id)) {\n return;\n }\n seenIds.add(adapter.id);\n onAdapter(adapter);\n };\n\n const app = mod.getWallets();\n for (const wallet of app.get()) {\n tryAdd(wallet);\n }\n\n const offRegister = app.on(\"register\", (...wallets) => {\n for (const wallet of wallets) {\n tryAdd(wallet);\n }\n });\n const offUnregister = app.on(\"unregister\", (...wallets) => {\n for (const wallet of wallets) {\n const emit = disconnectors.get(wallet);\n if (emit) {\n emit();\n disconnectors.delete(wallet);\n }\n }\n });\n internalUnsub = () => {\n offRegister();\n offUnregister();\n };\n })();\n\n return () => {\n cancelled = true;\n internalUnsub?.();\n internalUnsub = null;\n };\n};\n\nexport type { WalletStandardAdapterBuilder };\nexport { discoverWalletStandard };\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAM,WAAW,gBAAwB,SAAyB;CAKhE,OAAO,mBAAmB,eAAe,GAJ5B,KACV,KAAK,CAAC,CACN,YAAY,CAAC,CACb,2BAAW,6BAAa,GAAG,GACiB;AACjD;;;;;;AAOA,MAAM,cAAiB,QAA8B,SAAgC;CACnF,MAAM,UAAU,OAAO,SAAS;CAChC,OAAO,UAAW,UAAgB;AACpC;;;;;;;AAQA,MAAM,gBAAgB,SAAiB,WAA+B;CACpE;CACA,IAAI,GAAG,MAAM,GAAG,GAAG;CACnB,eAAe;AACjB;;;;;AAMA,MAAM,oBAAoB,aAAwE;CAChG,MAAM,QAAQ,SAAS;CACvB,OAAO,QAAQ,MAAM,UAAU;AACjC;;;;;;;;;AAUA,MAAM,wBACJ,UACA,YAEA,SAAS,MAAM,MAAM,EAAE,YAAY,OAAO,KAAK,SAAS;;;;AC3D1D,IAAI,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CvB,MAAM,0BACJ,WACA,UACiB;CACjB,IAAI,YAAY;CAChB,IAAI,gBAAqC;CAEzC,CAAM,YAAY;EAChB,IAAI;EACJ,IAAI;GACF,MAAO,MAAM,OAAO;EACtB,SAAS,OAAO;GACd,IAAI,CAAC,kBAAkB;IACrB,mBAAmB;IACnB,QACE,iLACA,KACF;GACF;GACA;EACF;EACA,IAAI,WACF;EAGF,MAAM,0BAAU,IAAI,IAAY;EAIhC,MAAM,gCAAgB,IAAI,IAAsC;EAEhE,MAAM,UAAU,WAAiC;GAC/C,MAAM,UAAU,MAAM,SAAS,SAAS;IACtC,cAAc,IAAI,QAAQ,IAAI;GAChC,CAAC;GACD,IAAI,CAAC,WAAW,QAAQ,IAAI,QAAQ,EAAE,GACpC;GAEF,QAAQ,IAAI,QAAQ,EAAE;GACtB,UAAU,OAAO;EACnB;EAEA,MAAM,MAAM,IAAI,WAAW;EAC3B,KAAK,MAAM,UAAU,IAAI,IAAI,GAC3B,OAAO,MAAM;EAGf,MAAM,cAAc,IAAI,GAAG,aAAa,GAAG,YAAY;GACrD,KAAK,MAAM,UAAU,SACnB,OAAO,MAAM;EAEjB,CAAC;EACD,MAAM,gBAAgB,IAAI,GAAG,eAAe,GAAG,YAAY;GACzD,KAAK,MAAM,UAAU,SAAS;IAC5B,MAAM,OAAO,cAAc,IAAI,MAAM;IACrC,IAAI,MAAM;KACR,KAAK;KACL,cAAc,OAAO,MAAM;IAC7B;GACF;EACF,CAAC;EACD,sBAAsB;GACpB,YAAY;GACZ,cAAc;EAChB;CACF,EAAC,CAAE;CAEH,aAAa;EACX,YAAY;EACZ,gBAAgB;EAChB,gBAAgB;CAClB;AACF"}
1
+ {"version":3,"file":"index.js","names":["buildAccount"],"sources":["../src/primitives.ts","../src/adapter-core.ts","../src/discovery.ts"],"sourcesContent":["import type { WalletStandardWallet, WalletStandardWalletAccount } from \"./types\";\n\n/**\n * Convert a wallet name into a stable kebab-case adapter id, scoped by\n * a platform prefix so adapters from different platforms (Phantom SVM,\n * Phantom Sui, Phantom BTC) coexist in the pool without colliding on\n * the shared `getWallets()` bus.\n *\n * @example\n * slugify(\"svm\", \"Phantom\") // \"wallet-standard:svm-phantom\"\n * slugify(\"sui\", \"Sui Wallet\") // \"wallet-standard:sui-sui-wallet\"\n * slugify(\"btc\", \"Phantom\") // \"wallet-standard:btc-phantom\"\n */\nconst slugify = (platformPrefix: string, name: string): string => {\n const slug = name\n .trim()\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/gv, \"-\");\n return `wallet-standard:${platformPrefix}-${slug}`;\n};\n\n/**\n * Read a Wallet Standard feature off a wallet, returning `undefined`\n * when absent. `features` is a reverse-DNS-keyed registry typed\n * `Record<string, unknown>` by the spec, so the caller declares the\n * concrete feature shape it expects; this accessor is the single\n * boundary where that dynamism is acknowledged. The `T` parameter is\n * intentionally caller-supplied (not inferable) and the assertion is\n * unavoidable for an untyped registry.\n */\n// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- caller-supplied feature shape; not inferable from args\nconst getFeature = <T>(wallet: WalletStandardWallet, name: string): T | undefined => {\n const feature: unknown = wallet.features[name];\n if (typeof feature !== \"object\" || feature === null) {\n return undefined;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- untyped Wallet Standard feature registry; caller declares the shape\n return feature as T;\n};\n\n/**\n * Pick the first address out of a wallet's accounts array, returning\n * `null` when the wallet currently exposes none.\n */\nconst pickFirstAddress = (accounts: ReadonlyArray<WalletStandardWalletAccount>): string | null => {\n const first = accounts[0];\n return first === undefined ? null : first.address;\n};\n\n/**\n * Look up a wallet account by address, falling back to the first\n * exposed account when the requested address isn't present.\n *\n * Used by per-call routing in `sendTx` / `signMessage`: callers pass\n * an `account` from `ConnectedWallet.accounts` to sign with a non-\n * active address; the wallet's `accounts[]` is the source of truth.\n */\nconst pickAccountByAddress = (\n accounts: ReadonlyArray<WalletStandardWalletAccount>,\n address: string,\n): WalletStandardWalletAccount | undefined =>\n accounts.find((a) => a.address === address) ?? accounts[0];\n\n// Re-exported so this package's public surface keeps offering the shared\n// account builder now that the implementation lives in @usebutr/core\n// (next to `Account` and the reducer that relies on its id format).\nexport { buildAccount } from \"@usebutr/core\";\nexport { getFeature, pickAccountByAddress, pickFirstAddress, slugify };\n","import type { Account, ChainBase, ConnectorEvent } from \"@usebutr/core\";\nimport { buildAccount, logWarn, sanitizeIcon } from \"@usebutr/core\";\n\nimport { getFeature, pickAccountByAddress, pickFirstAddress } from \"./primitives\";\nimport type {\n StandardConnectFeature,\n StandardDisconnectFeature,\n StandardEventsFeature,\n WalletStandardWallet,\n WalletStandardWalletAccount,\n} from \"./types\";\n\ntype WalletStandardCoreInput = {\n /** CAIP-2 prefix including its colon (`solana:`, `sui:`, `bip122:`). */\n chainPrefix: string;\n /** Stable adapter id. Each platform package owns its own slug prefix. */\n id: string;\n /** How this adapter names itself in errors (`Bitcoin`, `SVM`, `Sui`). */\n label: string;\n /** CAIP-2 namespace without its colon. */\n namespace: string;\n /** How the chain family reads in errors (`Bitcoin`, `Solana`, `Sui`). */\n platform: string;\n /** Chain ids worth preferring over a bare prefix match. Matched against\n * the wallet's own ordering, so a wallet listing `mainnet-beta` before\n * `mainnet` keeps the chain it advertised first. */\n preferredChainIds: ReadonlyArray<string>;\n /** Called with a function that pushes a synthetic `disconnected` event\n * to all current subscribers. The discovery layer invokes it on Wallet\n * Standard `unregister`. */\n registerDisconnector?: (emit: () => void) => void;\n /** Re-point the active chain when the wallet reports a `chains` change.\n * Polkadot opts out: its wallets advertise a single relay chain, so a\n * re-point would only ever move the adapter off the chain it resolved. */\n trackChainChanges: boolean;\n wallet: WalletStandardWallet;\n};\n\ntype WalletStandardCore = {\n /** Chains the wallet advertises in this namespace; feeds capability gating. */\n chainCount: number;\n connect: (opts?: { silent?: boolean }) => Promise<void>;\n /** Active CAIP-2 chain id, for features that take a per-call `chain`. */\n currentChainId: () => string;\n disconnect: () => Promise<void>;\n getAccount: () => Promise<Account | null>;\n getAccounts: () => Promise<Array<Account>>;\n getSigner: () => Promise<unknown>;\n /** Whether the wallet advertises `standard:events`; feeds capability gating. */\n hasEvents: boolean;\n icon: string | undefined;\n id: string;\n name: string;\n /** Wallet Standard account a call should route through: the one matching\n * `account`, else the wallet's first exposed account. */\n resolveAccount: (account?: { walletAddress: string }) => WalletStandardWalletAccount;\n subscribe: (listener: (event: ConnectorEvent) => void) => () => void;\n switchChain: (chain: ChainBase) => Promise<void>;\n /** butr chain for the active chain id, for responses that mint their own\n * `Account` (Sign-In-With-Solana) rather than going through `getAccounts`. */\n toChain: () => ChainBase;\n};\n\n/**\n * Session plumbing every Wallet Standard platform adapter repeats: chain\n * resolution, the connect/disconnect handshake, account reads, the local\n * listener set that lets `switchChain` synthesise `accountChanged`, and\n * the `standard:events` bridge. Returns `null` for wallets butr can't\n * drive (no chain in this namespace, or no `standard:connect`), which is\n * the same `null` each platform adapter returns to its caller.\n *\n * Platform packages keep what genuinely differs: which features they read\n * off the wallet, how they encode transactions and messages, and their\n * balance units. `getSigner` hands back the raw Wallet Standard wallet so\n * consumers can wrap it in their own signing library.\n */\nconst createWalletStandardCore = ({\n chainPrefix,\n id,\n label,\n namespace,\n platform,\n preferredChainIds,\n registerDisconnector,\n trackChainChanges,\n wallet,\n}: WalletStandardCoreInput): WalletStandardCore | null => {\n const pickChain = (chains: ReadonlyArray<string>): string | null =>\n chains.find((c) => preferredChainIds.includes(c)) ??\n chains.find((c) => c.startsWith(chainPrefix)) ??\n null;\n\n const initialChainId = pickChain(wallet.chains);\n if (initialChainId === null) {\n return null;\n }\n const connect = getFeature<StandardConnectFeature>(wallet, \"standard:connect\");\n if (connect === undefined) {\n return null;\n }\n\n const disconnect = getFeature<StandardDisconnectFeature>(wallet, \"standard:disconnect\");\n const events = getFeature<StandardEventsFeature>(wallet, \"standard:events\");\n\n let currentChainId = initialChainId;\n const toChain = (): ChainBase => ({\n id: currentChainId,\n // butr ships no chain-id → display-name table; the wallet name stands\n // in and consumers overlay their own labels via structural typing.\n name: wallet.name,\n namespace,\n reference: currentChainId.slice(chainPrefix.length),\n });\n\n const listeners = new Set<(event: ConnectorEvent) => void>();\n const notifyAccountChanged = () => {\n if (wallet.accounts.length === 0) {\n return;\n }\n const chain = toChain();\n const built = wallet.accounts.map((a) => buildAccount(a.address, chain));\n const first = built[0];\n if (first === undefined) {\n return;\n }\n for (const listener of listeners) {\n listener({ account: first, accounts: built, type: \"accountChanged\" });\n }\n };\n\n registerDisconnector?.(() => {\n for (const listener of listeners) {\n listener({ type: \"disconnected\" });\n }\n });\n\n return {\n chainCount: wallet.chains.filter((c) => c.startsWith(chainPrefix)).length,\n\n async connect(opts) {\n // Forward `silent` so eager hydration restores already-authorized\n // accounts without re-opening the wallet's approval UI. Wallets\n // that don't honour `silent` fall back to their normal behaviour.\n await connect.connect(opts?.silent === true ? { silent: true } : undefined);\n },\n\n currentChainId: () => currentChainId,\n\n async disconnect() {\n if (disconnect !== undefined) {\n try {\n await disconnect.disconnect();\n } catch (error) {\n logWarn(`[butr] ${label} Wallet Standard disconnect threw:`, error);\n }\n }\n },\n\n getAccount: () => {\n const address = pickFirstAddress(wallet.accounts);\n return Promise.resolve(address === null ? null : buildAccount(address, toChain()));\n },\n\n getAccounts: () => {\n const chain = toChain();\n return Promise.resolve(wallet.accounts.map((a) => buildAccount(a.address, chain)));\n },\n\n getSigner: () => Promise.resolve(wallet),\n\n hasEvents: Boolean(events),\n\n icon: sanitizeIcon(wallet.icon),\n id,\n name: wallet.name,\n\n resolveAccount: (account) => {\n const wsAccount = account\n ? pickAccountByAddress(wallet.accounts, account.walletAddress)\n : wallet.accounts[0];\n if (wsAccount === undefined) {\n throw new Error(\"No connected account\");\n }\n return wsAccount;\n },\n\n subscribe(listener) {\n listeners.add(listener);\n let unsubWallet: (() => void) | null = null;\n if (events !== undefined) {\n const unsub = events.on(\"change\", (changes) => {\n // Chain change: the wallet switched network. Re-point\n // currentChainId so subsequent per-call `chain` inputs route\n // through it, mirroring `switchChain`'s local-state model.\n if (trackChainChanges && changes.chains !== undefined) {\n const next = pickChain(changes.chains);\n if (next !== null) {\n currentChainId = next;\n }\n }\n\n if (changes.accounts !== undefined) {\n if (changes.accounts.length === 0) {\n listener({ type: \"disconnected\" });\n return;\n }\n // Forward the FULL accounts list; Wallet Standard's\n // change.accounts reflects the wallet's current exposure\n // set. Mirroring it into the pool entry keeps the array in\n // sync with what the wallet actually allows us to sign with,\n // so single-account-exposure wallets (Phantom Solana,\n // MetaMask Snap) don't accumulate stale addresses.\n const chain = toChain();\n const built = changes.accounts.map((a) => buildAccount(a.address, chain));\n const first = built[0];\n if (first === undefined) {\n return;\n }\n listener({ account: first, accounts: built, type: \"accountChanged\" });\n return;\n }\n\n if (trackChainChanges && changes.chains !== undefined) {\n notifyAccountChanged();\n }\n });\n unsubWallet = () => {\n unsub();\n };\n }\n return () => {\n listeners.delete(listener);\n unsubWallet?.();\n };\n },\n\n switchChain: (chain) => {\n if (chain.namespace !== namespace) {\n throw new Error(\n `${label} adapter received non-${platform} chain \"${chain.id}\". Pass a chain with namespace \"${namespace}\".`,\n );\n }\n // The wallet must advertise this chain; otherwise the per-call\n // `chain` input would be rejected by the wallet later.\n if (!wallet.chains.includes(chain.id)) {\n throw new Error(\n `Wallet ${wallet.name} does not advertise chain \"${chain.id}\". Available: ${wallet.chains.join(\", \")}`,\n );\n }\n currentChainId = chain.id;\n // Synthesise an `accountChanged` so butr's reducer updates the pool\n // entry's chain; the wallet itself has no event to fire here.\n notifyAccountChanged();\n return Promise.resolve();\n },\n\n toChain,\n };\n};\n\nexport type { WalletStandardCore };\nexport { createWalletStandardCore };\n","import type { WalletAdapter } from \"@usebutr/core\";\nimport { logWarn } from \"@usebutr/core\";\n\nimport type { WalletStandardAppModule, WalletStandardWallet } from \"./types\";\n\nlet warnedMissingApp = false;\n\n/**\n * Callback supplied by per-platform discovery to build a `WalletAdapter`\n * out of a Wallet Standard wallet announcement.\n *\n * Returns `null` when the wallet doesn't advertise this platform; that\n * lets a multi-chain wallet (e.g. Phantom: SVM + EVM + Sui + Bitcoin)\n * produce one adapter per platform without each builder needing to know\n * about the others.\n *\n * The second argument is a hook the builder calls during construction\n * to wire a synthetic `disconnected` event into its subscriber set.\n * The discovery loop fires the registered emitter when Wallet Standard\n * announces `unregister` for that wallet.\n */\ntype WalletStandardAdapterBuilder = (\n wallet: WalletStandardWallet,\n registerDisconnector: (emit: () => void) => void,\n) => WalletAdapter | null;\n\n/**\n * Subscribe to Wallet Standard announcements and turn matching wallets\n * into butr `WalletAdapter`s using a per-platform `build` callback.\n *\n * **Shared machinery** every platform package needs:\n * - Dynamic import of `@wallet-standard/app` (optional peer dep;\n * failure to resolve quietly disables discovery so consumers who\n * don't install it pay nothing).\n * - Cancellation: the returned unsubscribe is safe to call before the\n * dynamic import has resolved.\n * - Dedupe by adapter id, so re-announcements don't double-emit.\n * - `unregister` integration: when an extension is removed mid-session,\n * fire the disconnector the builder registered so connected pool\n * entries on the consumer side tear down cleanly.\n *\n * **What's platform-specific** lives entirely in `build`:\n * - Which `wallet.chains` to accept.\n * - Which features to gate on.\n * - The `id` slug prefix (use `slugify(prefix, wallet.name)`).\n * - The capability resolver, the feature decoding, the chain coercion.\n *\n * Disconnectors are keyed by the wallet object itself (identity equality),\n * not by adapter id; Wallet Standard's `register` / `unregister` emit\n * the same wallet object, so identity is the cheapest stable key.\n */\nconst discoverWalletStandard = (\n onAdapter: (adapter: WalletAdapter) => void,\n build: WalletStandardAdapterBuilder,\n): (() => void) => {\n let cancelled = false;\n let internalUnsub: (() => void) | null = null;\n\n void (async () => {\n let mod: WalletStandardAppModule;\n try {\n const imported: unknown = await import(\"@wallet-standard/app\");\n if (\n typeof imported !== \"object\" ||\n imported === null ||\n !(\"getWallets\" in imported) ||\n typeof imported.getWallets !== \"function\"\n ) {\n throw new Error(\"@wallet-standard/app has no getWallets export\");\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated getWallets export above; the rest of the untyped module is trusted\n mod = imported as WalletStandardAppModule;\n } catch (error) {\n if (!warnedMissingApp) {\n warnedMissingApp = true;\n logWarn(\n \"[butr] Wallet Standard wallet discovery is disabled: `@wallet-standard/app` could not be loaded. Install it (`npm i @wallet-standard/app`) to detect Wallet Standard wallets.\",\n error,\n );\n }\n return;\n }\n if (cancelled) {\n return;\n }\n\n const seenIds = new Set<string>();\n // wallet object → emitter that pushes synthetic `disconnected` to\n // this wallet's adapter's subscribers. Identity-keyed so the\n // unregister handler can find the right emitter cheaply.\n const disconnectors = new Map<WalletStandardWallet, () => void>();\n\n const tryAdd = (wallet: WalletStandardWallet) => {\n const adapter = build(wallet, (emit) => {\n disconnectors.set(wallet, emit);\n });\n if (!adapter || seenIds.has(adapter.id)) {\n return;\n }\n seenIds.add(adapter.id);\n onAdapter(adapter);\n };\n\n const app = mod.getWallets();\n for (const wallet of app.get()) {\n tryAdd(wallet);\n }\n\n const offRegister = app.on(\"register\", (...wallets) => {\n for (const wallet of wallets) {\n tryAdd(wallet);\n }\n });\n const offUnregister = app.on(\"unregister\", (...wallets) => {\n for (const wallet of wallets) {\n const emit = disconnectors.get(wallet);\n if (emit) {\n emit();\n disconnectors.delete(wallet);\n }\n }\n });\n internalUnsub = () => {\n offRegister();\n offUnregister();\n };\n })();\n\n return () => {\n cancelled = true;\n internalUnsub?.();\n internalUnsub = null;\n };\n};\n\nexport type { WalletStandardAdapterBuilder };\nexport { discoverWalletStandard };\n"],"mappings":";;;;;;;;;;;;;;AAaA,MAAM,WAAW,gBAAwB,SAAyB;CAKhE,OAAO,mBAAmB,eAAe,GAJ5B,KACV,KAAK,CAAC,CACN,YAAY,CAAC,CACb,2BAAW,6BAAa,GAAG,GACiB;AACjD;;;;;;;;;;AAYA,MAAM,cAAiB,QAA8B,SAAgC;CACnF,MAAM,UAAmB,OAAO,SAAS;CACzC,IAAI,OAAO,YAAY,YAAY,YAAY,MAC7C;CAGF,OAAO;AACT;;;;;AAMA,MAAM,oBAAoB,aAAwE;CAChG,MAAM,QAAQ,SAAS;CACvB,OAAO,UAAU,SAAY,OAAO,MAAM;AAC5C;;;;;;;;;AAUA,MAAM,wBACJ,UACA,YAEA,SAAS,MAAM,MAAM,EAAE,YAAY,OAAO,KAAK,SAAS;;;;;;;;;;;;;;;;;ACe1D,MAAM,4BAA4B,EAChC,aACA,IACA,OACA,WACA,UACA,mBACA,sBACA,mBACA,aACwD;CACxD,MAAM,aAAa,WACjB,OAAO,MAAM,MAAM,kBAAkB,SAAS,CAAC,CAAC,KAChD,OAAO,MAAM,MAAM,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M;EAEjB,CAAC;EACD,MAAM,gBAAgB,IAAI,GAAG,eAAe,GAAG,YAAY;GACzD,KAAK,MAAM,UAAU,SAAS;IAC5B,MAAM,OAAO,cAAc,IAAI,MAAM;IACrC,IAAI,MAAM;KACR,KAAK;KACL,cAAc,OAAO,MAAM;IAC7B;GACF;EACF,CAAC;EACD,sBAAsB;GACpB,YAAY;GACZ,cAAc;EAChB;CACF,EAAC,CAAE;CAEH,aAAa;EACX,YAAY;EACZ,gBAAgB;EAChB,gBAAgB;CAClB;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usebutr/wallet-standard-shared",
3
- "version": "0.2.5",
3
+ "version": "0.3.0",
4
4
  "description": "Shared Wallet Standard discovery primitives used by @usebutr/svm, @usebutr/sui, @usebutr/bitcoin.",
5
5
  "license": "MIT",
6
6
  "author": "Pedro Filho <pedro@filho.me>",
@@ -22,12 +22,12 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@usebutr/core": "0.4.1"
25
+ "@usebutr/core": "0.5.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@wallet-standard/app": "^1.1.1",
29
29
  "typescript": "^6.0.3",
30
- "vitest": "^4.1.9",
30
+ "vitest": "^4.1.10",
31
31
  "@repo/config-vitest": "0.0.0",
32
32
  "@repo/typescript-config": "0.0.0"
33
33
  },