@usebutr/polkadot 1.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +209 -0
- package/LICENSE +21 -0
- package/README.md +68 -0
- package/dist/index.d.ts +20 -69
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +76 -189
- package/dist/index.js.map +1 -1
- package/package.json +22 -6
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# @usebutr/polkadot
|
|
2
|
+
|
|
3
|
+
## 2.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- [#203](https://github.com/pedroapfilho/usebutr/pull/203) [`1263f86`](https://github.com/pedroapfilho/usebutr/commit/1263f8666afd43b4f7dbf8df1763709c3edf09d9) Thanks [@pedroapfilho](https://github.com/pedroapfilho)! - Adapters now say what they can do by having the method: `capabilities` is gone, and an optional method (`sendTx`, `signMessage`, `getBalance`, `switchChain`, …) exists only when it works for that wallet. No adapter returns a placeholder balance or a receipt that stays pending anymore.
|
|
8
|
+
|
|
9
|
+
- `sendTx(tx, { account, chain })` replaces `sendTx` and `sendTxToChain`, and `signMessage`, `signTransaction` and `getBalance` take options objects. `chain` is a `ChainBase`. An adapter either routes the call to that chain, switches the wallet to it, or rejects; none ignores it.
|
|
10
|
+
- An `account` the wallet does not expose now rejects instead of signing with the first account. `chain.name` is the chain's name, never the wallet's.
|
|
11
|
+
- `getAccounts()` resolves the active account first. `getAccount` and `switchAccount` are removed.
|
|
12
|
+
- `getSigner()` resolves a tagged `WalletSigner` (`eip1193`, `wallet-standard`, `walletconnect`, `ledger-*`, …), so it can be narrowed with `switch (signer.kind)` instead of cast.
|
|
13
|
+
- `createWalletManager(config, { initialState })` owns discovery, hydration and persistence, and works without React. `config.sources` replaces the `discovery`, `connectors` and `createConnector` props. `fromAdapters` registers WalletConnect, Ledger and hand-built adapters, which now also appear in `useDiscoveredWallets()`.
|
|
14
|
+
- `WalletManagerProvider` takes `config` and `initialState`. `useSigner(wallet)` and `useBalance(wallet, { token, account })` take the wallet entry itself, and id-taking hooks read the active wallet only when the id is omitted (`null` reads none). The hooks are `useWalletManager`, `useWalletState`, `useConnect`, `useWallet`, `useSelectedWallet` (now typed per platform), `useAccounts`, `useConnectionStatus`, `useIsHydrated`, `useIsReconnecting`, `useDiscoveredWallets`, `useConnectedWallets`, the `…ByPlatform` groupings, `useBalance` and `useSigner`.
|
|
15
|
+
- `manager.connect()` and `useConnect().connectAsync()` resolve the `ConnectedWallet` and reject with a `ConnectionError`, now an `Error` subclass with a `kind` and a new `WalletNotFound` kind. `useConnect().connect()` never rejects: the failure lands in its `error`.
|
|
16
|
+
- `WalletPersistence` is `load()` / `save(state)`, and `createWalletStorage` replaces `new WalletStorage`. Storage keys are unchanged.
|
|
17
|
+
- Chain registries (`EVM_CHAINS`, `SVM_CHAINS`, …, `CHAINS_BY_PLATFORM`) move to `@usebutr/core`, and `BITCOIN_CHAINS` gains `testnet4`. `@usebutr/wallets` loads every platform's signer kinds, so an app that imports only it can narrow `signer.kind`.
|
|
18
|
+
- `@usebutr/react` requires React 19, which its `use()` call already needed.
|
|
19
|
+
- WalletConnect requests on Solana, Sui and Bitcoin now carry their chain, so they no longer fall through to the first namespace in a multi-namespace session. Solana takes `SVM_CHAINS` chains and maps them to the genesis-hash ids WalletConnect sessions use.
|
|
20
|
+
- Ledger's Solana `signTransaction` returns the full signed transaction, Sui signs the intent message, and Bitcoin `signMessage` returns a BIP-137 signature.
|
|
21
|
+
- `@usebutr/testing`'s fake adapter resolves a `signer` you pass instead of registering a test-only signer kind.
|
|
22
|
+
- `setAccount` selects an exposed account without changing any account's chain. Unknown accounts are ignored; chain changes come from the adapter.
|
|
23
|
+
- WalletConnect EVM events use the namespace in `session_event`, including empty account lists that end the connection. Local chain switches still update the manager.
|
|
24
|
+
- Failed persistence saves wait for every key write to finish before reporting failure, so delayed writes cannot overwrite a later disconnect.
|
|
25
|
+
- `@usebutr/svm/transaction` provides the shared legacy/v0 signing codec used by Ledger and WalletConnect, with consistent layout and signature validation.
|
|
26
|
+
|
|
27
|
+
See the migration guide at https://docs.usebutr.com/migration.
|
|
28
|
+
|
|
29
|
+
### Patch Changes
|
|
30
|
+
|
|
31
|
+
- Updated dependencies [[`1263f86`](https://github.com/pedroapfilho/usebutr/commit/1263f8666afd43b4f7dbf8df1763709c3edf09d9), [`5d1f234`](https://github.com/pedroapfilho/usebutr/commit/5d1f23403263f7a1f8a48be061727972fe749b5f)]:
|
|
32
|
+
- @usebutr/core@3.0.0
|
|
33
|
+
- @usebutr/wallet-standard-shared@2.0.0
|
|
34
|
+
|
|
35
|
+
## 1.1.2
|
|
36
|
+
|
|
37
|
+
### Patch Changes
|
|
38
|
+
|
|
39
|
+
- Updated dependencies [[`bc5b58c`](https://github.com/pedroapfilho/usebutr/commit/bc5b58cd87601be38dbb77a14e16eaaa36e8f012), [`bc5b58c`](https://github.com/pedroapfilho/usebutr/commit/bc5b58cd87601be38dbb77a14e16eaaa36e8f012)]:
|
|
40
|
+
- @usebutr/wallet-standard-shared@1.0.0
|
|
41
|
+
- @usebutr/core@2.0.1
|
|
42
|
+
|
|
43
|
+
## 1.1.1
|
|
44
|
+
|
|
45
|
+
### Patch Changes
|
|
46
|
+
|
|
47
|
+
- Updated dependencies [302ae4a]
|
|
48
|
+
- @usebutr/wallet-standard-shared@0.5.1
|
|
49
|
+
|
|
50
|
+
## 1.1.0
|
|
51
|
+
|
|
52
|
+
### Minor Changes
|
|
53
|
+
|
|
54
|
+
- 9b1caa2: Correctness pass across the storage, hydration and connector layers. Several of
|
|
55
|
+
these change observable behaviour; the ones worth knowing about before upgrading:
|
|
56
|
+
|
|
57
|
+
**Breaking**
|
|
58
|
+
|
|
59
|
+
- `SuiWallet.signTransaction` now returns `{ bytes, signature }` instead of
|
|
60
|
+
`Uint8Array`. Sui's `executeTransactionBlock` needs both, and each connector
|
|
61
|
+
previously returned a different half, so the old value could not be broadcast
|
|
62
|
+
and a consumer could not tell which half they held. SVM and Bitcoin keep their
|
|
63
|
+
single-`Uint8Array` shape.
|
|
64
|
+
- `@usebutr/svm`'s `sendTx` returns the signature base58-encoded, matching the
|
|
65
|
+
WalletConnect namespace, the Ledger app, Solana explorers and
|
|
66
|
+
`getSignatureStatuses`. It previously returned base64.
|
|
67
|
+
- `@usebutr/sui`'s feature input types drop the `string` arm from
|
|
68
|
+
`transaction`; wallets only ever accepted the `toJSON()` form. Strings and BCS
|
|
69
|
+
bytes are now wrapped for you, so `sendTx` accepts strictly more than before.
|
|
70
|
+
|
|
71
|
+
**Behaviour fixes**
|
|
72
|
+
|
|
73
|
+
- `WalletStorage.setPool` and `removePoolEntry` could self-deadlock on a corrupt
|
|
74
|
+
pool payload, leaving `connectWallet` unresolved and every later pool write
|
|
75
|
+
jammed for the page's life. Both are fixed, and `readWalletSnapshot` now shares
|
|
76
|
+
one codec with `WalletStorage` so the server and client decodes cannot drift.
|
|
77
|
+
- A seeded (SSR) entry whose silent reconnect failed used to stay in the pool
|
|
78
|
+
backed by a placeholder connector forever, so `useSigner`/`useBalance`
|
|
79
|
+
reported an error and `useConnectionStatus` reported `"reconnecting"`
|
|
80
|
+
permanently. Those entries are now dropped.
|
|
81
|
+
- `useSigner` and `useBalance` stay `idle` for a wallet that is still
|
|
82
|
+
reconnecting instead of surfacing a placeholder rejection as `status: "error"`.
|
|
83
|
+
- `useConnectionStatus` lets a live `"connecting"`/`"error"` take precedence over
|
|
84
|
+
the derived `"reconnecting"`, so an in-flight attempt and a connection error
|
|
85
|
+
are no longer hidden. New `useIsReconnecting(connectorId?)` answers the
|
|
86
|
+
per-wallet question directly.
|
|
87
|
+
- A background restore no longer writes the connect-attempt status or steals
|
|
88
|
+
`activeConnectorId`, and a superseded `CONNECT_FAILED` no longer overwrites the
|
|
89
|
+
current attempt.
|
|
90
|
+
- An externally-disconnected connector is now torn down, not just dropped from
|
|
91
|
+
the pool, so a cached adapter is not reused while still holding a session.
|
|
92
|
+
- EVM: a malformed provider response is treated as absent rather than `""`, which
|
|
93
|
+
previously produced chain `eip155:0`, zero-length signatures, empty transaction
|
|
94
|
+
hashes and a confident `0 ETH`. `switchChain` gained the same-chain
|
|
95
|
+
short-circuit `sendTxToChain` already had.
|
|
96
|
+
- WalletConnect: accounts carry their own chain instead of all being stamped with
|
|
97
|
+
the active one, so a multi-chain session no longer returns a wrong-chain
|
|
98
|
+
address. One pairing now covers every configured namespace, the pairing URI
|
|
99
|
+
survives a reconnect, and concurrent connects share one pairing.
|
|
100
|
+
- Bitcoin: the sats-connect (Xverse) adapter honours `silent`, so a reload no
|
|
101
|
+
longer triggers an unsolicited approval prompt, and exposes the payment address
|
|
102
|
+
as its single account instead of also presenting the ordinals address as
|
|
103
|
+
spendable.
|
|
104
|
+
- Polkadot: the injected adapter actually delivers events to subscribers,
|
|
105
|
+
`switchChain` notifies like its Wallet Standard sibling, and chain resolution
|
|
106
|
+
prefers the mainnets rather than whatever the wallet listed first.
|
|
107
|
+
- Ledger: the device session is committed atomically, so a locked device no
|
|
108
|
+
longer leaves an open transport that reports itself connected, and concurrent
|
|
109
|
+
connects open one transport.
|
|
110
|
+
- SVM: `sendTxToChain` submits to the chain you asked for instead of the
|
|
111
|
+
adapter's current one, and rejects a chain the wallet does not advertise.
|
|
112
|
+
- `@usebutr/svm`'s `switchChain` capability now counts only `solana:` chains, so
|
|
113
|
+
a multi-namespace wallet no longer advertises a method that always throws.
|
|
114
|
+
|
|
115
|
+
**Testing**
|
|
116
|
+
|
|
117
|
+
- `createFakePersistence` is now the real `WalletStorage` over memory drivers
|
|
118
|
+
rather than a parallel implementation, so it inherits upsert semantics,
|
|
119
|
+
validation and JSON round-tripping. Two divergences are fixed as a result:
|
|
120
|
+
`setPool` upserts rather than replaces, and `clearAll` leaves the
|
|
121
|
+
user-disconnected flag alone.
|
|
122
|
+
- `createFakeConnectedWallet` rejects being given both an `adapter` and explicit
|
|
123
|
+
`addresses`/`accounts`, a combination whose halves could disagree.
|
|
124
|
+
|
|
125
|
+
### Patch Changes
|
|
126
|
+
|
|
127
|
+
- Updated dependencies [9b1caa2]
|
|
128
|
+
- @usebutr/wallet-standard-shared@0.5.0
|
|
129
|
+
- @usebutr/core@2.0.0
|
|
130
|
+
|
|
131
|
+
## 1.0.1
|
|
132
|
+
|
|
133
|
+
### Patch Changes
|
|
134
|
+
|
|
135
|
+
- Updated dependencies [8ecaf89]
|
|
136
|
+
- @usebutr/core@1.1.0
|
|
137
|
+
- @usebutr/wallet-standard-shared@0.4.1
|
|
138
|
+
|
|
139
|
+
## 1.0.0
|
|
140
|
+
|
|
141
|
+
### Major Changes
|
|
142
|
+
|
|
143
|
+
- f0a5116: **Breaking:** the `platform` field is gone from the `PlatformDiscoverer` type in `@usebutr/core`, and from the `evmDiscoverer`, `svmDiscoverer`, `suiDiscoverer`, `bitcoinDiscoverer` and `polkadotDiscoverer` objects that implement it. Nothing read it: the aggregator keys discoverers by `ChainPlatform` in its own registry, so the field only restated the key.
|
|
144
|
+
|
|
145
|
+
Migration: read the platform from the `KNOWN_DISCOVERERS` key in `@usebutr/wallets` (`Object.entries(KNOWN_DISCOVERERS)`), or from `adapter.chainPlatform` on a discovered adapter. Custom `PlatformDiscoverer` implementations must drop the `platform` property; keeping it is now an excess-property error.
|
|
146
|
+
|
|
147
|
+
### Patch Changes
|
|
148
|
+
|
|
149
|
+
- 7887cf0: Resolve capabilities through `buildWalletCapabilities` from `@usebutr/wallet-standard-shared` instead of a per-package copy of the same object literal. Resolver names, input types and returned flags are unchanged. The injected Polkadot profile now derives its chain count from `POLKADOT_CHAINS_LIST` rather than asserting `switchChain: true` directly; the result is the same.
|
|
150
|
+
- 7887cf0: Move each package's `discover*Adapters` function next to the adapter builder it wraps and drop the single-function `wallet-standard.ts` module. The functions are still exported from the package root under the same names; only an internal file boundary went away.
|
|
151
|
+
- Updated dependencies [7887cf0]
|
|
152
|
+
- Updated dependencies [7887cf0]
|
|
153
|
+
- Updated dependencies [f0a5116]
|
|
154
|
+
- Updated dependencies [f0a5116]
|
|
155
|
+
- Updated dependencies [7887cf0]
|
|
156
|
+
- @usebutr/core@1.0.0
|
|
157
|
+
- @usebutr/wallet-standard-shared@0.4.0
|
|
158
|
+
|
|
159
|
+
## 0.1.4
|
|
160
|
+
|
|
161
|
+
### Patch Changes
|
|
162
|
+
|
|
163
|
+
- efe4550: Share the session plumbing behind the Wallet Standard and WalletConnect CAIP adapters. `@usebutr/wallet-standard-shared` now exports `createWalletStandardCore`, which the Bitcoin, Polkadot, Sui and SVM adapters build on; the WalletConnect Bitcoin, Sui and SVM namespaces share an equivalent CAIP core. Every package's public API is unchanged. The one visible difference is a dev-console warning: a failed SVM disconnect now logs `[butr] SVM Wallet Standard disconnect threw:` instead of `[butr] Wallet Standard disconnect threw:`.
|
|
164
|
+
- Updated dependencies [efe4550]
|
|
165
|
+
- Updated dependencies [4467a5e]
|
|
166
|
+
- @usebutr/wallet-standard-shared@0.3.0
|
|
167
|
+
- @usebutr/core@0.5.0
|
|
168
|
+
|
|
169
|
+
## 0.1.3
|
|
170
|
+
|
|
171
|
+
### Patch Changes
|
|
172
|
+
|
|
173
|
+
- Updated dependencies [c1309ee]
|
|
174
|
+
- @usebutr/core@0.4.2
|
|
175
|
+
- @usebutr/wallet-standard-shared@0.2.6
|
|
176
|
+
|
|
177
|
+
## 0.1.2
|
|
178
|
+
|
|
179
|
+
### Patch Changes
|
|
180
|
+
|
|
181
|
+
- 937dfae: Bump runtime dependency floors (`@wallet-standard/app` 1.1.1, `@ledgerhq/*` latest minors, `@walletconnect/universal-provider` 2.23.10) and modernize public type declarations from method signatures to property function types (oxlint `method-signature-style`). Type-level only — no runtime behavior change.
|
|
182
|
+
- Updated dependencies [937dfae]
|
|
183
|
+
- @usebutr/core@0.4.1
|
|
184
|
+
- @usebutr/wallet-standard-shared@0.2.5
|
|
185
|
+
|
|
186
|
+
## 0.1.1
|
|
187
|
+
|
|
188
|
+
### Patch Changes
|
|
189
|
+
|
|
190
|
+
- a46eecd: Ship unminified ESM so downstream bundlers (Vite/esbuild dep pre-bundling) process the package correctly; fixes a ReferenceError in consumer dev servers. The consuming app minifies once at its own build.
|
|
191
|
+
- Updated dependencies [b5322ae]
|
|
192
|
+
- Updated dependencies [d5f32c7]
|
|
193
|
+
- Updated dependencies [a46eecd]
|
|
194
|
+
- Updated dependencies [3f26776]
|
|
195
|
+
- @usebutr/core@0.4.0
|
|
196
|
+
- @usebutr/wallet-standard-shared@0.2.4
|
|
197
|
+
|
|
198
|
+
## 0.1.0
|
|
199
|
+
|
|
200
|
+
### Minor Changes
|
|
201
|
+
|
|
202
|
+
- 886ee1d: Add Polkadot/Substrate support. New `@usebutr/polkadot` package discovers wallets via injectedWeb3 (polkadot-js, Talisman, SubWallet, Nova, Enkrypt) with a Wallet Standard `polkadot:*` fallback. `ChainPlatform` widens to include `"polkadot"`; `autoDiscovery({ polkadot: true })` and `CHAINS_BY_PLATFORM` now cover it. Message signing works via the injected `signer.signRaw`; transaction signing is delegated to the consumer through `getSigner()` (e.g. polkadot-api), matching butr's no-RPC posture.
|
|
203
|
+
|
|
204
|
+
### Patch Changes
|
|
205
|
+
|
|
206
|
+
- 0751cc3: Share the no-RPC placeholders between the injectedWeb3 and Wallet Standard adapters (single `no-rpc` module), so the "butr ships no RPC on Polkadot" invariant lives in one place. `getBalance` now returns a neutral, chain-agnostic placeholder (`{ decimals: 0, symbol: "" }`) instead of a hardcoded `DOT`/10 that was wrong for Kusama/Westend/Paseo; it stays gated behind `capabilities.getBalance === false`. The injected `getSigner()` now throws `"No connected account"` instead of handing back an empty-string address.
|
|
207
|
+
- Updated dependencies [886ee1d]
|
|
208
|
+
- @usebutr/core@0.3.0
|
|
209
|
+
- @usebutr/wallet-standard-shared@0.2.3
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pedro Filho
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# @usebutr/polkadot
|
|
2
|
+
|
|
3
|
+
injectedWeb3 + Wallet Standard adapter for butr (Polkadot/Substrate).
|
|
4
|
+
|
|
5
|
+
Part of [butr](https://www.usebutr.com), a multi-chain wallet discovery and
|
|
6
|
+
connection-state library. Your application owns the picker UI and chain client.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @usebutr/react @usebutr/core @usebutr/polkadot zustand
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
React 19 is a peer dependency of the provider. Discovery does not render a connect modal; add your picker as the provider child. This example uses injectedWeb3. Use `@usebutr/wallets` to also compose the Wallet Standard fallback.
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```tsx
|
|
19
|
+
import type { ReactNode } from "react";
|
|
20
|
+
import type { WalletManagerConfig } from "@usebutr/core";
|
|
21
|
+
import { discoverInjectedPolkadotAdapters } from "@usebutr/polkadot";
|
|
22
|
+
import { WalletManagerProvider } from "@usebutr/react";
|
|
23
|
+
|
|
24
|
+
const config: WalletManagerConfig = { sources: [discoverInjectedPolkadotAdapters] };
|
|
25
|
+
|
|
26
|
+
export const WalletProvider = ({ children }: { children: ReactNode }) => (
|
|
27
|
+
<WalletManagerProvider config={config}>{children}</WalletManagerProvider>
|
|
28
|
+
);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Signing
|
|
32
|
+
|
|
33
|
+
butr ships no Polkadot RPC, so a Polkadot adapter has no `sendTx`,
|
|
34
|
+
`getBalance` or `getTransactionReceipt`. Build and submit extrinsics with
|
|
35
|
+
polkadot-api through `getSigner()`:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { connectInjectedExtension } from "polkadot-api/pjs-signer";
|
|
39
|
+
|
|
40
|
+
const signer = await wallet.connector.getSigner();
|
|
41
|
+
if (signer.kind === "polkadot-injected") {
|
|
42
|
+
const extension = await connectInjectedExtension(signer.extensionName);
|
|
43
|
+
const account = extension.getAccounts().find((a) => a.address === wallet.account.walletAddress);
|
|
44
|
+
// tx.signSubmitAndWatch(account.polkadotSigner)
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Wallet Standard wallets resolve `{ kind: "wallet-standard", wallet }` instead.
|
|
49
|
+
`signMessage` is defined when the wallet can sign bytes: on Wallet Standard
|
|
50
|
+
when it advertises `polkadot:signMessage`, on injectedWeb3 once `connect()`
|
|
51
|
+
has enabled an extension that exposes `signRaw`. Pass `{ account }` to sign
|
|
52
|
+
as another exposed account; an account the wallet does not expose rejects.
|
|
53
|
+
|
|
54
|
+
Chains come from `POLKADOT_CHAINS` in `@usebutr/core`. injectedWeb3
|
|
55
|
+
extensions have no network to switch, so those adapters have no
|
|
56
|
+
`switchChain`; an account the extension pins to a network through
|
|
57
|
+
`genesisHash` carries that chain.
|
|
58
|
+
|
|
59
|
+
## Documentation
|
|
60
|
+
|
|
61
|
+
- [Package reference](https://docs.usebutr.com/api/polkadot)
|
|
62
|
+
- [Getting started](https://docs.usebutr.com/getting-started/quickstart)
|
|
63
|
+
- [Examples and source](https://github.com/pedroapfilho/usebutr)
|
|
64
|
+
- [Report an issue](https://github.com/pedroapfilho/usebutr/issues)
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
[MIT](./LICENSE), copyright 2026 Pedro Filho.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,55 +1,5 @@
|
|
|
1
|
+
import { PlatformDiscoverer, PolkadotAdapter, WalletAdapter } from "@usebutr/core";
|
|
1
2
|
import { WalletStandardWallet, WalletStandardWalletAccount } from "@usebutr/wallet-standard-shared";
|
|
2
|
-
import { ChainBase, PlatformDiscoverer, PolkadotAdapter, WalletAdapter, WalletCapabilities } from "@usebutr/core";
|
|
3
|
-
//#region src/chains.d.ts
|
|
4
|
-
declare const POLKADOT_CHAINS: {
|
|
5
|
-
readonly kusama: {
|
|
6
|
-
readonly id: "polkadot:b0a8d493285c2df73290dfb7e61f870f";
|
|
7
|
-
readonly name: "Kusama";
|
|
8
|
-
readonly namespace: "polkadot";
|
|
9
|
-
readonly reference: "b0a8d493285c2df73290dfb7e61f870f";
|
|
10
|
-
};
|
|
11
|
-
readonly paseo: {
|
|
12
|
-
readonly id: "polkadot:77afd6190f1554ad45fd0d31aee62aac";
|
|
13
|
-
readonly name: "Paseo";
|
|
14
|
-
readonly namespace: "polkadot";
|
|
15
|
-
readonly reference: "77afd6190f1554ad45fd0d31aee62aac";
|
|
16
|
-
};
|
|
17
|
-
readonly polkadot: {
|
|
18
|
-
readonly id: "polkadot:91b171bb158e2d3848fa23a9f1c25182";
|
|
19
|
-
readonly name: "Polkadot";
|
|
20
|
-
readonly namespace: "polkadot";
|
|
21
|
-
readonly reference: "91b171bb158e2d3848fa23a9f1c25182";
|
|
22
|
-
};
|
|
23
|
-
readonly westend: {
|
|
24
|
-
readonly id: "polkadot:e143f23803ac50e8f6f8e62695d1ce9e";
|
|
25
|
-
readonly name: "Westend";
|
|
26
|
-
readonly namespace: "polkadot";
|
|
27
|
-
readonly reference: "e143f23803ac50e8f6f8e62695d1ce9e";
|
|
28
|
-
};
|
|
29
|
-
};
|
|
30
|
-
declare const POLKADOT_CHAINS_LIST: ReadonlyArray<ChainBase>;
|
|
31
|
-
//#endregion
|
|
32
|
-
//#region src/capabilities.d.ts
|
|
33
|
-
type WalletStandardPolkadotCapabilityInput = {
|
|
34
|
-
chainCount: number;
|
|
35
|
-
features: {
|
|
36
|
-
events: boolean;
|
|
37
|
-
signMessage: boolean;
|
|
38
|
-
};
|
|
39
|
-
};
|
|
40
|
-
/**
|
|
41
|
-
* injectedWeb3 always exposes `signer.signRaw` and `accounts.subscribe`, so
|
|
42
|
-
* those flags are unconditional. The chain count comes from butr's own
|
|
43
|
-
* registry because injectedWeb3 wallets advertise no chains.
|
|
44
|
-
*/
|
|
45
|
-
declare const resolveInjectedPolkadotCapabilities: () => WalletCapabilities;
|
|
46
|
-
/**
|
|
47
|
-
* Wallet Standard `polkadot:*` feature → butr capability mapping. No
|
|
48
|
-
* standalone `signTransaction`: building an extrinsic needs chain metadata
|
|
49
|
-
* butr doesn't fetch, so transaction signing goes through `getSigner()`.
|
|
50
|
-
*/
|
|
51
|
-
declare const resolveWalletStandardPolkadotCapabilities: (input: WalletStandardPolkadotCapabilityInput) => WalletCapabilities;
|
|
52
|
-
//#endregion
|
|
53
3
|
//#region src/injected/injected-web3.d.ts
|
|
54
4
|
/**
|
|
55
5
|
* Local narrowing of the `@polkadot/extension-dapp` injectedWeb3 standard
|
|
@@ -92,20 +42,17 @@ type InjectedWindowProvider = {
|
|
|
92
42
|
type InjectedWindow = {
|
|
93
43
|
injectedWeb3?: Record<string, InjectedWindowProvider>;
|
|
94
44
|
};
|
|
45
|
+
declare global {
|
|
46
|
+
interface Window {
|
|
47
|
+
injectedWeb3?: Record<string, InjectedWindowProvider>;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
95
50
|
//#endregion
|
|
96
51
|
//#region src/injected/adapter.d.ts
|
|
97
|
-
/** Handle returned by `getSigner()`. Carries the `window.injectedWeb3`
|
|
98
|
-
* key (`extensionName`) so consumers can bridge to polkadot-api's
|
|
99
|
-
* `connectInjectedExtension`, the active SS58 address, and the raw
|
|
100
|
-
* `Injected` object for direct `signer` access. */
|
|
101
|
-
type PolkadotSignerHandle = {
|
|
102
|
-
address: string;
|
|
103
|
-
extension: Injected;
|
|
104
|
-
extensionName: string;
|
|
105
|
-
};
|
|
106
52
|
/**
|
|
107
|
-
*
|
|
108
|
-
* extension
|
|
53
|
+
* `enable()` prompts, so it waits for `connect()`. No `switchChain`: the
|
|
54
|
+
* extension has no network to switch and nothing here takes a chain; an
|
|
55
|
+
* extrinsic carries its genesis hash in the payload polkadot-api builds.
|
|
109
56
|
*/
|
|
110
57
|
declare const buildInjectedPolkadotAdapter: (extensionName: string, displayName: string, provider: InjectedWindowProvider) => PolkadotAdapter;
|
|
111
58
|
//#endregion
|
|
@@ -135,6 +82,7 @@ type PolkadotSignMessageOutput = {
|
|
|
135
82
|
};
|
|
136
83
|
type PolkadotSignMessageFeature = {
|
|
137
84
|
signMessage: (input: PolkadotSignMessageInput) => Promise<PolkadotSignMessageOutput>;
|
|
85
|
+
version?: string;
|
|
138
86
|
};
|
|
139
87
|
//#endregion
|
|
140
88
|
//#region src/wallet-standard-adapter.d.ts
|
|
@@ -142,7 +90,7 @@ declare const buildPolkadotWalletStandardAdapter: (wallet: WalletStandardWallet,
|
|
|
142
90
|
/** Optional. Called with a function that pushes a synthetic
|
|
143
91
|
* `disconnected` event to all current subscribers. The discovery
|
|
144
92
|
* layer invokes it on Wallet Standard `unregister`. */
|
|
145
|
-
registerDisconnector?: (emit: () => void) => void) =>
|
|
93
|
+
registerDisconnector?: (emit: () => void) => void) => PolkadotAdapter | null;
|
|
146
94
|
/**
|
|
147
95
|
* The fallback channel; see `polkadotDiscoverer`. Requires the optional
|
|
148
96
|
* `@wallet-standard/app` peer dep and no-ops without it.
|
|
@@ -159,15 +107,18 @@ declare const polkadotDiscoverer: PlatformDiscoverer;
|
|
|
159
107
|
//#endregion
|
|
160
108
|
//#region src/signer-augmentation.d.ts
|
|
161
109
|
/**
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
* `
|
|
110
|
+
* `extensionName` is the `window.injectedWeb3` key polkadot-api's
|
|
111
|
+
* `connectInjectedExtension` takes. No address: sign as the connected
|
|
112
|
+
* wallet's `account`, which follows `setAccount`.
|
|
165
113
|
*/
|
|
166
114
|
declare module "@usebutr/core" {
|
|
167
|
-
interface
|
|
168
|
-
polkadot:
|
|
115
|
+
interface WalletSignerRegistry {
|
|
116
|
+
"polkadot-injected": {
|
|
117
|
+
extension: Injected;
|
|
118
|
+
extensionName: string;
|
|
119
|
+
};
|
|
169
120
|
}
|
|
170
121
|
}
|
|
171
122
|
//#endregion
|
|
172
|
-
export { type InjectedPolkadotDiscoveryOptions,
|
|
123
|
+
export { type InjectedPolkadotDiscoveryOptions, type PolkadotSignMessageFeature, type PolkadotSignMessageInput, type PolkadotSignMessageOutput, buildInjectedPolkadotAdapter, buildPolkadotWalletStandardAdapter, discoverInjectedPolkadotAdapters, discoverPolkadotWalletStandardAdapters, polkadotDiscoverer };
|
|
173
124
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/injected/injected-web3.ts","../src/injected/adapter.ts","../src/injected/index.ts","../src/wallet-standard-types.ts","../src/wallet-standard-adapter.ts","../src/discoverer.ts","../src/signer-augmentation.ts"],"mappings":";;;;;;;;;;KAQK;EACH;EACA;EACA;EACA;;;;KAKG;EACH,WAAW;IACT;IACA;IACA;QACI;IAAU;IAAY;;;;KAIzB;EACH;IACE,WAAW,QAAQ,cAAc;IACjC,aAAa,KAAK,UAAU,cAAc;;EAE5C,QAAQ;;;KAIL;EACH,SAAS,mBAAmB,QAAQ;EACpC;;KAGG;EACH,eAAe,eAAe;;QAGxB;YAEI;IACR,eAAe,eAAe;;;;;;;;;;cCiB5B,+BAA4B,uBACX,qBACF,UACT,2BACT;;;KChCE;;;EAGH,SAAS;;EAET,SAAS;;;;;;;cAUL,mCAAgC,YACxB,SAAS,wBAAsB,UAClC;;;KC9CN;EACH,SAAS;EACT,SAAS;;KAGN;EACH,WAAW;EACX,gBAAgB;;KAGb;EACH,cAAc,OAAO,6BAA6B,QAAQ;EAC1D;;;;cCPI,qCAAkC,QAC9B,sBAIe;;;;AAAA,wBAAC,8BACvB;;;;;cA0CG,yCAAsC,YAC9B,SAAS;;;;;;;;cCnDjB,oBAAoB;;;;;;;;;YCDd;IACR;MAAuB,WAAW;MAAU"}
|
package/dist/index.js
CHANGED
|
@@ -1,89 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { POLKADOT_CHAINS, POLKADOT_CHAINS_LIST, buildAccount, bytesToHexPrefixed as bytesToHex, hexToBytes, logWarn, resolveChain, sanitizeIcon } from "@usebutr/core";
|
|
2
|
+
import { createWalletStandardCore, discoverWalletStandard, getFeature, slugify } from "@usebutr/wallet-standard-shared";
|
|
3
3
|
|
|
4
|
-
//#region src/chains.ts
|
|
5
|
-
const POLKADOT_CHAINS = {
|
|
6
|
-
kusama: {
|
|
7
|
-
id: "polkadot:b0a8d493285c2df73290dfb7e61f870f",
|
|
8
|
-
name: "Kusama",
|
|
9
|
-
namespace: "polkadot",
|
|
10
|
-
reference: "b0a8d493285c2df73290dfb7e61f870f"
|
|
11
|
-
},
|
|
12
|
-
paseo: {
|
|
13
|
-
id: "polkadot:77afd6190f1554ad45fd0d31aee62aac",
|
|
14
|
-
name: "Paseo",
|
|
15
|
-
namespace: "polkadot",
|
|
16
|
-
reference: "77afd6190f1554ad45fd0d31aee62aac"
|
|
17
|
-
},
|
|
18
|
-
polkadot: {
|
|
19
|
-
id: "polkadot:91b171bb158e2d3848fa23a9f1c25182",
|
|
20
|
-
name: "Polkadot",
|
|
21
|
-
namespace: "polkadot",
|
|
22
|
-
reference: "91b171bb158e2d3848fa23a9f1c25182"
|
|
23
|
-
},
|
|
24
|
-
westend: {
|
|
25
|
-
id: "polkadot:e143f23803ac50e8f6f8e62695d1ce9e",
|
|
26
|
-
name: "Westend",
|
|
27
|
-
namespace: "polkadot",
|
|
28
|
-
reference: "e143f23803ac50e8f6f8e62695d1ce9e"
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
const POLKADOT_CHAINS_LIST = Object.values(POLKADOT_CHAINS);
|
|
32
|
-
const POLKADOT_CHAIN_BY_ID = new Map(POLKADOT_CHAINS_LIST.map((chain) => [chain.id, chain]));
|
|
33
|
-
/** Chains a wallet advertising several networks should resolve to first.
|
|
34
|
-
* Kusama sits alongside Polkadot because it carries real value; Westend
|
|
35
|
-
* and Paseo are faucet testnets and must never win the default. */
|
|
36
|
-
const POLKADOT_MAINNET_IDS = [POLKADOT_CHAINS.polkadot.id, POLKADOT_CHAINS.kusama.id];
|
|
37
|
-
|
|
38
|
-
//#endregion
|
|
39
|
-
//#region src/capabilities.ts
|
|
40
|
-
/**
|
|
41
|
-
* injectedWeb3 always exposes `signer.signRaw` and `accounts.subscribe`, so
|
|
42
|
-
* those flags are unconditional. The chain count comes from butr's own
|
|
43
|
-
* registry because injectedWeb3 wallets advertise no chains.
|
|
44
|
-
*/
|
|
45
|
-
const resolveInjectedPolkadotCapabilities = () => buildWalletCapabilities({
|
|
46
|
-
chainCount: POLKADOT_CHAINS_LIST.length,
|
|
47
|
-
events: true,
|
|
48
|
-
sendTransaction: false,
|
|
49
|
-
signIn: false,
|
|
50
|
-
signMessage: true,
|
|
51
|
-
signTransaction: false
|
|
52
|
-
});
|
|
53
|
-
/**
|
|
54
|
-
* Wallet Standard `polkadot:*` feature → butr capability mapping. No
|
|
55
|
-
* standalone `signTransaction`: building an extrinsic needs chain metadata
|
|
56
|
-
* butr doesn't fetch, so transaction signing goes through `getSigner()`.
|
|
57
|
-
*/
|
|
58
|
-
const resolveWalletStandardPolkadotCapabilities = (input) => buildWalletCapabilities({
|
|
59
|
-
chainCount: input.chainCount,
|
|
60
|
-
events: input.features.events,
|
|
61
|
-
sendTransaction: false,
|
|
62
|
-
signIn: false,
|
|
63
|
-
signMessage: input.features.signMessage,
|
|
64
|
-
signTransaction: false
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
//#endregion
|
|
68
|
-
//#region src/no-rpc.ts
|
|
69
|
-
/**
|
|
70
|
-
* Building an extrinsic or reading on-chain state both need chain metadata
|
|
71
|
-
* butr doesn't fetch, so it ships no Polkadot RPC. The neutral balance and
|
|
72
|
-
* receipt values are gated behind the matching `capabilities` flags.
|
|
73
|
-
*/
|
|
74
|
-
const POLKADOT_SEND_TX_HINT = "Polkadot sendTx is unsupported: use getSigner() with polkadot-api to build and submit extrinsics";
|
|
75
|
-
const POLKADOT_SEND_TX_TO_CHAIN_HINT = "Polkadot sendTxToChain is unsupported: use getSigner() with polkadot-api to build and submit extrinsics";
|
|
76
|
-
const noRpcBalance = () => Promise.resolve({
|
|
77
|
-
decimals: 0,
|
|
78
|
-
formatted: "0",
|
|
79
|
-
symbol: "",
|
|
80
|
-
value: 0n
|
|
81
|
-
});
|
|
82
|
-
const noRpcTransactionReceipt = () => Promise.resolve({ status: "Pending" });
|
|
83
|
-
const noRpcSendTx = () => Promise.reject(/* @__PURE__ */ new Error(POLKADOT_SEND_TX_HINT));
|
|
84
|
-
const noRpcSendTxToChain = () => Promise.reject(/* @__PURE__ */ new Error(POLKADOT_SEND_TX_TO_CHAIN_HINT));
|
|
85
|
-
|
|
86
|
-
//#endregion
|
|
87
4
|
//#region src/injected/icon.ts
|
|
88
5
|
const GENERIC_POLKADOT_ICON = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMiAzMiI+PGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTYiIGZpbGw9IiNFNjAwN0EiLz48L3N2Zz4=";
|
|
89
6
|
|
|
@@ -113,32 +30,23 @@ const DAPP_NAME = "butr";
|
|
|
113
30
|
* `injected:polkadot:<slug>` convention.
|
|
114
31
|
*/
|
|
115
32
|
const toKebab = (name) => name.trim().toLowerCase().replaceAll(new RegExp("[^a-z0-9]+", "gv"), "-").replaceAll(new RegExp("^-|-$", "gv"), "");
|
|
116
|
-
const buildPolkadotAccount = (address, chain) => ({
|
|
117
|
-
chain,
|
|
118
|
-
id: `${chain.id}:${address}`,
|
|
119
|
-
walletAddress: address
|
|
120
|
-
});
|
|
121
33
|
/**
|
|
122
|
-
*
|
|
123
|
-
*
|
|
34
|
+
* An account works on any Substrate chain unless the extension pins it to
|
|
35
|
+
* one through `genesisHash`, whose first 16 bytes are the CAIP-2 reference.
|
|
36
|
+
* Unpinned accounts are labelled Polkadot, butr's default network.
|
|
37
|
+
*/
|
|
38
|
+
const chainOf = ({ genesisHash }) => genesisHash === void 0 || genesisHash === null || genesisHash === "" ? POLKADOT_CHAINS.polkadot : resolveChain(`polkadot:${genesisHash.replace(new RegExp("^0x", "v"), "").slice(0, 32)}`, POLKADOT_CHAINS_LIST);
|
|
39
|
+
const toAccount = (account) => buildAccount(account.address, chainOf(account));
|
|
40
|
+
/**
|
|
41
|
+
* `enable()` prompts, so it waits for `connect()`. No `switchChain`: the
|
|
42
|
+
* extension has no network to switch and nothing here takes a chain; an
|
|
43
|
+
* extrinsic carries its genesis hash in the payload polkadot-api builds.
|
|
124
44
|
*/
|
|
125
45
|
const buildInjectedPolkadotAdapter = (extensionName, displayName, provider) => {
|
|
126
|
-
const capabilities = resolveInjectedPolkadotCapabilities();
|
|
127
46
|
let session = null;
|
|
128
|
-
|
|
129
|
-
const listenersSet = /* @__PURE__ */ new Set();
|
|
47
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
130
48
|
const emit = (event) => {
|
|
131
|
-
const
|
|
132
|
-
for (const listener of snapshot) listener(event);
|
|
133
|
-
};
|
|
134
|
-
const emitAccounts = (accounts) => {
|
|
135
|
-
const built = accounts.map((a) => buildPolkadotAccount(a.address, chain));
|
|
136
|
-
const first = built[0];
|
|
137
|
-
if (first !== void 0) emit({
|
|
138
|
-
account: first,
|
|
139
|
-
accounts: built,
|
|
140
|
-
type: "accountChanged"
|
|
141
|
-
});
|
|
49
|
+
for (const listener of listeners) listener(event);
|
|
142
50
|
};
|
|
143
51
|
const closeSession = () => {
|
|
144
52
|
session?.unsubscribe?.();
|
|
@@ -150,7 +58,10 @@ const buildInjectedPolkadotAdapter = (extensionName, displayName, provider) => {
|
|
|
150
58
|
emit({ type: "disconnected" });
|
|
151
59
|
return;
|
|
152
60
|
}
|
|
153
|
-
|
|
61
|
+
emit({
|
|
62
|
+
accounts: accounts.map(toAccount),
|
|
63
|
+
type: "accountsChanged"
|
|
64
|
+
});
|
|
154
65
|
};
|
|
155
66
|
const openSession = (injected) => {
|
|
156
67
|
closeSession();
|
|
@@ -172,88 +83,79 @@ const buildInjectedPolkadotAdapter = (extensionName, displayName, provider) => {
|
|
|
172
83
|
if (session === null) throw new Error(`Wallet ${displayName} is not connected`);
|
|
173
84
|
return session.injected;
|
|
174
85
|
};
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
return (
|
|
86
|
+
const subscribe = (listener) => {
|
|
87
|
+
listeners.add(listener);
|
|
88
|
+
return () => {
|
|
89
|
+
listeners.delete(listener);
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
const signMessage = async (message, options) => {
|
|
93
|
+
const injected = requireInjected();
|
|
94
|
+
if (injected.signer.signRaw === void 0) throw new Error(`Wallet ${displayName} does not expose signRaw`);
|
|
95
|
+
const exposed = await injected.accounts.get();
|
|
96
|
+
const requested = options?.account;
|
|
97
|
+
const match = requested === void 0 ? exposed[0] : exposed.find((a) => a.address === requested.walletAddress);
|
|
98
|
+
if (match === void 0) throw new Error(requested === void 0 ? `Wallet ${displayName} has no connected account` : `Wallet ${displayName} does not expose account ${requested.walletAddress}`);
|
|
99
|
+
const wrapped = wrapBytes(message);
|
|
100
|
+
const result = await injected.signer.signRaw({
|
|
101
|
+
address: match.address,
|
|
102
|
+
data: bytesToHex(wrapped),
|
|
103
|
+
type: "bytes"
|
|
104
|
+
});
|
|
105
|
+
return {
|
|
106
|
+
signature: hexToBytes(result.signature),
|
|
107
|
+
signedMessage: wrapped
|
|
108
|
+
};
|
|
178
109
|
};
|
|
179
110
|
return {
|
|
180
|
-
capabilities,
|
|
181
111
|
chainPlatform: "polkadot",
|
|
182
112
|
async connect() {
|
|
183
113
|
const injected = await provider.enable(DAPP_NAME);
|
|
184
114
|
if ((await injected.accounts.get()).length === 0) throw new Error(`Wallet ${displayName} exposed no accounts`);
|
|
185
115
|
openSession(injected);
|
|
186
116
|
},
|
|
187
|
-
disconnect
|
|
117
|
+
async disconnect() {
|
|
188
118
|
closeSession();
|
|
189
|
-
|
|
190
|
-
},
|
|
191
|
-
async getAccount() {
|
|
192
|
-
const address = await firstAddress();
|
|
193
|
-
return address === null ? null : buildPolkadotAccount(address, chain);
|
|
119
|
+
await Promise.resolve();
|
|
194
120
|
},
|
|
195
121
|
async getAccounts() {
|
|
196
122
|
if (session === null) return [];
|
|
197
|
-
return (await session.injected.accounts.get()).map(
|
|
123
|
+
return (await session.injected.accounts.get()).map(toAccount);
|
|
198
124
|
},
|
|
199
|
-
getBalance: noRpcBalance,
|
|
200
125
|
async getSigner() {
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
if (address === null) throw new Error("No connected account");
|
|
126
|
+
const extension = requireInjected();
|
|
127
|
+
await Promise.resolve();
|
|
204
128
|
return {
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
129
|
+
extension,
|
|
130
|
+
extensionName,
|
|
131
|
+
kind: "polkadot-injected"
|
|
208
132
|
};
|
|
209
133
|
},
|
|
210
|
-
getTransactionReceipt: noRpcTransactionReceipt,
|
|
211
134
|
icon: sanitizeIcon(GENERIC_POLKADOT_ICON),
|
|
212
135
|
id: `injected:polkadot:${toKebab(extensionName)}`,
|
|
213
136
|
name: displayName,
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
async signMessage(msg, account) {
|
|
217
|
-
const ext = requireInjected();
|
|
218
|
-
if (ext.signer.signRaw === void 0) throw new Error(`Wallet ${displayName} does not expose signRaw`);
|
|
219
|
-
const address = account?.walletAddress ?? await firstAddress();
|
|
220
|
-
if (address === null || address === "") throw new Error("No connected account");
|
|
221
|
-
const wrapped = wrapBytes(msg);
|
|
222
|
-
const result = await ext.signer.signRaw({
|
|
223
|
-
address,
|
|
224
|
-
data: bytesToHex(wrapped),
|
|
225
|
-
type: "bytes"
|
|
226
|
-
});
|
|
227
|
-
return {
|
|
228
|
-
signature: hexToBytes(result.signature),
|
|
229
|
-
signedMessage: wrapped
|
|
230
|
-
};
|
|
137
|
+
get signMessage() {
|
|
138
|
+
return session?.injected.signer.signRaw === void 0 ? void 0 : signMessage;
|
|
231
139
|
},
|
|
232
|
-
subscribe(
|
|
233
|
-
|
|
234
|
-
return () => {
|
|
235
|
-
listenersSet.delete(listener);
|
|
236
|
-
};
|
|
237
|
-
},
|
|
238
|
-
async switchChain(target) {
|
|
239
|
-
if (target.namespace !== "polkadot") throw new Error(`Polkadot adapter received non-Polkadot chain "${target.id}". Pass a chain with namespace "polkadot".`);
|
|
240
|
-
chain = POLKADOT_CHAIN_BY_ID.get(target.id) ?? target;
|
|
241
|
-
if (session === null) return;
|
|
242
|
-
emitAccounts(await session.injected.accounts.get());
|
|
140
|
+
get subscribe() {
|
|
141
|
+
return (session?.unsubscribe ?? null) === null ? void 0 : subscribe;
|
|
243
142
|
}
|
|
244
143
|
};
|
|
245
144
|
};
|
|
246
145
|
|
|
247
146
|
//#endregion
|
|
248
147
|
//#region src/injected/index.ts
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
148
|
+
const knownDisplayNameFor = (key) => {
|
|
149
|
+
switch (key) {
|
|
150
|
+
case "enkrypt": return "Enkrypt";
|
|
151
|
+
case "nova-wallet": return "Nova Wallet";
|
|
152
|
+
case "polkadot-js": return "Polkadot{.js}";
|
|
153
|
+
case "subwallet-js": return "SubWallet";
|
|
154
|
+
case "talisman": return "Talisman";
|
|
155
|
+
default: return;
|
|
156
|
+
}
|
|
255
157
|
};
|
|
256
|
-
const displayNameFor = (key) =>
|
|
158
|
+
const displayNameFor = (key) => knownDisplayNameFor(key) ?? key.split(new RegExp("[\\-_]", "v")).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
257
159
|
const DEFAULT_POLLS = [250, 750];
|
|
258
160
|
/**
|
|
259
161
|
* Adapters are built without calling `enable()`, which would raise the
|
|
@@ -288,54 +190,39 @@ const discoverInjectedPolkadotAdapters = (onAdapter, options = {}) => {
|
|
|
288
190
|
|
|
289
191
|
//#endregion
|
|
290
192
|
//#region src/wallet-standard-adapter.ts
|
|
291
|
-
const POLKADOT_PREFIX = "polkadot:";
|
|
292
|
-
const slugify$1 = (name) => slugify("polkadot", name);
|
|
293
193
|
const buildPolkadotWalletStandardAdapter = (wallet, registerDisconnector) => {
|
|
294
194
|
const core = createWalletStandardCore({
|
|
295
|
-
|
|
296
|
-
id: slugify
|
|
195
|
+
chains: POLKADOT_CHAINS_LIST,
|
|
196
|
+
id: slugify("polkadot", wallet.name),
|
|
297
197
|
label: "Polkadot",
|
|
298
198
|
namespace: "polkadot",
|
|
299
|
-
|
|
300
|
-
preferredChainIds: POLKADOT_MAINNET_IDS,
|
|
199
|
+
preferredChainIds: [POLKADOT_CHAINS.polkadot.id, POLKADOT_CHAINS.kusama.id],
|
|
301
200
|
registerDisconnector,
|
|
302
201
|
trackChainChanges: false,
|
|
303
202
|
wallet
|
|
304
203
|
});
|
|
305
204
|
if (core === null) return null;
|
|
306
|
-
const
|
|
205
|
+
const signer = getFeature(wallet, "polkadot:signMessage", "signMessage");
|
|
307
206
|
return {
|
|
308
|
-
...core,
|
|
309
|
-
capabilities: resolveWalletStandardPolkadotCapabilities({
|
|
310
|
-
chainCount: core.chainCount,
|
|
311
|
-
features: {
|
|
312
|
-
events: core.hasEvents,
|
|
313
|
-
signMessage: Boolean(signMessage)
|
|
314
|
-
}
|
|
315
|
-
}),
|
|
207
|
+
...core.base,
|
|
316
208
|
chainPlatform: "polkadot",
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
async signMessage(msg, account) {
|
|
322
|
-
if (signMessage === void 0) throw new Error(`Wallet ${wallet.name} does not advertise polkadot:signMessage`);
|
|
323
|
-
const output = await signMessage.signMessage({
|
|
324
|
-
account: core.resolveAccount(account),
|
|
325
|
-
message: msg
|
|
209
|
+
...signer !== void 0 && { signMessage: async (message, options) => {
|
|
210
|
+
const output = await signer.signMessage({
|
|
211
|
+
account: core.resolveAccount(options?.account),
|
|
212
|
+
message
|
|
326
213
|
});
|
|
327
214
|
return {
|
|
328
215
|
signature: output.signature,
|
|
329
|
-
signedMessage: output.signedMessage ??
|
|
216
|
+
signedMessage: output.signedMessage ?? message
|
|
330
217
|
};
|
|
331
|
-
}
|
|
218
|
+
} }
|
|
332
219
|
};
|
|
333
220
|
};
|
|
334
221
|
/**
|
|
335
222
|
* The fallback channel; see `polkadotDiscoverer`. Requires the optional
|
|
336
223
|
* `@wallet-standard/app` peer dep and no-ops without it.
|
|
337
224
|
*/
|
|
338
|
-
const discoverPolkadotWalletStandardAdapters = (onAdapter) => discoverWalletStandard(onAdapter,
|
|
225
|
+
const discoverPolkadotWalletStandardAdapters = (onAdapter) => discoverWalletStandard(onAdapter, buildPolkadotWalletStandardAdapter);
|
|
339
226
|
|
|
340
227
|
//#endregion
|
|
341
228
|
//#region src/discoverer.ts
|
|
@@ -353,5 +240,5 @@ const polkadotDiscoverer = {
|
|
|
353
240
|
};
|
|
354
241
|
|
|
355
242
|
//#endregion
|
|
356
|
-
export {
|
|
243
|
+
export { buildInjectedPolkadotAdapter, buildPolkadotWalletStandardAdapter, discoverInjectedPolkadotAdapters, discoverPolkadotWalletStandardAdapters, polkadotDiscoverer };
|
|
357
244
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["slugify","kitSlugify"],"sources":["../src/chains.ts","../src/capabilities.ts","../src/no-rpc.ts","../src/injected/icon.ts","../src/injected/injected-web3.ts","../src/injected/adapter.ts","../src/injected/index.ts","../src/wallet-standard-adapter.ts","../src/discoverer.ts"],"sourcesContent":["import type { ChainBase } from \"@usebutr/core\";\n\nconst POLKADOT_CHAINS = {\n kusama: {\n id: \"polkadot:b0a8d493285c2df73290dfb7e61f870f\",\n name: \"Kusama\",\n namespace: \"polkadot\",\n reference: \"b0a8d493285c2df73290dfb7e61f870f\",\n },\n paseo: {\n id: \"polkadot:77afd6190f1554ad45fd0d31aee62aac\",\n name: \"Paseo\",\n namespace: \"polkadot\",\n reference: \"77afd6190f1554ad45fd0d31aee62aac\",\n },\n polkadot: {\n id: \"polkadot:91b171bb158e2d3848fa23a9f1c25182\",\n name: \"Polkadot\",\n namespace: \"polkadot\",\n reference: \"91b171bb158e2d3848fa23a9f1c25182\",\n },\n westend: {\n id: \"polkadot:e143f23803ac50e8f6f8e62695d1ce9e\",\n name: \"Westend\",\n namespace: \"polkadot\",\n reference: \"e143f23803ac50e8f6f8e62695d1ce9e\",\n },\n} as const satisfies Record<string, ChainBase>;\n\nconst POLKADOT_CHAINS_LIST: ReadonlyArray<ChainBase> = Object.values(POLKADOT_CHAINS);\n\nconst POLKADOT_CHAIN_BY_ID: ReadonlyMap<string, ChainBase> = new Map(\n POLKADOT_CHAINS_LIST.map((chain) => [chain.id, chain]),\n);\n\n/** Chains a wallet advertising several networks should resolve to first.\n * Kusama sits alongside Polkadot because it carries real value; Westend\n * and Paseo are faucet testnets and must never win the default. */\nconst POLKADOT_MAINNET_IDS: ReadonlyArray<string> = [\n POLKADOT_CHAINS.polkadot.id,\n POLKADOT_CHAINS.kusama.id,\n];\n\nexport { POLKADOT_CHAIN_BY_ID, POLKADOT_CHAINS, POLKADOT_CHAINS_LIST, POLKADOT_MAINNET_IDS };\n","import type { WalletCapabilities } from \"@usebutr/core\";\nimport { buildWalletCapabilities } from \"@usebutr/wallet-standard-shared\";\n\nimport { POLKADOT_CHAINS_LIST } from \"./chains\";\n\ntype WalletStandardPolkadotCapabilityInput = {\n chainCount: number;\n features: {\n events: boolean;\n signMessage: boolean;\n };\n};\n\n/**\n * injectedWeb3 always exposes `signer.signRaw` and `accounts.subscribe`, so\n * those flags are unconditional. The chain count comes from butr's own\n * registry because injectedWeb3 wallets advertise no chains.\n */\nconst resolveInjectedPolkadotCapabilities = (): WalletCapabilities =>\n buildWalletCapabilities({\n chainCount: POLKADOT_CHAINS_LIST.length,\n events: true,\n sendTransaction: false,\n signIn: false,\n signMessage: true,\n signTransaction: false,\n });\n\n/**\n * Wallet Standard `polkadot:*` feature → butr capability mapping. No\n * standalone `signTransaction`: building an extrinsic needs chain metadata\n * butr doesn't fetch, so transaction signing goes through `getSigner()`.\n */\nconst resolveWalletStandardPolkadotCapabilities = (\n input: WalletStandardPolkadotCapabilityInput,\n): WalletCapabilities =>\n buildWalletCapabilities({\n chainCount: input.chainCount,\n events: input.features.events,\n sendTransaction: false,\n signIn: false,\n signMessage: input.features.signMessage,\n signTransaction: false,\n });\n\nexport type { WalletStandardPolkadotCapabilityInput };\nexport { resolveInjectedPolkadotCapabilities, resolveWalletStandardPolkadotCapabilities };\n","import type { Balance } from \"@usebutr/core\";\n\n/**\n * Building an extrinsic or reading on-chain state both need chain metadata\n * butr doesn't fetch, so it ships no Polkadot RPC. The neutral balance and\n * receipt values are gated behind the matching `capabilities` flags.\n */\nconst POLKADOT_SEND_TX_HINT =\n \"Polkadot sendTx is unsupported: use getSigner() with polkadot-api to build and submit extrinsics\";\nconst POLKADOT_SEND_TX_TO_CHAIN_HINT =\n \"Polkadot sendTxToChain is unsupported: use getSigner() with polkadot-api to build and submit extrinsics\";\n\nconst noRpcBalance = (): Promise<Balance> =>\n Promise.resolve({ decimals: 0, formatted: \"0\", symbol: \"\", value: 0n });\n\nconst noRpcTransactionReceipt = (): Promise<{ status: \"Success\" | \"Error\" | \"Pending\" }> =>\n Promise.resolve({ status: \"Pending\" });\n\nconst noRpcSendTx = (): Promise<string> => Promise.reject(new Error(POLKADOT_SEND_TX_HINT));\n\nconst noRpcSendTxToChain = (): Promise<string> =>\n Promise.reject(new Error(POLKADOT_SEND_TX_TO_CHAIN_HINT));\n\nexport { noRpcBalance, noRpcSendTx, noRpcSendTxToChain, noRpcTransactionReceipt };\n","const GENERIC_POLKADOT_ICON =\n \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMiAzMiI+PGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTYiIGZpbGw9IiNFNjAwN0EiLz48L3N2Zz4=\";\n\nexport { GENERIC_POLKADOT_ICON };\n","/**\n * Local narrowing of the `@polkadot/extension-dapp` injectedWeb3 standard\n * to the fields butr reads, so the connector takes no dependency on\n * `@polkadot/extension-inject`.\n */\n\n/** A single account the extension exposes. Addresses are SS58; accounts\n * are chain-agnostic across Substrate. */\ntype InjectedAccount = {\n address: string;\n genesisHash?: string | null;\n name?: string;\n type?: string;\n};\n\n/** The polkadot-js `Signer`: butr only uses `signRaw` for message\n * signing. `signPayload` is consumer territory (via polkadot-api). */\ntype InjectedSigner = {\n signRaw?: (raw: {\n address: string;\n data: string;\n type: \"bytes\" | \"payload\";\n }) => Promise<{ id: number; signature: string }>;\n};\n\n/** The object returned by `enable()`. */\ntype Injected = {\n accounts: {\n get: () => Promise<ReadonlyArray<InjectedAccount>>;\n subscribe?: (cb: (accounts: ReadonlyArray<InjectedAccount>) => void) => () => void;\n };\n signer: InjectedSigner;\n};\n\n/** What lives at `window.injectedWeb3[key]`. */\ntype InjectedWindowProvider = {\n enable: (origin: string) => Promise<Injected>;\n version?: string;\n};\n\ntype InjectedWindow = {\n injectedWeb3?: Record<string, InjectedWindowProvider>;\n};\n\nconst BYTES_PREFIX = new TextEncoder().encode(\"<Bytes>\");\nconst BYTES_SUFFIX = new TextEncoder().encode(\"</Bytes>\");\n\nconst wrapBytes = (message: Uint8Array): Uint8Array => {\n const out = new Uint8Array(BYTES_PREFIX.length + message.length + BYTES_SUFFIX.length);\n out.set(BYTES_PREFIX, 0);\n out.set(message, BYTES_PREFIX.length);\n out.set(BYTES_SUFFIX, BYTES_PREFIX.length + message.length);\n return out;\n};\n\nconst readInjectedWindow = (target?: InjectedWindow | null): InjectedWindow | null => {\n if (target !== undefined) {\n return target;\n }\n if (typeof window === \"undefined\") {\n return null;\n }\n // `window.injectedWeb3` is the untyped Polkadot extension registry; the\n // DOM lib doesn't declare it, so this boundary assertion is unavoidable.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion, anti-slop/no-chained-type-assertions -- untyped window.injectedWeb3 extension registry\n return window as unknown as InjectedWindow;\n};\n\nexport type { Injected, InjectedAccount, InjectedSigner, InjectedWindow, InjectedWindowProvider };\nexport { bytesToHexPrefixed as bytesToHex, hexToBytes } from \"@usebutr/core\";\nexport { readInjectedWindow, wrapBytes };\n","import type {\n Account,\n ChainBase,\n ConnectorEvent,\n PolkadotAdapter,\n WalletCapabilities,\n} from \"@usebutr/core\";\nimport { logWarn, sanitizeIcon } from \"@usebutr/core\";\n\nimport { resolveInjectedPolkadotCapabilities } from \"../capabilities\";\nimport { POLKADOT_CHAIN_BY_ID, POLKADOT_CHAINS } from \"../chains\";\nimport { noRpcBalance, noRpcSendTx, noRpcSendTxToChain, noRpcTransactionReceipt } from \"../no-rpc\";\n\nimport { GENERIC_POLKADOT_ICON } from \"./icon\";\nimport type { Injected, InjectedAccount, InjectedWindowProvider } from \"./injected-web3\";\nimport { bytesToHex, hexToBytes, wrapBytes } from \"./injected-web3\";\n\nconst DAPP_NAME = \"butr\";\n\n/** Handle returned by `getSigner()`. Carries the `window.injectedWeb3`\n * key (`extensionName`) so consumers can bridge to polkadot-api's\n * `connectInjectedExtension`, the active SS58 address, and the raw\n * `Injected` object for direct `signer` access. */\ntype PolkadotSignerHandle = {\n address: string;\n extension: Injected;\n extensionName: string;\n};\n\n/**\n * Deliberately not wallet-standard-shared's `slugify`: that helper embeds\n * the `wallet-standard:` scheme, while injected adapter ids follow the\n * `injected:polkadot:<slug>` convention.\n */\nconst toKebab = (name: string): string =>\n name\n .trim()\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/gv, \"-\")\n .replaceAll(/^-|-$/gv, \"\");\n\nconst buildPolkadotAccount = (address: string, chain: ChainBase): Account => ({\n chain,\n id: `${chain.id}:${address}`,\n walletAddress: address,\n});\n\n/** Everything that only exists between `connect()` and `disconnect()`: the\n * enabled provider and the wallet-side account subscription opened against\n * it. One value so the adapter can never be half-connected. */\ntype InjectedSession = {\n injected: Injected;\n unsubscribe: (() => void) | null;\n};\n\n/**\n * The provider is not enabled at construction: `enable()` raises the\n * extension's authorization prompt, so it runs lazily in `connect()`.\n */\nconst buildInjectedPolkadotAdapter = (\n extensionName: string,\n displayName: string,\n provider: InjectedWindowProvider,\n): PolkadotAdapter => {\n const capabilities: WalletCapabilities = resolveInjectedPolkadotCapabilities();\n let session: InjectedSession | null = null;\n let chain: ChainBase = POLKADOT_CHAINS.polkadot;\n const listenersSet = new Set<(event: ConnectorEvent) => void>();\n\n const emit = (event: ConnectorEvent): void => {\n // Snapshot: a listener is free to unsubscribe others from inside its\n // callback, and every listener registered at emit time still gets this\n // event.\n const snapshot = [...listenersSet];\n for (const listener of snapshot) {\n listener(event);\n }\n };\n\n const emitAccounts = (accounts: ReadonlyArray<InjectedAccount>): void => {\n const built = accounts.map((a) => buildPolkadotAccount(a.address, chain));\n const first = built[0];\n if (first !== undefined) {\n emit({ account: first, accounts: built, type: \"accountChanged\" });\n }\n };\n\n const closeSession = (): void => {\n session?.unsubscribe?.();\n session = null;\n };\n\n const handleWalletAccounts = (accounts: ReadonlyArray<InjectedAccount>): void => {\n if (accounts.length === 0) {\n closeSession();\n emit({ type: \"disconnected\" });\n return;\n }\n emitAccounts(accounts);\n };\n\n const openSession = (injected: Injected): void => {\n closeSession();\n const opened: InjectedSession = { injected, unsubscribe: null };\n session = opened;\n try {\n const unsubscribe = injected.accounts.subscribe?.(handleWalletAccounts);\n if (unsubscribe === undefined) {\n return;\n }\n // Wallets may fire the callback synchronously; an empty first payload\n // closes the session before this assignment, so never revive it.\n if (session === opened) {\n opened.unsubscribe = unsubscribe;\n } else {\n unsubscribe();\n }\n } catch (error) {\n logWarn(`[butr/polkadot] ${displayName} accounts.subscribe threw:`, error);\n }\n };\n\n const requireInjected = (): Injected => {\n if (session === null) {\n throw new Error(`Wallet ${displayName} is not connected`);\n }\n return session.injected;\n };\n\n const firstAddress = async (): Promise<string | null> => {\n if (session === null) {\n return null;\n }\n const accounts = await session.injected.accounts.get();\n return accounts[0]?.address ?? null;\n };\n\n return {\n capabilities,\n chainPlatform: \"polkadot\",\n\n async connect() {\n const injected = await provider.enable(DAPP_NAME);\n const accounts = await injected.accounts.get();\n if (accounts.length === 0) {\n throw new Error(`Wallet ${displayName} exposed no accounts`);\n }\n openSession(injected);\n },\n\n disconnect: () => {\n closeSession();\n return Promise.resolve();\n },\n\n async getAccount() {\n const address = await firstAddress();\n return address === null ? null : buildPolkadotAccount(address, chain);\n },\n\n async getAccounts() {\n if (session === null) {\n return [];\n }\n const accounts = await session.injected.accounts.get();\n return accounts.map((a) => buildPolkadotAccount(a.address, chain));\n },\n\n getBalance: noRpcBalance,\n\n async getSigner() {\n const ext = requireInjected();\n const address = await firstAddress();\n if (address === null) {\n throw new Error(\"No connected account\");\n }\n const handle: PolkadotSignerHandle = { address, extension: ext, extensionName };\n return handle;\n },\n\n getTransactionReceipt: noRpcTransactionReceipt,\n\n icon: sanitizeIcon(GENERIC_POLKADOT_ICON),\n id: `injected:polkadot:${toKebab(extensionName)}`,\n name: displayName,\n\n sendTx: noRpcSendTx,\n\n sendTxToChain: noRpcSendTxToChain,\n\n async signMessage(msg, account) {\n const ext = requireInjected();\n if (ext.signer.signRaw === undefined) {\n throw new Error(`Wallet ${displayName} does not expose signRaw`);\n }\n const address = account?.walletAddress ?? (await firstAddress());\n if (address === null || address === \"\") {\n throw new Error(\"No connected account\");\n }\n const wrapped = wrapBytes(msg);\n const result = await ext.signer.signRaw({\n address,\n data: bytesToHex(wrapped),\n type: \"bytes\",\n });\n return { signature: hexToBytes(result.signature), signedMessage: wrapped };\n },\n\n subscribe(listener) {\n listenersSet.add(listener);\n return () => {\n listenersSet.delete(listener);\n };\n },\n\n async switchChain(target) {\n if (target.namespace !== \"polkadot\") {\n throw new Error(\n `Polkadot adapter received non-Polkadot chain \"${target.id}\". Pass a chain with namespace \"polkadot\".`,\n );\n }\n chain = POLKADOT_CHAIN_BY_ID.get(target.id) ?? target;\n if (session === null) {\n return;\n }\n emitAccounts(await session.injected.accounts.get());\n },\n };\n};\n\nexport type { PolkadotSignerHandle };\nexport { buildInjectedPolkadotAdapter };\n","import type { WalletAdapter } from \"@usebutr/core\";\n\nimport { buildInjectedPolkadotAdapter } from \"./adapter\";\nimport type { InjectedWindow } from \"./injected-web3\";\nimport { readInjectedWindow } from \"./injected-web3\";\n\nconst KNOWN_NAMES: Readonly<Record<string, string>> = {\n enkrypt: \"Enkrypt\",\n \"nova-wallet\": \"Nova Wallet\",\n \"polkadot-js\": \"Polkadot{.js}\",\n \"subwallet-js\": \"SubWallet\",\n talisman: \"Talisman\",\n};\n\nconst displayNameFor = (key: string): string =>\n KNOWN_NAMES[key] ??\n key\n .split(/[\\-_]/v)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n\ntype InjectedPolkadotDiscoveryOptions = {\n /** Poll schedule (ms offsets) for late-injecting extensions. Defaults\n * to a few short polls; pass `[]` in tests for a single sync read. */\n pollMs?: ReadonlyArray<number>;\n /** Override the global host (tests, iframes). */\n target?: InjectedWindow | null;\n};\n\nconst DEFAULT_POLLS: ReadonlyArray<number> = [250, 750];\n\n/**\n * Adapters are built without calling `enable()`, which would raise the\n * extension's authorization prompt at discovery time. Extensions inject at\n * different points during page load, hence the poll schedule.\n */\nconst discoverInjectedPolkadotAdapters = (\n onAdapter: (adapter: WalletAdapter) => void,\n options: InjectedPolkadotDiscoveryOptions = {},\n): (() => void) => {\n const polls = options.pollMs ?? DEFAULT_POLLS;\n const seen = new Set<string>();\n const timers: Array<ReturnType<typeof setTimeout>> = [];\n let cancelled = false;\n\n const scan = () => {\n if (cancelled) {\n return;\n }\n const host = readInjectedWindow(options.target);\n const registry = host?.injectedWeb3;\n if (!registry) {\n return;\n }\n for (const [key, provider] of Object.entries(registry)) {\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n onAdapter(buildInjectedPolkadotAdapter(key, displayNameFor(key), provider));\n }\n };\n\n scan();\n for (const offset of polls) {\n if (offset === 0) {\n continue;\n }\n timers.push(setTimeout(scan, offset));\n }\n\n return () => {\n cancelled = true;\n for (const timer of timers) {\n clearTimeout(timer);\n }\n };\n};\n\nexport type { InjectedPolkadotDiscoveryOptions };\nexport { discoverInjectedPolkadotAdapters };\n","import type { WalletAdapter } from \"@usebutr/core\";\nimport {\n createWalletStandardCore,\n discoverWalletStandard,\n getFeature,\n slugify as kitSlugify,\n} from \"@usebutr/wallet-standard-shared\";\nimport type { WalletStandardWallet } from \"@usebutr/wallet-standard-shared\";\n\nimport { resolveWalletStandardPolkadotCapabilities } from \"./capabilities\";\nimport { POLKADOT_MAINNET_IDS } from \"./chains\";\nimport { noRpcBalance, noRpcSendTx, noRpcSendTxToChain, noRpcTransactionReceipt } from \"./no-rpc\";\nimport type { PolkadotSignMessageFeature } from \"./wallet-standard-types\";\n\nconst POLKADOT_PREFIX = \"polkadot:\";\n\nconst slugify = (name: string): string => kitSlugify(\"polkadot\", name);\n\nconst buildPolkadotWalletStandardAdapter = (\n wallet: WalletStandardWallet,\n /** Optional. Called with a function that pushes a synthetic\n * `disconnected` event to all current subscribers. The discovery\n * layer invokes it on Wallet Standard `unregister`. */\n registerDisconnector?: (emit: () => void) => void,\n): WalletAdapter | null => {\n const core = createWalletStandardCore({\n chainPrefix: POLKADOT_PREFIX,\n id: slugify(wallet.name),\n label: \"Polkadot\",\n namespace: \"polkadot\",\n platform: \"Polkadot\",\n preferredChainIds: POLKADOT_MAINNET_IDS,\n registerDisconnector,\n trackChainChanges: false,\n wallet,\n });\n if (core === null) {\n return null;\n }\n\n const signMessage = getFeature<PolkadotSignMessageFeature>(wallet, \"polkadot:signMessage\");\n\n return {\n ...core,\n capabilities: resolveWalletStandardPolkadotCapabilities({\n chainCount: core.chainCount,\n features: { events: core.hasEvents, signMessage: Boolean(signMessage) },\n }),\n chainPlatform: \"polkadot\",\n\n getBalance: noRpcBalance,\n\n getTransactionReceipt: noRpcTransactionReceipt,\n\n sendTx: noRpcSendTx,\n\n sendTxToChain: noRpcSendTxToChain,\n\n async signMessage(msg, account) {\n if (signMessage === undefined) {\n throw new Error(`Wallet ${wallet.name} does not advertise polkadot:signMessage`);\n }\n const output = await signMessage.signMessage({\n account: core.resolveAccount(account),\n message: msg,\n });\n return { signature: output.signature, signedMessage: output.signedMessage ?? msg };\n },\n };\n};\n\n/**\n * The fallback channel; see `polkadotDiscoverer`. Requires the optional\n * `@wallet-standard/app` peer dep and no-ops without it.\n */\nconst discoverPolkadotWalletStandardAdapters = (\n onAdapter: (adapter: WalletAdapter) => void,\n): (() => void) =>\n discoverWalletStandard(onAdapter, (wallet, registerDisconnector) =>\n buildPolkadotWalletStandardAdapter(wallet, registerDisconnector),\n );\n\nexport { buildPolkadotWalletStandardAdapter, discoverPolkadotWalletStandardAdapters };\n","import type { PlatformDiscoverer } from \"@usebutr/core\";\n\nimport { discoverInjectedPolkadotAdapters } from \"./injected\";\nimport { discoverPolkadotWalletStandardAdapters } from \"./wallet-standard-adapter\";\n\n/**\n * Primary is injectedWeb3; Wallet Standard `polkadot:*` is the fallback. Its\n * defer is the only thing preventing double-listing: a wallet on both\n * channels mints two unrelated ids the discovery bus cannot collapse.\n */\nconst polkadotDiscoverer: PlatformDiscoverer = {\n fallback: {\n subscribe: (onAdapter, opts) => {\n if (opts.hasAnyPrimaryAdapter()) {\n return () => undefined;\n }\n return discoverPolkadotWalletStandardAdapters(onAdapter);\n },\n },\n subscribe: discoverInjectedPolkadotAdapters,\n};\n\nexport { polkadotDiscoverer };\n"],"mappings":";;;;AAEA,MAAM,kBAAkB;CACtB,QAAQ;EACN,IAAI;EACJ,MAAM;EACN,WAAW;EACX,WAAW;CACb;CACA,OAAO;EACL,IAAI;EACJ,MAAM;EACN,WAAW;EACX,WAAW;CACb;CACA,UAAU;EACR,IAAI;EACJ,MAAM;EACN,WAAW;EACX,WAAW;CACb;CACA,SAAS;EACP,IAAI;EACJ,MAAM;EACN,WAAW;EACX,WAAW;CACb;AACF;AAEA,MAAM,uBAAiD,OAAO,OAAO,eAAe;AAEpF,MAAM,uBAAuD,IAAI,IAC/D,qBAAqB,KAAK,UAAU,CAAC,MAAM,IAAI,KAAK,CAAC,CACvD;;;;AAKA,MAAM,uBAA8C,CAClD,gBAAgB,SAAS,IACzB,gBAAgB,OAAO,EACzB;;;;;;;;;ACvBA,MAAM,4CACJ,wBAAwB;CACtB,YAAY,qBAAqB;CACjC,QAAQ;CACR,iBAAiB;CACjB,QAAQ;CACR,aAAa;CACb,iBAAiB;AACnB,CAAC;;;;;;AAOH,MAAM,6CACJ,UAEA,wBAAwB;CACtB,YAAY,MAAM;CAClB,QAAQ,MAAM,S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AMA,aAAW,SAAyBC,QAAW,YAAY,IAAI;AAErE,MAAM,sCACJ,QAIA,yBACyB;CACzB,MAAM,OAAO,yBAAyB;EACpC,aAAa;EACb,IAAID,UAAQ,OAAO,IAAI;EACvB,OAAO;EACP,WAAW;EACX,UAAU;EACV,mBAAmB;EACnB;EACA,mBAAmB;EACnB;CACF,CAAC;CACD,IAAI,SAAS,MACX,OAAO;CAGT,MAAM,cAAc,WAAuC,QAAQ,sBAAsB;CAEzF,OAAO;EACL,GAAG;EACH,cAAc,0CAA0C;GACtD,YAAY,KAAK;GACjB,UAAU;IAAE,QAAQ,KAAK;IAAW,aAAa,QAAQ,WAAW;GAAE;EACxE,CAAC;EACD,eAAe;EAEf,YAAY;EAEZ,uBAAuB;EAEvB,QAAQ;EAER,eAAe;EAEf,MAAM,YAAY,KAAK,SAAS;GAC9B,IAAI,gBAAgB,QAClB,MAAM,IAAI,MAAM,UAAU,OAAO,KAAK,yCAAyC;GAEjF,MAAM,SAAS,MAAM,YAAY,YAAY;IAC3C,SAAS,KAAK,eAAe,OAAO;IACpC,SAAS;GACX,CAAC;GACD,OAAO;IAAE,WAAW,OAAO;IAAW,eAAe,OAAO,iBAAiB;GAAI;EACnF;CACF;AACF;;;;;AAMA,MAAM,0CACJ,cAEA,uBAAuB,YAAY,QAAQ,yBACzC,mCAAmC,QAAQ,oBAAoB,CACjE;;;;;;;;;ACtEF,MAAM,qBAAyC;CAC7C,UAAU,EACR,YAAY,WAAW,SAAS;EAC9B,IAAI,KAAK,qBAAqB,GAC5B,aAAa;EAEf,OAAO,uCAAuC,SAAS;CACzD,EACF;CACA,WAAW;AACb"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/injected/icon.ts","../src/injected/injected-web3.ts","../src/injected/adapter.ts","../src/injected/index.ts","../src/wallet-standard-adapter.ts","../src/discoverer.ts"],"sourcesContent":["const GENERIC_POLKADOT_ICON =\n \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMiAzMiI+PGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTYiIGZpbGw9IiNFNjAwN0EiLz48L3N2Zz4=\";\n\nexport { GENERIC_POLKADOT_ICON };\n","/**\n * Local narrowing of the `@polkadot/extension-dapp` injectedWeb3 standard\n * to the fields butr reads, so the connector takes no dependency on\n * `@polkadot/extension-inject`.\n */\n\n/** A single account the extension exposes. Addresses are SS58; accounts\n * are chain-agnostic across Substrate. */\ntype InjectedAccount = {\n address: string;\n genesisHash?: string | null;\n name?: string;\n type?: string;\n};\n\n/** The polkadot-js `Signer`: butr only uses `signRaw` for message\n * signing. `signPayload` is consumer territory (via polkadot-api). */\ntype InjectedSigner = {\n signRaw?: (raw: {\n address: string;\n data: string;\n type: \"bytes\" | \"payload\";\n }) => Promise<{ id: number; signature: string }>;\n};\n\n/** The object returned by `enable()`. */\ntype Injected = {\n accounts: {\n get: () => Promise<ReadonlyArray<InjectedAccount>>;\n subscribe?: (cb: (accounts: ReadonlyArray<InjectedAccount>) => void) => () => void;\n };\n signer: InjectedSigner;\n};\n\n/** What lives at `window.injectedWeb3[key]`. */\ntype InjectedWindowProvider = {\n enable: (origin: string) => Promise<Injected>;\n version?: string;\n};\n\ntype InjectedWindow = {\n injectedWeb3?: Record<string, InjectedWindowProvider>;\n};\n\ndeclare global {\n // oxlint-disable-next-line typescript/consistent-type-definitions -- DOM globals require interface merging.\n interface Window {\n injectedWeb3?: Record<string, InjectedWindowProvider>;\n }\n}\n\nconst BYTES_PREFIX = new TextEncoder().encode(\"<Bytes>\");\nconst BYTES_SUFFIX = new TextEncoder().encode(\"</Bytes>\");\n\nconst wrapBytes = (message: Uint8Array): Uint8Array => {\n const out = new Uint8Array(BYTES_PREFIX.length + message.length + BYTES_SUFFIX.length);\n out.set(BYTES_PREFIX, 0);\n out.set(message, BYTES_PREFIX.length);\n out.set(BYTES_SUFFIX, BYTES_PREFIX.length + message.length);\n return out;\n};\n\nconst readInjectedWindow = (target?: InjectedWindow | null): InjectedWindow | null => {\n if (target !== undefined) {\n return target;\n }\n if (typeof window === \"undefined\") {\n return null;\n }\n return window;\n};\n\nexport type { Injected, InjectedAccount, InjectedSigner, InjectedWindow, InjectedWindowProvider };\nexport { bytesToHexPrefixed as bytesToHex, hexToBytes } from \"@usebutr/core\";\nexport { readInjectedWindow, wrapBytes };\n","import type {\n Account,\n AccountOptions,\n ChainBase,\n ConnectorEvent,\n PolkadotAdapter,\n SignedMessage,\n} from \"@usebutr/core\";\nimport {\n buildAccount,\n logWarn,\n POLKADOT_CHAINS,\n POLKADOT_CHAINS_LIST,\n resolveChain,\n sanitizeIcon,\n} from \"@usebutr/core\";\n\nimport { GENERIC_POLKADOT_ICON } from \"./icon\";\nimport type { Injected, InjectedAccount, InjectedWindowProvider } from \"./injected-web3\";\nimport { bytesToHex, hexToBytes, wrapBytes } from \"./injected-web3\";\n\nconst DAPP_NAME = \"butr\";\n\n/**\n * Deliberately not wallet-standard-shared's `slugify`: that helper embeds\n * the `wallet-standard:` scheme, while injected adapter ids follow the\n * `injected:polkadot:<slug>` convention.\n */\nconst toKebab = (name: string): string =>\n name\n .trim()\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/gv, \"-\")\n .replaceAll(/^-|-$/gv, \"\");\n\n/**\n * An account works on any Substrate chain unless the extension pins it to\n * one through `genesisHash`, whose first 16 bytes are the CAIP-2 reference.\n * Unpinned accounts are labelled Polkadot, butr's default network.\n */\nconst chainOf = ({ genesisHash }: InjectedAccount): ChainBase =>\n genesisHash === undefined || genesisHash === null || genesisHash === \"\"\n ? POLKADOT_CHAINS.polkadot\n : resolveChain(\n `polkadot:${genesisHash.replace(/^0x/v, \"\").slice(0, 32)}`,\n POLKADOT_CHAINS_LIST,\n );\n\nconst toAccount = (account: InjectedAccount): Account =>\n buildAccount(account.address, chainOf(account));\n\n/** Everything that only exists between `connect()` and `disconnect()`: the\n * enabled provider and the wallet-side account subscription opened against\n * it. One value so the adapter can never be half-connected. */\ntype InjectedSession = {\n injected: Injected;\n unsubscribe: (() => void) | null;\n};\n\n/**\n * `enable()` prompts, so it waits for `connect()`. No `switchChain`: the\n * extension has no network to switch and nothing here takes a chain; an\n * extrinsic carries its genesis hash in the payload polkadot-api builds.\n */\nconst buildInjectedPolkadotAdapter = (\n extensionName: string,\n displayName: string,\n provider: InjectedWindowProvider,\n): PolkadotAdapter => {\n let session: InjectedSession | null = null;\n const listeners = new Set<(event: ConnectorEvent) => void>();\n\n const emit = (event: ConnectorEvent): void => {\n for (const listener of listeners) {\n listener(event);\n }\n };\n\n const closeSession = (): void => {\n session?.unsubscribe?.();\n session = null;\n };\n\n const handleWalletAccounts = (accounts: ReadonlyArray<InjectedAccount>): void => {\n if (accounts.length === 0) {\n closeSession();\n emit({ type: \"disconnected\" });\n return;\n }\n emit({ accounts: accounts.map(toAccount), type: \"accountsChanged\" });\n };\n\n const openSession = (injected: Injected): void => {\n closeSession();\n const opened: InjectedSession = { injected, unsubscribe: null };\n session = opened;\n try {\n const unsubscribe = injected.accounts.subscribe?.(handleWalletAccounts);\n if (unsubscribe === undefined) {\n return;\n }\n // Wallets may fire the callback synchronously; an empty first payload\n // closes the session before this assignment, so never revive it.\n if (session === opened) {\n opened.unsubscribe = unsubscribe;\n } else {\n unsubscribe();\n }\n } catch (error) {\n logWarn(`[butr/polkadot] ${displayName} accounts.subscribe threw:`, error);\n }\n };\n\n const requireInjected = (): Injected => {\n if (session === null) {\n throw new Error(`Wallet ${displayName} is not connected`);\n }\n return session.injected;\n };\n\n const subscribe = (listener: (event: ConnectorEvent) => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n };\n\n const signMessage = async (\n message: Uint8Array,\n options?: AccountOptions,\n ): Promise<SignedMessage> => {\n const injected = requireInjected();\n if (injected.signer.signRaw === undefined) {\n throw new Error(`Wallet ${displayName} does not expose signRaw`);\n }\n const exposed = await injected.accounts.get();\n const requested = options?.account;\n const match =\n requested === undefined\n ? exposed[0]\n : exposed.find((a) => a.address === requested.walletAddress);\n if (match === undefined) {\n throw new Error(\n requested === undefined\n ? `Wallet ${displayName} has no connected account`\n : `Wallet ${displayName} does not expose account ${requested.walletAddress}`,\n );\n }\n const wrapped = wrapBytes(message);\n const result = await injected.signer.signRaw({\n address: match.address,\n data: bytesToHex(wrapped),\n type: \"bytes\",\n });\n return { signature: hexToBytes(result.signature), signedMessage: wrapped };\n };\n\n return {\n chainPlatform: \"polkadot\",\n\n // injectedWeb3 has no silent check, so `silent` still calls `enable()`.\n // It only prompts an origin the extension has not authorised, and a\n // session being restored already is.\n async connect() {\n const injected = await provider.enable(DAPP_NAME);\n const accounts = await injected.accounts.get();\n if (accounts.length === 0) {\n throw new Error(`Wallet ${displayName} exposed no accounts`);\n }\n openSession(injected);\n },\n\n async disconnect() {\n closeSession();\n await Promise.resolve();\n },\n\n async getAccounts() {\n if (session === null) {\n return [];\n }\n const accounts = await session.injected.accounts.get();\n return accounts.map(toAccount);\n },\n\n async getSigner() {\n const extension = requireInjected();\n await Promise.resolve();\n return { extension, extensionName, kind: \"polkadot-injected\" };\n },\n\n icon: sanitizeIcon(GENERIC_POLKADOT_ICON),\n id: `injected:polkadot:${toKebab(extensionName)}`,\n name: displayName,\n\n // `signRaw` and `accounts.subscribe` are optional in injectedWeb3 and\n // live on the object `enable()` returns, so both members appear once\n // `connect()` has shown the extension offers them.\n get signMessage() {\n return session?.injected.signer.signRaw === undefined ? undefined : signMessage;\n },\n\n get subscribe() {\n return (session?.unsubscribe ?? null) === null ? undefined : subscribe;\n },\n };\n};\n\nexport { buildInjectedPolkadotAdapter };\n","import type { WalletAdapter } from \"@usebutr/core\";\n\nimport { buildInjectedPolkadotAdapter } from \"./adapter\";\nimport type { InjectedWindow } from \"./injected-web3\";\nimport { readInjectedWindow } from \"./injected-web3\";\n\nconst knownDisplayNameFor = (key: string): string | undefined => {\n switch (key) {\n case \"enkrypt\": {\n return \"Enkrypt\";\n }\n case \"nova-wallet\": {\n return \"Nova Wallet\";\n }\n case \"polkadot-js\": {\n return \"Polkadot{.js}\";\n }\n case \"subwallet-js\": {\n return \"SubWallet\";\n }\n case \"talisman\": {\n return \"Talisman\";\n }\n default: {\n return undefined;\n }\n }\n};\n\nconst displayNameFor = (key: string): string =>\n knownDisplayNameFor(key) ??\n key\n .split(/[\\-_]/v)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n\ntype InjectedPolkadotDiscoveryOptions = {\n /** Poll schedule (ms offsets) for late-injecting extensions. Defaults\n * to a few short polls; pass `[]` in tests for a single sync read. */\n pollMs?: ReadonlyArray<number>;\n /** Override the global host (tests, iframes). */\n target?: InjectedWindow | null;\n};\n\nconst DEFAULT_POLLS: ReadonlyArray<number> = [250, 750];\n\n/**\n * Adapters are built without calling `enable()`, which would raise the\n * extension's authorization prompt at discovery time. Extensions inject at\n * different points during page load, hence the poll schedule.\n */\nconst discoverInjectedPolkadotAdapters = (\n onAdapter: (adapter: WalletAdapter) => void,\n options: InjectedPolkadotDiscoveryOptions = {},\n): (() => void) => {\n const polls = options.pollMs ?? DEFAULT_POLLS;\n const seen = new Set<string>();\n const timers: Array<ReturnType<typeof setTimeout>> = [];\n let cancelled = false;\n\n const scan = () => {\n if (cancelled) {\n return;\n }\n const host = readInjectedWindow(options.target);\n const registry = host?.injectedWeb3;\n if (!registry) {\n return;\n }\n for (const [key, provider] of Object.entries(registry)) {\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n onAdapter(buildInjectedPolkadotAdapter(key, displayNameFor(key), provider));\n }\n };\n\n scan();\n for (const offset of polls) {\n if (offset === 0) {\n continue;\n }\n timers.push(setTimeout(scan, offset));\n }\n\n return () => {\n cancelled = true;\n for (const timer of timers) {\n clearTimeout(timer);\n }\n };\n};\n\nexport type { InjectedPolkadotDiscoveryOptions };\nexport { discoverInjectedPolkadotAdapters };\n","import type { AccountOptions, PolkadotAdapter, WalletAdapter } from \"@usebutr/core\";\nimport { POLKADOT_CHAINS, POLKADOT_CHAINS_LIST } from \"@usebutr/core\";\nimport {\n createWalletStandardCore,\n discoverWalletStandard,\n getFeature,\n slugify,\n} from \"@usebutr/wallet-standard-shared\";\nimport type { WalletStandardWallet } from \"@usebutr/wallet-standard-shared\";\n\nimport type { PolkadotSignMessageFeature } from \"./wallet-standard-types\";\n\nconst buildPolkadotWalletStandardAdapter = (\n wallet: WalletStandardWallet,\n /** Optional. Called with a function that pushes a synthetic\n * `disconnected` event to all current subscribers. The discovery\n * layer invokes it on Wallet Standard `unregister`. */\n registerDisconnector?: (emit: () => void) => void,\n): PolkadotAdapter | null => {\n const core = createWalletStandardCore({\n chains: POLKADOT_CHAINS_LIST,\n id: slugify(\"polkadot\", wallet.name),\n label: \"Polkadot\",\n namespace: \"polkadot\",\n // Kusama sits alongside Polkadot because it carries real value; Westend\n // and Paseo are faucet testnets and must never win the default.\n preferredChainIds: [POLKADOT_CHAINS.polkadot.id, POLKADOT_CHAINS.kusama.id],\n registerDisconnector,\n trackChainChanges: false,\n wallet,\n });\n if (core === null) {\n return null;\n }\n\n const signer = getFeature<PolkadotSignMessageFeature>(\n wallet,\n \"polkadot:signMessage\",\n \"signMessage\",\n );\n\n return {\n ...core.base,\n chainPlatform: \"polkadot\",\n ...(signer !== undefined && {\n signMessage: async (message: Uint8Array, options?: AccountOptions) => {\n const output = await signer.signMessage({\n account: core.resolveAccount(options?.account),\n message,\n });\n return { signature: output.signature, signedMessage: output.signedMessage ?? message };\n },\n }),\n };\n};\n\n/**\n * The fallback channel; see `polkadotDiscoverer`. Requires the optional\n * `@wallet-standard/app` peer dep and no-ops without it.\n */\nconst discoverPolkadotWalletStandardAdapters = (\n onAdapter: (adapter: WalletAdapter) => void,\n): (() => void) => discoverWalletStandard(onAdapter, buildPolkadotWalletStandardAdapter);\n\nexport { buildPolkadotWalletStandardAdapter, discoverPolkadotWalletStandardAdapters };\n","import type { PlatformDiscoverer } from \"@usebutr/core\";\n\nimport { discoverInjectedPolkadotAdapters } from \"./injected\";\nimport { discoverPolkadotWalletStandardAdapters } from \"./wallet-standard-adapter\";\n\n/**\n * Primary is injectedWeb3; Wallet Standard `polkadot:*` is the fallback. Its\n * defer is the only thing preventing double-listing: a wallet on both\n * channels mints two unrelated ids the discovery bus cannot collapse.\n */\nconst polkadotDiscoverer: PlatformDiscoverer = {\n fallback: {\n subscribe: (onAdapter, opts) => {\n if (opts.hasAnyPrimaryAdapter()) {\n return () => undefined;\n }\n return discoverPolkadotWalletStandardAdapters(onAdapter);\n },\n },\n subscribe: discoverInjectedPolkadotAdapters,\n};\n\nexport { polkadotDiscoverer };\n"],"mappings":";;;;AAAA,MAAM,wBACJ;;;;ACkDF,MAAM,eAAe,IAAI,YAAY,CAAC,CAAC,OAAO,SAAS;AACvD,MAAM,eAAe,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU;AAExD,MAAM,aAAa,YAAoC;CACrD,MAAM,MAAM,IAAI,WAAW,aAAa,SAAS,QAAQ,SAAS,aAAa,MAAM;CACrF,IAAI,IAAI,cAAc,CAAC;CACvB,IAAI,IAAI,SAAS,aAAa,MAAM;CACpC,IAAI,IAAI,cAAc,aAAa,SAAS,QAAQ,MAAM;CAC1D,OAAO;AACT;AAEA,MAAM,sBAAsB,WAA0D;CACpF,IAAI,WAAW,QACb,OAAO;CAET,IAAI,OAAO,WAAW,aACpB,OAAO;CAET,OAAO;AACT;;;;ACjDA,MAAM,YAAY;;;;;;AAOlB,MAAM,WAAW,SACf,KACG,KAAK,CAAC,CACN,YAAY,CAAC,CACb,WAAW,6BAAa,GAAG,GAAG,CAAC,CAC/B,WAAW,wBAAQ,GAAG,EAAE;;;;;;AAO7B,MAAM,WAAW,EAAE,kBACjB,gBAAgB,UAAa,gBAAgB,QAAQ,gBAAgB,KACjE,gBAAgB,WAChB,aACE,YAAY,YAAY,QAAQ,qBAAK,GAAG,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE,KACvD,oBACF;AAEN,MAAM,aAAa,YACjB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,eAAe;EACf,GAAI,WAAW,UAAa,EAC1B,aAAa,OAAO,SAAqB,YAA6B;GACpE,MAAM,SAAS,MAAM,OAAO,YAAY;IACtC,SAAS,KAAK,eAAe,SAAS,OAAO;IAC7C;GACF,CAAC;GACD,OAAO;IAAE,WAAW,OAAO;IAAW,eAAe,OAAO,iBAAiB;GAAQ;EACvF,EACF;CACF;AACF;;;;;AAMA,MAAM,0CACJ,cACiB,uBAAuB,WAAW,kCAAkC;;;;;;;;;ACpDvF,MAAM,qBAAyC;CAC7C,UAAU,EACR,YAAY,WAAW,SAAS;EAC9B,IAAI,KAAK,qBAAqB,GAC5B,aAAa;EAEf,OAAO,uCAAuC,SAAS;CACzD,EACF;CACA,WAAW;AACb"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usebutr/polkadot",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "injectedWeb3 + Wallet Standard adapter for butr (Polkadot/Substrate).",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"butr",
|
|
7
|
+
"dapp",
|
|
8
|
+
"injectedweb3",
|
|
9
|
+
"polkadot",
|
|
10
|
+
"react",
|
|
11
|
+
"substrate",
|
|
12
|
+
"typescript",
|
|
13
|
+
"wallet",
|
|
14
|
+
"web3"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://docs.usebutr.com/api/polkadot",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/pedroapfilho/usebutr/issues"
|
|
19
|
+
},
|
|
5
20
|
"license": "MIT",
|
|
6
21
|
"author": "Pedro Filho <pedro@filho.me>",
|
|
7
22
|
"repository": {
|
|
@@ -10,7 +25,8 @@
|
|
|
10
25
|
"directory": "packages/polkadot"
|
|
11
26
|
},
|
|
12
27
|
"files": [
|
|
13
|
-
"dist"
|
|
28
|
+
"dist",
|
|
29
|
+
"CHANGELOG.md"
|
|
14
30
|
],
|
|
15
31
|
"type": "module",
|
|
16
32
|
"sideEffects": false,
|
|
@@ -25,13 +41,13 @@
|
|
|
25
41
|
"access": "public"
|
|
26
42
|
},
|
|
27
43
|
"dependencies": {
|
|
28
|
-
"@usebutr/core": "
|
|
29
|
-
"@usebutr/wallet-standard-shared": "0.
|
|
44
|
+
"@usebutr/core": "3.0.0",
|
|
45
|
+
"@usebutr/wallet-standard-shared": "2.0.0"
|
|
30
46
|
},
|
|
31
47
|
"devDependencies": {
|
|
32
48
|
"@wallet-standard/app": "^1.1.1",
|
|
33
|
-
"typescript": "^
|
|
34
|
-
"vitest": "^
|
|
49
|
+
"typescript": "^7.0.2",
|
|
50
|
+
"vitest": "^5.0.0",
|
|
35
51
|
"@repo/config-vitest": "0.0.0",
|
|
36
52
|
"@repo/typescript-config": "0.0.0"
|
|
37
53
|
},
|