@tuwaio/pulsar-solana 0.1.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/LICENSE +201 -0
- package/README.md +162 -0
- package/dist/index.d.mts +179 -0
- package/dist/index.d.ts +179 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +3 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +67 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 FOP Tkach Oleksandr
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Pulsar Solana Adapter & Toolkit
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@tuwaio/pulsar-solana)
|
|
4
|
+
[](https://www.google.com/search?q=./LICENSE)
|
|
5
|
+
[](https://github.com/TuwaIO/pulsar-core/actions)
|
|
6
|
+
|
|
7
|
+
An advanced toolkit for the Pulsar Engine that adds comprehensive support for tracking transactions on the Solana blockchain. It integrates seamlessly with **`@solana/kit`** and the **`@solana/wallet-adapter-react`** ecosystem.
|
|
8
|
+
|
|
9
|
+
-----
|
|
10
|
+
|
|
11
|
+
## 🏛️ What is `@tuwaio/pulsar-solana`?
|
|
12
|
+
|
|
13
|
+
This package is a powerful, official adapter for `@tuwaio/pulsar-core`. It contains all the necessary logic to interact with the Solana blockchain, acting as the primary logic provider for Solana-based dApps using Pulsar.
|
|
14
|
+
|
|
15
|
+
While its main export is the `solanaAdapter`, it also includes a suite of standalone trackers and utilities that can be used for advanced or custom implementations. The architecture is designed for robustness, ensuring transactions can be tracked even after a page reload by storing the relevant RPC endpoint within each transaction object.
|
|
16
|
+
|
|
17
|
+
-----
|
|
18
|
+
|
|
19
|
+
## ✨ Core Features
|
|
20
|
+
|
|
21
|
+
- **🔌 Simple Integration:** A single `solanaAdapter` factory function to easily plug full Solana support into `@tuwaio/pulsar-core`.
|
|
22
|
+
- **🛰️ Robust Polling Tracker:** A durable transaction tracker that polls for signature statuses until finality, built on Pulsar's generic polling utility.
|
|
23
|
+
- **🔗 RPC Persistence:** The tracker is designed to be self-contained, storing the `rpcUrl` within each transaction to guarantee tracking can resume after page reloads, independent of the current wallet connection.
|
|
24
|
+
- **🌐 Network Verification:** Includes a utility (`checkSolanaChain`) to robustly verify the connected network via its genesis hash, preventing transactions from being sent to the wrong cluster.
|
|
25
|
+
- **👤 Name Service Support:** Built-in support for **Solana Name Service (SNS)** via Bonfida, allowing for easy resolution of `.sol` domain names and associated avatars.
|
|
26
|
+
- **🛠️ Utility Suite:** Exports a rich set of helpers, including the SNS resolvers (`getSolanaName`, `getSolanaAvatar`) and an explorer link generator (`selectSolanaTxExplorerLink`).
|
|
27
|
+
|
|
28
|
+
-----
|
|
29
|
+
|
|
30
|
+
## 💾 Installation
|
|
31
|
+
|
|
32
|
+
This package is designed for use in a React environment with `@solana/wallet-adapter-react` and requires `@solana/kit`. Install all necessary packages together:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
# Using pnpm
|
|
36
|
+
pnpm add @tuwaio/pulsar-solana @tuwaio/pulsar-core @solana/kit @solana/wallet-adapter-react zustand immer
|
|
37
|
+
|
|
38
|
+
# Using npm
|
|
39
|
+
npm install @tuwaio/pulsar-solana @tuwaio/pulsar-core @solana/kit @solana/wallet-adapter-react zustand immer
|
|
40
|
+
|
|
41
|
+
# Using yarn
|
|
42
|
+
yarn add @tuwaio/pulsar-solana @tuwaio/pulsar-core @solana/kit @solana/wallet-adapter-react zustand immer
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
-----
|
|
46
|
+
|
|
47
|
+
## 🚀 Usage
|
|
48
|
+
|
|
49
|
+
### 1\. Primary Usage: The `solanaAdapter`
|
|
50
|
+
|
|
51
|
+
For most applications, you'll need to import the `solanaAdapter` and pass it to your `createPulsarStore` configuration. The adapter should be initialized within a React component to access the necessary hooks from `@solana/wallet-adapter-react`.
|
|
52
|
+
|
|
53
|
+
```tsx
|
|
54
|
+
// src/store/pulsarStore.ts
|
|
55
|
+
import { createPulsarStore } from '@tuwaio/pulsar-core';
|
|
56
|
+
import { solanaAdapter } from '@tuwaio/pulsar-solana';
|
|
57
|
+
import { useConnection, useWallet } from '@solana/wallet-adapter-react';
|
|
58
|
+
import { useMemo } from 'react';
|
|
59
|
+
|
|
60
|
+
// It's best to create the store instance via a hook to access wallet/connection hooks.
|
|
61
|
+
export const useMyPulsarStore = () => {
|
|
62
|
+
const wallet = useWallet();
|
|
63
|
+
const connection = useConnection();
|
|
64
|
+
|
|
65
|
+
// useMemo ensures the store is created only once.
|
|
66
|
+
return useMemo(() => {
|
|
67
|
+
return createPulsarStore({
|
|
68
|
+
// A unique name for localStorage persistence
|
|
69
|
+
name: 'my-solana-dapp-transactions',
|
|
70
|
+
// Provide the solanaAdapter with the hook contexts
|
|
71
|
+
adapters: [solanaAdapter({ wallet, connection })],
|
|
72
|
+
// Optional: Add global callbacks for all successful transactions
|
|
73
|
+
onSucceedCallbacks: (tx) => {
|
|
74
|
+
console.log(`Transaction ${tx.txKey} succeeded!`);
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}, [wallet, connection]);
|
|
78
|
+
};
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 2\. Initiating a Transaction
|
|
82
|
+
|
|
83
|
+
When calling `handleTransaction`, you must now provide the `rpcUrl` for the transaction. This ensures the tracker can function correctly even after a page reload.
|
|
84
|
+
|
|
85
|
+
```tsx
|
|
86
|
+
// src/components/MyTransactionButton.tsx
|
|
87
|
+
import { usePulsar } from '@tuwaio/pulsar-react'; // Or your custom hook
|
|
88
|
+
import { useConnection } from '@solana/wallet-adapter-react';
|
|
89
|
+
import { TransactionAdapter } from '@tuwaio/pulsar-core';
|
|
90
|
+
|
|
91
|
+
// An example action that returns a transaction signature
|
|
92
|
+
async function mySolanaAction(): Promise<string> {
|
|
93
|
+
// ... your logic to build and send a transaction ...
|
|
94
|
+
const signature = await sendTransaction(...);
|
|
95
|
+
return signature;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function MyTransactionButton() {
|
|
99
|
+
const { handleTransaction } = usePulsar();
|
|
100
|
+
const { connection } = useConnection();
|
|
101
|
+
|
|
102
|
+
const handleClick = async () => {
|
|
103
|
+
await handleTransaction({
|
|
104
|
+
actionFunction: () => mySolanaAction(),
|
|
105
|
+
params: {
|
|
106
|
+
adapter: TransactionAdapter.SOLANA,
|
|
107
|
+
// The RPC endpoint must be provided for tracking.
|
|
108
|
+
rpcUrl: connection.rpcEndpoint,
|
|
109
|
+
desiredChainID: 'mainnet-beta', // The cluster name for the pre-flight check
|
|
110
|
+
type: 'MY_ACTION',
|
|
111
|
+
title: 'My Action',
|
|
112
|
+
description: 'Executing my custom action.',
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
return <button onClick={handleClick}>Execute Action</button>;
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 3\. Using Standalone Utilities
|
|
122
|
+
|
|
123
|
+
You can use exported utilities, like the SNS resolvers, to enrich your UI.
|
|
124
|
+
|
|
125
|
+
**Example: Displaying a user's .sol domain name**
|
|
126
|
+
|
|
127
|
+
```tsx
|
|
128
|
+
// src/components/DisplayName.tsx
|
|
129
|
+
import { getSolanaName } from '@tuwaio/pulsar-solana';
|
|
130
|
+
import { useConnection, useWallet } from '@solana/wallet-adapter-react';
|
|
131
|
+
import { useEffect, useState } from 'react';
|
|
132
|
+
|
|
133
|
+
function DisplayName() {
|
|
134
|
+
const { publicKey } = useWallet();
|
|
135
|
+
const connection = useConnection();
|
|
136
|
+
const [name, setName] = useState<string | null>(null);
|
|
137
|
+
|
|
138
|
+
useEffect(() => {
|
|
139
|
+
if (publicKey && connection) {
|
|
140
|
+
getSolanaName(connection, publicKey.toBase58()).then(setName);
|
|
141
|
+
}
|
|
142
|
+
}, [publicKey, connection]);
|
|
143
|
+
|
|
144
|
+
if (!publicKey) return null;
|
|
145
|
+
|
|
146
|
+
return <span>{name || publicKey.toBase58()}</span>;
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## 🤝 Contributing & Support
|
|
153
|
+
|
|
154
|
+
Contributions are welcome! Please read our main **[Contribution Guidelines](https://github.com/TuwaIO/workflows/blob/main/CONTRIBUTING.md)**.
|
|
155
|
+
|
|
156
|
+
If you find this library useful, please consider supporting its development. Every contribution helps!
|
|
157
|
+
|
|
158
|
+
[**➡️ View Support Options**](https://github.com/TuwaIO/workflows/blob/main/Donation.md)
|
|
159
|
+
|
|
160
|
+
## 📄 License
|
|
161
|
+
|
|
162
|
+
This project is licensed under the **Apache-2.0 License** - see the [LICENSE](./LICENSE) file for details.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { Transaction, TxAdapter, PollingTrackerConfig, ITxTrackingStore } from '@tuwaio/pulsar-core';
|
|
2
|
+
import { WalletContextState, ConnectionContextState } from '@solana/wallet-adapter-react';
|
|
3
|
+
import { TransactionError } from '@solana/kit';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @file Defines the core types and enums specific to the @tuwaio/pulsar-solana package.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Defines the possible Solana network clusters.
|
|
11
|
+
*/
|
|
12
|
+
type SolanaCluster = 'mainnet-beta' | 'devnet' | 'testnet';
|
|
13
|
+
/**
|
|
14
|
+
* Configuration object for the `solanaAdapter`.
|
|
15
|
+
* All properties are optional and are typically derived from the Solana wallet adapter hooks.
|
|
16
|
+
*
|
|
17
|
+
* @property {WalletContextState} [wallet] - The state object from `useWallet()`. Required for actions that need a connected wallet, like signing or retrying transactions.
|
|
18
|
+
* @property {ConnectionContextState} [connection] - The state object from `useConnection()`. Required for on-chain operations like checking the network or using the Solana Name Service.
|
|
19
|
+
* @property {string} [explorerUrl] - The base URL for the transaction explorer (e.g., "https://solscan.io"). Defaults to Solscan if not provided.
|
|
20
|
+
* @property {SolanaCluster} [cluster] - The specific cluster the app is connected to. Used for generating correct explorer links.
|
|
21
|
+
*/
|
|
22
|
+
interface SolanaAdapterConfig {
|
|
23
|
+
wallet?: WalletContextState;
|
|
24
|
+
connection?: ConnectionContextState;
|
|
25
|
+
explorerUrl?: string;
|
|
26
|
+
cluster?: SolanaCluster;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Defines the tracker identifiers available in the Solana adapter.
|
|
30
|
+
*/
|
|
31
|
+
declare enum SolanaTransactionTracker {
|
|
32
|
+
/** The default tracker for monitoring standard Solana transaction signatures. */
|
|
33
|
+
Solana = "solana"
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Represents the unique key returned by a transaction-creating action on Solana.
|
|
37
|
+
* For standard Solana transactions, this is always the transaction signature as a base58 string.
|
|
38
|
+
*/
|
|
39
|
+
type SolanaActionTxKey = string;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @file This file contains the factory function for creating the Solana adapter for Pulsar.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Factory function to create a Solana adapter for Pulsar.
|
|
47
|
+
* This adapter provides all the necessary logic to interact with the Solana ecosystem,
|
|
48
|
+
* including wallet interactions, transaction tracking, and name services.
|
|
49
|
+
*
|
|
50
|
+
* @param {SolanaAdapterConfig} config - The configuration object, typically derived from Solana wallet adapter hooks.
|
|
51
|
+
* @returns {TxAdapter} An object conforming to the `TxAdapter` interface.
|
|
52
|
+
*/
|
|
53
|
+
declare function solanaAdapter<T extends Transaction<SolanaTransactionTracker>>(config: SolanaAdapterConfig): TxAdapter<SolanaTransactionTracker, T, SolanaActionTxKey>;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @file This file defines custom error classes for the @tuwaio/pulsar-solana package.
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Thrown when the connected Solana cluster does not match the required cluster for a transaction.
|
|
61
|
+
*
|
|
62
|
+
* This allows consuming applications to `catch` this specific error and
|
|
63
|
+
* implement custom logic, such as prompting the user to switch networks.
|
|
64
|
+
*/
|
|
65
|
+
declare class SolanaChainMismatchError extends Error {
|
|
66
|
+
/** The name of the error, for easy identification. */
|
|
67
|
+
name: string;
|
|
68
|
+
/** The cluster that the transaction requires (e.g., 'mainnet-beta'). */
|
|
69
|
+
requiredCluster: SolanaCluster;
|
|
70
|
+
/** The cluster the wallet is currently connected to. */
|
|
71
|
+
currentCluster: SolanaCluster | string;
|
|
72
|
+
constructor(requiredCluster: SolanaCluster, currentCluster: SolanaCluster | string);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @file Implements the transaction tracking logic for standard Solana transactions.
|
|
77
|
+
* It uses a polling mechanism to query the `getSignatureStatuses` RPC method.
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The shape of the status object returned for each signature from `getSignatureStatuses`.
|
|
82
|
+
* @internal
|
|
83
|
+
*/
|
|
84
|
+
type SolanaSignatureStatusResponse = {
|
|
85
|
+
slot: bigint;
|
|
86
|
+
confirmations: number | null;
|
|
87
|
+
err: TransactionError | null;
|
|
88
|
+
confirmationStatus: 'processed' | 'confirmed' | 'finalized' | null;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* The parameters for our specific fetcher function.
|
|
92
|
+
* @internal
|
|
93
|
+
*/
|
|
94
|
+
type SolanaFetcherParams = Parameters<PollingTrackerConfig<SolanaSignatureStatusResponse, Transaction<SolanaTransactionTracker>, SolanaTransactionTracker>['fetcher']>[0];
|
|
95
|
+
/**
|
|
96
|
+
* A reusable fetcher for `initializePollingTracker` that queries the Solana RPC for a transaction's signature status.
|
|
97
|
+
* This is the core polling logic that powers the tracker.
|
|
98
|
+
*/
|
|
99
|
+
declare function solanaFetcher({ tx, stopPolling, onSuccess, onFailure, onIntervalTick }: SolanaFetcherParams): Promise<void>;
|
|
100
|
+
/**
|
|
101
|
+
* A higher-level wrapper that integrates the Solana polling logic with the Pulsar store.
|
|
102
|
+
* It uses the generic `solanaFetcher` and provides store-specific callbacks.
|
|
103
|
+
*
|
|
104
|
+
* @template T - The application-specific transaction type, constrained to Transaction.
|
|
105
|
+
*/
|
|
106
|
+
declare function solanaTrackerForStore<T extends Transaction<SolanaTransactionTracker>>({ tx, ...rest }: Pick<ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>, 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'> & {
|
|
107
|
+
tx: T;
|
|
108
|
+
}): Promise<void>;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @file This file contains the primary router for initializing transaction trackers.
|
|
112
|
+
*/
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Initializes the correct background tracker for a given Solana transaction.
|
|
116
|
+
* This function acts as a router, selecting the appropriate tracker based on the `tx.tracker` property.
|
|
117
|
+
*
|
|
118
|
+
* @template T - The transaction type, constrained to Solana transactions.
|
|
119
|
+
* @param {object} params - The parameters for initializing the tracker.
|
|
120
|
+
* @param {T} params.tx - The transaction object to be tracked.
|
|
121
|
+
* @param {SolanaTransactionTracker} params.tracker - The specific tracker to use.
|
|
122
|
+
* @param {object} params.rest - The rest of the store's methods and state needed by the tracker.
|
|
123
|
+
* @returns {Promise<void>} A promise that resolves when the tracker has been initialized.
|
|
124
|
+
*/
|
|
125
|
+
declare function checkAndInitializeTrackerInStore<T extends Transaction<SolanaTransactionTracker>>({ tx, tracker, ...rest }: {
|
|
126
|
+
tx: T;
|
|
127
|
+
tracker: SolanaTransactionTracker;
|
|
128
|
+
} & Pick<ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>, 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'>): Promise<void>;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @file This file contains a utility to robustly verify the Solana cluster by its genesis hash.
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Checks if an RPC endpoint is connected to the required Solana cluster.
|
|
136
|
+
* It fetches the genesis hash from the RPC endpoint and compares it
|
|
137
|
+
* with a known hash for the specified cluster.
|
|
138
|
+
*
|
|
139
|
+
* @param {string} rpcUrl - The RPC endpoint URL to check.
|
|
140
|
+
* @param {SolanaCluster} requiredCluster - The cluster that the transaction requires (e.g., 'mainnet-beta').
|
|
141
|
+
* @throws {SolanaChainMismatchError} If the connected chain does not match the required cluster.
|
|
142
|
+
* @throws {Error} If the cluster name is unknown or if the RPC call fails for other reasons.
|
|
143
|
+
*/
|
|
144
|
+
declare const checkSolanaChain: (rpcUrl: string, requiredCluster: SolanaCluster) => Promise<void>;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* @file This file contains a utility function for generating Solana transaction explorer links.
|
|
148
|
+
*/
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Generates a full URL to a transaction on a Solana explorer like Solscan.
|
|
152
|
+
*
|
|
153
|
+
* @param {string} baseUrl - The base URL of the explorer (e.g., "https://solscan.io").
|
|
154
|
+
* @param {string} txKey - The transaction signature (hash).
|
|
155
|
+
* @param {SolanaCluster} [cluster] - The optional cluster name ('devnet', 'testnet') to add as a query parameter.
|
|
156
|
+
* @returns {string} The full URL to the transaction on the explorer.
|
|
157
|
+
*/
|
|
158
|
+
declare const selectSolanaTxExplorerLink: (baseUrl: string, txKey: string, cluster?: SolanaCluster) => string;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* @file This file contains utility functions for interacting with the Solana Name Service (SNS) provided by Bonfida.
|
|
162
|
+
*/
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Performs a reverse lookup to find the .sol domain name for a given wallet address.
|
|
166
|
+
* @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.
|
|
167
|
+
* @param {string} address - The public key of the wallet as a string.
|
|
168
|
+
* @returns {Promise<string | null>} The .sol domain name (e.g., "bonfida.sol") or null if not found.
|
|
169
|
+
*/
|
|
170
|
+
declare const getSolanaName: (connection: ConnectionContextState, address: string) => Promise<string | null>;
|
|
171
|
+
/**
|
|
172
|
+
* Retrieves the avatar URL from the 'pic' record of a .sol domain name.
|
|
173
|
+
* @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.
|
|
174
|
+
* @param {string} name - The .sol domain name (e.g., "bonfida.sol").
|
|
175
|
+
* @returns {Promise<string | null>} The URL of the avatar or null if not found or set.
|
|
176
|
+
*/
|
|
177
|
+
declare const getSolanaAvatar: (connection: ConnectionContextState, name: string) => Promise<string | null>;
|
|
178
|
+
|
|
179
|
+
export { type SolanaActionTxKey, type SolanaAdapterConfig, SolanaChainMismatchError, type SolanaCluster, SolanaTransactionTracker, checkAndInitializeTrackerInStore, checkSolanaChain, getSolanaAvatar, getSolanaName, selectSolanaTxExplorerLink, solanaAdapter, solanaFetcher, solanaTrackerForStore };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { Transaction, TxAdapter, PollingTrackerConfig, ITxTrackingStore } from '@tuwaio/pulsar-core';
|
|
2
|
+
import { WalletContextState, ConnectionContextState } from '@solana/wallet-adapter-react';
|
|
3
|
+
import { TransactionError } from '@solana/kit';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @file Defines the core types and enums specific to the @tuwaio/pulsar-solana package.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Defines the possible Solana network clusters.
|
|
11
|
+
*/
|
|
12
|
+
type SolanaCluster = 'mainnet-beta' | 'devnet' | 'testnet';
|
|
13
|
+
/**
|
|
14
|
+
* Configuration object for the `solanaAdapter`.
|
|
15
|
+
* All properties are optional and are typically derived from the Solana wallet adapter hooks.
|
|
16
|
+
*
|
|
17
|
+
* @property {WalletContextState} [wallet] - The state object from `useWallet()`. Required for actions that need a connected wallet, like signing or retrying transactions.
|
|
18
|
+
* @property {ConnectionContextState} [connection] - The state object from `useConnection()`. Required for on-chain operations like checking the network or using the Solana Name Service.
|
|
19
|
+
* @property {string} [explorerUrl] - The base URL for the transaction explorer (e.g., "https://solscan.io"). Defaults to Solscan if not provided.
|
|
20
|
+
* @property {SolanaCluster} [cluster] - The specific cluster the app is connected to. Used for generating correct explorer links.
|
|
21
|
+
*/
|
|
22
|
+
interface SolanaAdapterConfig {
|
|
23
|
+
wallet?: WalletContextState;
|
|
24
|
+
connection?: ConnectionContextState;
|
|
25
|
+
explorerUrl?: string;
|
|
26
|
+
cluster?: SolanaCluster;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Defines the tracker identifiers available in the Solana adapter.
|
|
30
|
+
*/
|
|
31
|
+
declare enum SolanaTransactionTracker {
|
|
32
|
+
/** The default tracker for monitoring standard Solana transaction signatures. */
|
|
33
|
+
Solana = "solana"
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Represents the unique key returned by a transaction-creating action on Solana.
|
|
37
|
+
* For standard Solana transactions, this is always the transaction signature as a base58 string.
|
|
38
|
+
*/
|
|
39
|
+
type SolanaActionTxKey = string;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @file This file contains the factory function for creating the Solana adapter for Pulsar.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Factory function to create a Solana adapter for Pulsar.
|
|
47
|
+
* This adapter provides all the necessary logic to interact with the Solana ecosystem,
|
|
48
|
+
* including wallet interactions, transaction tracking, and name services.
|
|
49
|
+
*
|
|
50
|
+
* @param {SolanaAdapterConfig} config - The configuration object, typically derived from Solana wallet adapter hooks.
|
|
51
|
+
* @returns {TxAdapter} An object conforming to the `TxAdapter` interface.
|
|
52
|
+
*/
|
|
53
|
+
declare function solanaAdapter<T extends Transaction<SolanaTransactionTracker>>(config: SolanaAdapterConfig): TxAdapter<SolanaTransactionTracker, T, SolanaActionTxKey>;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @file This file defines custom error classes for the @tuwaio/pulsar-solana package.
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Thrown when the connected Solana cluster does not match the required cluster for a transaction.
|
|
61
|
+
*
|
|
62
|
+
* This allows consuming applications to `catch` this specific error and
|
|
63
|
+
* implement custom logic, such as prompting the user to switch networks.
|
|
64
|
+
*/
|
|
65
|
+
declare class SolanaChainMismatchError extends Error {
|
|
66
|
+
/** The name of the error, for easy identification. */
|
|
67
|
+
name: string;
|
|
68
|
+
/** The cluster that the transaction requires (e.g., 'mainnet-beta'). */
|
|
69
|
+
requiredCluster: SolanaCluster;
|
|
70
|
+
/** The cluster the wallet is currently connected to. */
|
|
71
|
+
currentCluster: SolanaCluster | string;
|
|
72
|
+
constructor(requiredCluster: SolanaCluster, currentCluster: SolanaCluster | string);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @file Implements the transaction tracking logic for standard Solana transactions.
|
|
77
|
+
* It uses a polling mechanism to query the `getSignatureStatuses` RPC method.
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The shape of the status object returned for each signature from `getSignatureStatuses`.
|
|
82
|
+
* @internal
|
|
83
|
+
*/
|
|
84
|
+
type SolanaSignatureStatusResponse = {
|
|
85
|
+
slot: bigint;
|
|
86
|
+
confirmations: number | null;
|
|
87
|
+
err: TransactionError | null;
|
|
88
|
+
confirmationStatus: 'processed' | 'confirmed' | 'finalized' | null;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* The parameters for our specific fetcher function.
|
|
92
|
+
* @internal
|
|
93
|
+
*/
|
|
94
|
+
type SolanaFetcherParams = Parameters<PollingTrackerConfig<SolanaSignatureStatusResponse, Transaction<SolanaTransactionTracker>, SolanaTransactionTracker>['fetcher']>[0];
|
|
95
|
+
/**
|
|
96
|
+
* A reusable fetcher for `initializePollingTracker` that queries the Solana RPC for a transaction's signature status.
|
|
97
|
+
* This is the core polling logic that powers the tracker.
|
|
98
|
+
*/
|
|
99
|
+
declare function solanaFetcher({ tx, stopPolling, onSuccess, onFailure, onIntervalTick }: SolanaFetcherParams): Promise<void>;
|
|
100
|
+
/**
|
|
101
|
+
* A higher-level wrapper that integrates the Solana polling logic with the Pulsar store.
|
|
102
|
+
* It uses the generic `solanaFetcher` and provides store-specific callbacks.
|
|
103
|
+
*
|
|
104
|
+
* @template T - The application-specific transaction type, constrained to Transaction.
|
|
105
|
+
*/
|
|
106
|
+
declare function solanaTrackerForStore<T extends Transaction<SolanaTransactionTracker>>({ tx, ...rest }: Pick<ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>, 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'> & {
|
|
107
|
+
tx: T;
|
|
108
|
+
}): Promise<void>;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @file This file contains the primary router for initializing transaction trackers.
|
|
112
|
+
*/
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Initializes the correct background tracker for a given Solana transaction.
|
|
116
|
+
* This function acts as a router, selecting the appropriate tracker based on the `tx.tracker` property.
|
|
117
|
+
*
|
|
118
|
+
* @template T - The transaction type, constrained to Solana transactions.
|
|
119
|
+
* @param {object} params - The parameters for initializing the tracker.
|
|
120
|
+
* @param {T} params.tx - The transaction object to be tracked.
|
|
121
|
+
* @param {SolanaTransactionTracker} params.tracker - The specific tracker to use.
|
|
122
|
+
* @param {object} params.rest - The rest of the store's methods and state needed by the tracker.
|
|
123
|
+
* @returns {Promise<void>} A promise that resolves when the tracker has been initialized.
|
|
124
|
+
*/
|
|
125
|
+
declare function checkAndInitializeTrackerInStore<T extends Transaction<SolanaTransactionTracker>>({ tx, tracker, ...rest }: {
|
|
126
|
+
tx: T;
|
|
127
|
+
tracker: SolanaTransactionTracker;
|
|
128
|
+
} & Pick<ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>, 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'>): Promise<void>;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @file This file contains a utility to robustly verify the Solana cluster by its genesis hash.
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Checks if an RPC endpoint is connected to the required Solana cluster.
|
|
136
|
+
* It fetches the genesis hash from the RPC endpoint and compares it
|
|
137
|
+
* with a known hash for the specified cluster.
|
|
138
|
+
*
|
|
139
|
+
* @param {string} rpcUrl - The RPC endpoint URL to check.
|
|
140
|
+
* @param {SolanaCluster} requiredCluster - The cluster that the transaction requires (e.g., 'mainnet-beta').
|
|
141
|
+
* @throws {SolanaChainMismatchError} If the connected chain does not match the required cluster.
|
|
142
|
+
* @throws {Error} If the cluster name is unknown or if the RPC call fails for other reasons.
|
|
143
|
+
*/
|
|
144
|
+
declare const checkSolanaChain: (rpcUrl: string, requiredCluster: SolanaCluster) => Promise<void>;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* @file This file contains a utility function for generating Solana transaction explorer links.
|
|
148
|
+
*/
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Generates a full URL to a transaction on a Solana explorer like Solscan.
|
|
152
|
+
*
|
|
153
|
+
* @param {string} baseUrl - The base URL of the explorer (e.g., "https://solscan.io").
|
|
154
|
+
* @param {string} txKey - The transaction signature (hash).
|
|
155
|
+
* @param {SolanaCluster} [cluster] - The optional cluster name ('devnet', 'testnet') to add as a query parameter.
|
|
156
|
+
* @returns {string} The full URL to the transaction on the explorer.
|
|
157
|
+
*/
|
|
158
|
+
declare const selectSolanaTxExplorerLink: (baseUrl: string, txKey: string, cluster?: SolanaCluster) => string;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* @file This file contains utility functions for interacting with the Solana Name Service (SNS) provided by Bonfida.
|
|
162
|
+
*/
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Performs a reverse lookup to find the .sol domain name for a given wallet address.
|
|
166
|
+
* @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.
|
|
167
|
+
* @param {string} address - The public key of the wallet as a string.
|
|
168
|
+
* @returns {Promise<string | null>} The .sol domain name (e.g., "bonfida.sol") or null if not found.
|
|
169
|
+
*/
|
|
170
|
+
declare const getSolanaName: (connection: ConnectionContextState, address: string) => Promise<string | null>;
|
|
171
|
+
/**
|
|
172
|
+
* Retrieves the avatar URL from the 'pic' record of a .sol domain name.
|
|
173
|
+
* @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.
|
|
174
|
+
* @param {string} name - The .sol domain name (e.g., "bonfida.sol").
|
|
175
|
+
* @returns {Promise<string | null>} The URL of the avatar or null if not found or set.
|
|
176
|
+
*/
|
|
177
|
+
declare const getSolanaAvatar: (connection: ConnectionContextState, name: string) => Promise<string | null>;
|
|
178
|
+
|
|
179
|
+
export { type SolanaActionTxKey, type SolanaAdapterConfig, SolanaChainMismatchError, type SolanaCluster, SolanaTransactionTracker, checkAndInitializeTrackerInStore, checkSolanaChain, getSolanaAvatar, getSolanaName, selectSolanaTxExplorerLink, solanaAdapter, solanaFetcher, solanaTrackerForStore };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var kit=require('@solana/kit'),pulsarCore=require('@tuwaio/pulsar-core'),u=require('dayjs'),splNameService=require('@bonfida/spl-name-service');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var u__default=/*#__PURE__*/_interopDefault(u);var S=(n=>(n.Solana="solana",n))(S||{});var d=new Map,b=r=>{if(d.has(r))return d.get(r);let n=kit.createSolanaRpc(r);return d.set(r,n),n};async function N({tx:r,stopPolling:n,onSuccess:t,onFailure:a,onIntervalTick:i}){if(r.adapter!==pulsarCore.TransactionAdapter.SOLANA||!r.rpcUrl)throw new Error("RPC URL is missing from the Solana transaction.");let s=(await b(r.rpcUrl).getSignatureStatuses([r.txKey]).send())?.value[0];if(!s)return;let c=s;if(i?.(c),c.err){a(c);return}c.confirmationStatus==="finalized"&&t(c),u__default.default().diff(u__default.default.unix(r.localTimestamp),"minute")>=30&&(n({withoutRemoving:true}),a(c));}async function x({tx:r,...n}){return pulsarCore.initializePollingTracker({tx:r,fetcher:N,removeTxFromPool:n.removeTxFromPool,pollingInterval:2500,maxRetries:720,onSuccess:t=>{n.updateTxParams(r.txKey,{status:pulsarCore.TransactionStatus.Success,pending:false,isError:false,finishedTimestamp:u__default.default().unix(),confirmations:t.confirmations??1,slot:Number(t.slot)});let a=n.transactionsPool[r.txKey];n.onSucceedCallbacks&&a&&n.onSucceedCallbacks(a);},onIntervalTick:t=>{n.updateTxParams(r.txKey,{confirmations:t.confirmations??0,slot:Number(t.slot)});},onFailure:t=>{let a=t?.err?`Transaction failed: ${JSON.stringify(t.err)}`:"Transaction tracking timed out or the transaction was not found.";n.updateTxParams(r.txKey,{status:pulsarCore.TransactionStatus.Failed,pending:false,isError:true,errorMessage:a,finishedTimestamp:u__default.default().unix()});}})}async function y({tx:r,tracker:n,...t}){switch(n){case "solana":await x({tx:r,...t});break;default:console.error(`Unknown tracker type for Solana adapter: ${n}`),t.updateTxParams(r.txKey,{status:pulsarCore.TransactionStatus.Failed,pending:false,isError:true,errorMessage:`Unsupported tracker type: "${n}"`});break}}var m=class extends Error{name="SolanaChainMismatchError";requiredCluster;currentCluster;constructor(n,t){let a=`Wrong network. The transaction requires ${n}, but you are connected to ${t}.`;super(a),this.requiredCluster=n,this.currentCluster=t;}};var k={"mainnet-beta":"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",devnet:"GH7ome3EiwEr7tu9JuTh2dpYWBJK3z69Xm1ZE3MEE6JC",testnet:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY"},h=async(r,n)=>{let t=k[n];if(!t)throw new Error(`Unknown Solana cluster specified: ${n}`);let i=await kit.createSolanaRpc(r).getGenesisHash().send();if(i!==t){let o=Object.entries(k).find(([,e])=>e===i)?.[0]||"an unknown network";throw new m(n,o)}};var C=(r,n,t)=>{let a=r.endsWith("/")?r.slice(0,-1):r,i=t?`?cluster=${t}`:"";return `${a}/tx/${n}${i}`};var f=class{_bn;constructor(n){this._bn=kit.getBase58Encoder().encode(n);}toBuffer(){return Buffer.from(this._bn)}toString(){let[n]=kit.getBase58Decoder().decode(this._bn);return n}},w=async(r,n)=>{try{let t=new f(n),a=await splNameService.getDomainKeysWithReverses(r.connection,t);return a.length===0?null:`${await splNameService.performReverseLookup(r.connection,a[0])}.sol`}catch{return null}},A=async(r,n)=>{try{let t=await splNameService.getRecord(r.connection,n,splNameService.Record.Pic);return !t||!t.data?null:t.data.toString("utf-8")}catch{return null}};function Kn(r){let{wallet:n,connection:t,explorerUrl:a,cluster:i}=r;return {key:pulsarCore.TransactionAdapter.SOLANA,getWalletInfo:()=>({walletAddress:n?.publicKey?.toBase58()??"0x0",walletType:n?.wallet?.adapter.name.toLowerCase()??"unknown"}),checkChainForTx:async o=>{let e=t?.connection.rpcEndpoint;if(!e){console.warn("Cannot check chain: connection context not provided to adapter.");return}await h(e,o);},checkTransactionsTracker:o=>({tracker:"solana",txKey:o}),checkAndInitializeTrackerInStore:({tx:o,...e})=>y({tracker:o.tracker,tx:o,...e}),getExplorerUrl:()=>a??"https://solscan.io",getExplorerTxUrl:(o,e)=>C(a??"https://solscan.io",e,i),getName:async o=>t?w(t,o):(console.warn("Cannot get name: connection context not provided to adapter."),null),getAvatar:async o=>t?A(t,o):(console.warn("Cannot get avatar: connection context not provided to adapter."),null),retryTxAction:async({actions:o,onClose:e,txKey:s,handleTransaction:c,tx:l})=>{if(e(s),!n)throw new Error("Retry failed: A wallet must be connected to retry a transaction.");if(!c)throw new Error("Retry failed: handleTransaction function is not provided.");let p=l.actionKey;if(!p||!o?.[p])throw new Error(`Retry failed: No action found for actionKey "${p}".`);let R=o[p],T=l.rpcUrl??t?.connection.rpcEndpoint;if(!T)throw new Error("Retry failed: Could not determine RPC endpoint.");let P=kit.createSolanaRpc(T);await c({actionFunction:()=>R({wallet:n,connection:t?.connection,rpc:P,...l.payload}),params:l,defaultTracker:"solana"});}}}
|
|
2
|
+
exports.SolanaChainMismatchError=m;exports.SolanaTransactionTracker=S;exports.checkAndInitializeTrackerInStore=y;exports.checkSolanaChain=h;exports.getSolanaAvatar=A;exports.getSolanaName=w;exports.selectSolanaTxExplorerLink=C;exports.solanaAdapter=Kn;exports.solanaFetcher=N;exports.solanaTrackerForStore=x;//# sourceMappingURL=index.js.map
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/trackers/solanaTracker.ts","../src/utils/checkAndInitializeTrackerInStore.ts","../src/errors.ts","../src/utils/checkSolanaChain.ts","../src/utils/selectSolanaTxExplorerLink.ts","../src/utils/snsUtils.ts","../src/adapters/solanaAdapter.ts"],"names":["SolanaTransactionTracker","rpcCache","getRpcClient","rpcUrl","newRpc","createSolanaRpc","solanaFetcher","tx","stopPolling","onSuccess","onFailure","onIntervalTick","TransactionAdapter","status","typedStatus","dayjs","solanaTrackerForStore","rest","initializePollingTracker","response","TransactionStatus","updatedTx","errorMessage","checkAndInitializeTrackerInStore","tracker","SolanaChainMismatchError","requiredCluster","currentCluster","message","SOLANA_GENESIS_HASHES","checkSolanaChain","expectedGenesisHash","currentGenesisHash","currentClusterName","hash","selectSolanaTxExplorerLink","baseUrl","txKey","cluster","sanitizedBaseUrl","clusterParam","PublicKey","value","getBase58Encoder","decodedString","getBase58Decoder","getSolanaName","connection","address","pubKey","domainKeys","getDomainKeysWithReverses","performReverseLookup","getSolanaAvatar","name","record","getRecord","Record","solanaAdapter","config","wallet","explorerUrl","txCluster","currentRpcUrl","actionTxKey","txPool","actions","onClose","handleTransaction","actionKey","retryAction","rpcUrlForRetry","rpcForRetry"],"mappings":"6QA8BO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GAEVA,CAAAA,CAAA,MAAA,CAAS,SAFCA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA,ECNZ,IAAMC,CAAAA,CAAW,IAAI,GAAA,CAQfC,EAAgBC,CAAAA,EAAsC,CAC1D,GAAIF,CAAAA,CAAS,GAAA,CAAIE,CAAM,CAAA,CACrB,OAAOF,CAAAA,CAAS,GAAA,CAAIE,CAAM,CAAA,CAE5B,IAAMC,CAAAA,CAASC,mBAAAA,CAAgBF,CAAM,CAAA,CACrC,OAAAF,EAAS,GAAA,CAAIE,CAAAA,CAAQC,CAAM,CAAA,CACpBA,CACT,CAAA,CAiCA,eAAsBE,CAAAA,CAAc,CAAE,GAAAC,CAAAA,CAAI,WAAA,CAAAC,EAAa,SAAA,CAAAC,CAAAA,CAAW,SAAA,CAAAC,CAAAA,CAAW,cAAA,CAAAC,CAAe,EAAwB,CAClH,GAAIJ,EAAG,OAAA,GAAYK,6BAAAA,CAAmB,QAAU,CAACL,CAAAA,CAAG,MAAA,CAElD,MAAM,IAAI,KAAA,CAAM,iDAAiD,CAAA,CAKnE,IAAMM,CAAAA,CAAAA,CADW,MADLX,CAAAA,CAAaK,CAAAA,CAAG,MAAM,CAAA,CACP,oBAAA,CAAqB,CAACA,CAAAA,CAAG,KAAkB,CAAC,EAAE,IAAA,EAAK,GACrD,MAAM,CAAC,CAAA,CAEhC,GAAI,CAACM,CAAAA,CAGH,OAGF,IAAMC,CAAAA,CAAcD,CAAAA,CAGpB,GAFAF,CAAAA,GAAiBG,CAAW,EAExBA,CAAAA,CAA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AAA,CACH,MAAM,IAAI,MAAM,kEAAkE,CAAA,CAEpF,GAAI,CAACQ,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,2DAA2D,CAAA,CAG7E,IAAMC,CAAAA,CAAY9D,EAAG,SAAA,CACrB,GAAI,CAAC8D,CAAAA,EAAa,CAACH,CAAAA,GAAUG,CAAS,CAAA,CACpC,MAAM,IAAI,KAAA,CAAM,CAAA,6CAAA,EAAgDA,CAAS,IAAI,CAAA,CAG/E,IAAMC,EAAcJ,CAAAA,CAAQG,CAAS,EAG/BE,CAAAA,CAAiBhE,CAAAA,CAAG,MAAA,EAAUwC,CAAAA,EAAY,UAAA,CAAW,WAAA,CAC3D,GAAI,CAACwB,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,iDAAiD,CAAA,CAGnE,IAAMC,CAAAA,CAAcnE,mBAAAA,CAAgBkE,CAAc,CAAA,CAElD,MAAMH,CAAAA,CAAkB,CACtB,eAAgB,IACbE,CAAAA,CAAoB,CACnB,MAAA,CAAAV,CAAAA,CACA,UAAA,CAAYb,CAAAA,EAAY,UAAA,CACxB,GAAA,CAAKyB,EACL,GAAGjE,CAAAA,CAAG,OACR,CAAC,CAAA,CACH,MAAA,CAAQA,EACR,cAAA,CAAA,QACF,CAAC,EACH,CACF,CACF","file":"index.js","sourcesContent":["/**\n * @file Defines the core types and enums specific to the @tuwaio/pulsar-solana package.\n */\n\nimport { ConnectionContextState, WalletContextState } from '@solana/wallet-adapter-react';\n\n/**\n * Defines the possible Solana network clusters.\n */\nexport type SolanaCluster = 'mainnet-beta' | 'devnet' | 'testnet';\n\n/**\n * Configuration object for the `solanaAdapter`.\n * All properties are optional and are typically derived from the Solana wallet adapter hooks.\n *\n * @property {WalletContextState} [wallet] - The state object from `useWallet()`. Required for actions that need a connected wallet, like signing or retrying transactions.\n * @property {ConnectionContextState} [connection] - The state object from `useConnection()`. Required for on-chain operations like checking the network or using the Solana Name Service.\n * @property {string} [explorerUrl] - The base URL for the transaction explorer (e.g., \"https://solscan.io\"). Defaults to Solscan if not provided.\n * @property {SolanaCluster} [cluster] - The specific cluster the app is connected to. Used for generating correct explorer links.\n */\nexport interface SolanaAdapterConfig {\n wallet?: WalletContextState;\n connection?: ConnectionContextState;\n explorerUrl?: string;\n cluster?: SolanaCluster;\n}\n\n/**\n * Defines the tracker identifiers available in the Solana adapter.\n */\nexport enum SolanaTransactionTracker {\n /** The default tracker for monitoring standard Solana transaction signatures. */\n Solana = 'solana',\n}\n\n/**\n * Represents the unique key returned by a transaction-creating action on Solana.\n * For standard Solana transactions, this is always the transaction signature as a base58 string.\n */\nexport type SolanaActionTxKey = string;\n","/**\n * @file Implements the transaction tracking logic for standard Solana transactions.\n * It uses a polling mechanism to query the `getSignatureStatuses` RPC method.\n */\n\nimport { createSolanaRpc, Rpc, Signature, SolanaRpcApi, TransactionError } from '@solana/kit';\nimport {\n initializePollingTracker,\n ITxTrackingStore,\n PollingTrackerConfig,\n Transaction,\n TransactionAdapter,\n TransactionStatus,\n} from '@tuwaio/pulsar-core';\nimport dayjs from 'dayjs';\n\nimport { SolanaActionTxKey, SolanaTransactionTracker } from '../types';\n\n// --- RPC Client Caching ---\n\n/**\n * An in-memory cache for RPC clients to avoid re-creating them on every poll.\n * @internal\n */\nconst rpcCache = new Map<string, Rpc<SolanaRpcApi>>();\n\n/**\n * Retrieves a cached RPC client for a given URL or creates a new one.\n * @param rpcUrl - The RPC endpoint URL.\n * @returns The RPC client instance.\n * @internal\n */\nconst getRpcClient = (rpcUrl: string): Rpc<SolanaRpcApi> => {\n if (rpcCache.has(rpcUrl)) {\n return rpcCache.get(rpcUrl)!;\n }\n const newRpc = createSolanaRpc(rpcUrl);\n rpcCache.set(rpcUrl, newRpc);\n return newRpc;\n};\n\n// --- Types ---\n\n/**\n * The shape of the status object returned for each signature from `getSignatureStatuses`.\n * @internal\n */\ntype SolanaSignatureStatusResponse = {\n slot: bigint;\n confirmations: number | null;\n err: TransactionError | null;\n confirmationStatus: 'processed' | 'confirmed' | 'finalized' | null;\n};\n\n/**\n * The parameters for our specific fetcher function.\n * @internal\n */\ntype SolanaFetcherParams = Parameters<\n PollingTrackerConfig<\n SolanaSignatureStatusResponse,\n Transaction<SolanaTransactionTracker>,\n SolanaTransactionTracker\n >['fetcher']\n>[0];\n\n// --- Fetcher Implementation ---\n\n/**\n * A reusable fetcher for `initializePollingTracker` that queries the Solana RPC for a transaction's signature status.\n * This is the core polling logic that powers the tracker.\n */\nexport async function solanaFetcher({ tx, stopPolling, onSuccess, onFailure, onIntervalTick }: SolanaFetcherParams) {\n if (tx.adapter !== TransactionAdapter.SOLANA || !tx.rpcUrl) {\n // This should not happen if the types are correct, but it's a good runtime safeguard.\n throw new Error('RPC URL is missing from the Solana transaction.');\n }\n\n const rpc = getRpcClient(tx.rpcUrl);\n const statuses = await rpc.getSignatureStatuses([tx.txKey as Signature]).send();\n const status = statuses?.value[0];\n\n if (!status) {\n // Continue polling if the transaction is not yet found by the RPC node.\n // The polling tracker will handle the retry delay.\n return;\n }\n\n const typedStatus = status as SolanaSignatureStatusResponse;\n onIntervalTick?.(typedStatus);\n\n if (typedStatus.err) {\n onFailure(typedStatus); // Terminal failure state\n return;\n }\n\n if (typedStatus.confirmationStatus === 'finalized') {\n onSuccess(typedStatus); // Terminal success state\n }\n\n // Safeguard: Stop polling for very old pending transactions.\n if (dayjs().diff(dayjs.unix(tx.localTimestamp), 'minute') >= 30) {\n stopPolling({ withoutRemoving: true });\n // When a timeout occurs, we call `onFailure` with the last known status,\n // but the tracker itself will provide the specific timeout error message.\n onFailure(typedStatus);\n }\n}\n\n// --- Store-Connected Tracker ---\n\n/**\n * A higher-level wrapper that integrates the Solana polling logic with the Pulsar store.\n * It uses the generic `solanaFetcher` and provides store-specific callbacks.\n *\n * @template T - The application-specific transaction type, constrained to Transaction.\n */\nexport async function solanaTrackerForStore<T extends Transaction<SolanaTransactionTracker>>({\n tx,\n ...rest\n}: Pick<\n ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>,\n 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'\n> & {\n tx: T;\n}) {\n return initializePollingTracker<SolanaSignatureStatusResponse, T, SolanaTransactionTracker>({\n tx,\n fetcher: solanaFetcher,\n removeTxFromPool: rest.removeTxFromPool,\n pollingInterval: 2500,\n maxRetries: 720, // 30 minutes timeout (720 intervals * 2.5s = 1800s)\n onSuccess: (response) => {\n rest.updateTxParams(tx.txKey, {\n status: TransactionStatus.Success,\n pending: false,\n isError: false,\n finishedTimestamp: dayjs().unix(),\n confirmations: response.confirmations ?? 1,\n slot: Number(response.slot),\n });\n\n const updatedTx = rest.transactionsPool[tx.txKey];\n if (rest.onSucceedCallbacks && updatedTx) {\n rest.onSucceedCallbacks(updatedTx);\n }\n },\n onIntervalTick: (response) => {\n rest.updateTxParams(tx.txKey, {\n confirmations: response.confirmations ?? 0,\n slot: Number(response.slot),\n });\n },\n onFailure: (response) => {\n // If `response` is undefined, it means the polling timed out from `initializePollingTracker`.\n // Otherwise, the transaction failed on-chain.\n const errorMessage = response?.err\n ? `Transaction failed: ${JSON.stringify(response.err)}`\n : 'Transaction tracking timed out or the transaction was not found.';\n\n rest.updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n errorMessage,\n finishedTimestamp: dayjs().unix(),\n });\n },\n });\n}\n","/**\n * @file This file contains the primary router for initializing transaction trackers.\n */\n\nimport { ITxTrackingStore, Transaction, TransactionStatus } from '@tuwaio/pulsar-core';\n\nimport { solanaTrackerForStore } from '../trackers/solanaTracker';\nimport { SolanaActionTxKey, SolanaTransactionTracker } from '../types';\n\n/**\n * Initializes the correct background tracker for a given Solana transaction.\n * This function acts as a router, selecting the appropriate tracker based on the `tx.tracker` property.\n *\n * @template T - The transaction type, constrained to Solana transactions.\n * @param {object} params - The parameters for initializing the tracker.\n * @param {T} params.tx - The transaction object to be tracked.\n * @param {SolanaTransactionTracker} params.tracker - The specific tracker to use.\n * @param {object} params.rest - The rest of the store's methods and state needed by the tracker.\n * @returns {Promise<void>} A promise that resolves when the tracker has been initialized.\n */\nexport async function checkAndInitializeTrackerInStore<T extends Transaction<SolanaTransactionTracker>>({\n tx,\n tracker,\n ...rest\n}: {\n tx: T;\n tracker: SolanaTransactionTracker;\n} & Pick<\n ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>,\n 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'\n>): Promise<void> {\n switch (tracker) {\n case SolanaTransactionTracker.Solana:\n await solanaTrackerForStore({\n tx,\n ...rest,\n });\n break;\n default:\n console.error(`Unknown tracker type for Solana adapter: ${tracker}`);\n // If an unsupported tracker is specified, mark the transaction as failed.\n rest.updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n errorMessage: `Unsupported tracker type: \"${tracker}\"`,\n });\n break;\n }\n}\n","/**\n * @file This file defines custom error classes for the @tuwaio/pulsar-solana package.\n */\n\nimport { SolanaCluster } from './types';\n\n/**\n * Thrown when the connected Solana cluster does not match the required cluster for a transaction.\n *\n * This allows consuming applications to `catch` this specific error and\n * implement custom logic, such as prompting the user to switch networks.\n */\nexport class SolanaChainMismatchError extends Error {\n /** The name of the error, for easy identification. */\n name = 'SolanaChainMismatchError';\n /** The cluster that the transaction requires (e.g., 'mainnet-beta'). */\n requiredCluster: SolanaCluster;\n /** The cluster the wallet is currently connected to. */\n currentCluster: SolanaCluster | string;\n\n constructor(requiredCluster: SolanaCluster, currentCluster: SolanaCluster | string) {\n const message = `Wrong network. The transaction requires ${requiredCluster}, but you are connected to ${currentCluster}.`;\n super(message);\n this.requiredCluster = requiredCluster;\n this.currentCluster = currentCluster;\n }\n}\n","/**\n * @file This file contains a utility to robustly verify the Solana cluster by its genesis hash.\n */\n\nimport { createSolanaRpc } from '@solana/kit';\n\nimport { SolanaChainMismatchError } from '../errors';\nimport { SolanaCluster } from '../types';\n\nconst SOLANA_GENESIS_HASHES: Record<SolanaCluster, string> = {\n 'mainnet-beta': '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d',\n devnet: 'GH7ome3EiwEr7tu9JuTh2dpYWBJK3z69Xm1ZE3MEE6JC',\n testnet: '4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY',\n};\n\n/**\n * Checks if an RPC endpoint is connected to the required Solana cluster.\n * It fetches the genesis hash from the RPC endpoint and compares it\n * with a known hash for the specified cluster.\n *\n * @param {string} rpcUrl - The RPC endpoint URL to check.\n * @param {SolanaCluster} requiredCluster - The cluster that the transaction requires (e.g., 'mainnet-beta').\n * @throws {SolanaChainMismatchError} If the connected chain does not match the required cluster.\n * @throws {Error} If the cluster name is unknown or if the RPC call fails for other reasons.\n */\nexport const checkSolanaChain = async (rpcUrl: string, requiredCluster: SolanaCluster): Promise<void> => {\n const expectedGenesisHash = SOLANA_GENESIS_HASHES[requiredCluster];\n if (!expectedGenesisHash) {\n throw new Error(`Unknown Solana cluster specified: ${requiredCluster}`);\n }\n\n // Note: For optimal performance in a high-traffic app, the created RPC client could be cached.\n // However, for a one-off check like this, creating it on the fly is perfectly fine.\n const rpc = createSolanaRpc(rpcUrl);\n const currentGenesisHash = await rpc.getGenesisHash().send();\n\n if (currentGenesisHash !== expectedGenesisHash) {\n const currentClusterName =\n Object.entries(SOLANA_GENESIS_HASHES).find(([, hash]) => hash === currentGenesisHash)?.[0] ||\n 'an unknown network';\n\n throw new SolanaChainMismatchError(requiredCluster, currentClusterName as SolanaCluster | string);\n }\n};\n","/**\n * @file This file contains a utility function for generating Solana transaction explorer links.\n */\n\nimport { SolanaCluster } from '../types';\n\n/**\n * Generates a full URL to a transaction on a Solana explorer like Solscan.\n *\n * @param {string} baseUrl - The base URL of the explorer (e.g., \"https://solscan.io\").\n * @param {string} txKey - The transaction signature (hash).\n * @param {SolanaCluster} [cluster] - The optional cluster name ('devnet', 'testnet') to add as a query parameter.\n * @returns {string} The full URL to the transaction on the explorer.\n */\nexport const selectSolanaTxExplorerLink = (baseUrl: string, txKey: string, cluster?: SolanaCluster): string => {\n // Ensure there are no trailing slashes on the base URL for clean URL construction.\n const sanitizedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n\n // Build the cluster query parameter if provided.\n const clusterParam = cluster ? `?cluster=${cluster}` : '';\n\n return `${sanitizedBaseUrl}/tx/${txKey}${clusterParam}`;\n};\n","/**\n * @file This file contains utility functions for interacting with the Solana Name Service (SNS) provided by Bonfida.\n */\n\nimport { getDomainKeysWithReverses, getRecord, performReverseLookup, Record } from '@bonfida/spl-name-service';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/kit';\nimport { ConnectionContextState } from '@solana/wallet-adapter-react';\n\n// A minimal PublicKey class to satisfy the @bonfida/spl-name-service dependency\n// without importing the entire @solana/web3.js package. This is a form of duck typing.\nclass PublicKey {\n private readonly _bn: Uint8Array;\n\n constructor(value: string) {\n // The return type of `encode` is `ReadonlyUint8Array`, which we cast to `Uint8Array`.\n this._bn = getBase58Encoder().encode(value) as Uint8Array;\n }\n\n toBuffer(): Buffer {\n return Buffer.from(this._bn);\n }\n\n toString(): string {\n // The decoder returns a tuple [decodedString, bytesRead], we need the first element.\n const [decodedString] = getBase58Decoder().decode(this._bn);\n return decodedString;\n }\n}\n\n/**\n * Performs a reverse lookup to find the .sol domain name for a given wallet address.\n * @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.\n * @param {string} address - The public key of the wallet as a string.\n * @returns {Promise<string | null>} The .sol domain name (e.g., \"bonfida.sol\") or null if not found.\n */\nexport const getSolanaName = async (connection: ConnectionContextState, address: string): Promise<string | null> => {\n try {\n const pubKey = new PublicKey(address);\n\n // @ts-expect-error We are duck-typing the PublicKey to avoid a full dependency.\n const domainKeys = await getDomainKeysWithReverses(connection.connection, pubKey);\n\n if (domainKeys.length === 0) {\n return null;\n }\n\n // @ts-expect-error Duck-typing continued for the result.\n const domainName = await performReverseLookup(connection.connection, domainKeys[0]);\n return `${domainName}.sol`;\n } catch {\n // Fails silently if no domain is found.\n return null;\n }\n};\n\n/**\n * Retrieves the avatar URL from the 'pic' record of a .sol domain name.\n * @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.\n * @param {string} name - The .sol domain name (e.g., \"bonfida.sol\").\n * @returns {Promise<string | null>} The URL of the avatar or null if not found or set.\n */\nexport const getSolanaAvatar = async (connection: ConnectionContextState, name: string): Promise<string | null> => {\n try {\n const record = await getRecord(connection.connection, name, Record.Pic);\n\n if (!record || !record.data) {\n return null;\n }\n\n return record.data.toString('utf-8');\n } catch {\n // Fails silently if the record doesn't exist.\n return null;\n }\n};\n","/**\n * @file This file contains the factory function for creating the Solana adapter for Pulsar.\n */\n\nimport { createSolanaRpc } from '@solana/kit';\nimport { Transaction, TransactionAdapter, TransactionPool, TxAdapter } from '@tuwaio/pulsar-core';\n\nimport { SolanaActionTxKey, SolanaAdapterConfig, SolanaCluster, SolanaTransactionTracker } from '../types';\nimport { checkAndInitializeTrackerInStore } from '../utils/checkAndInitializeTrackerInStore';\nimport { checkSolanaChain } from '../utils/checkSolanaChain';\nimport { selectSolanaTxExplorerLink } from '../utils/selectSolanaTxExplorerLink';\nimport { getSolanaAvatar, getSolanaName } from '../utils/snsUtils';\n\n/**\n * Factory function to create a Solana adapter for Pulsar.\n * This adapter provides all the necessary logic to interact with the Solana ecosystem,\n * including wallet interactions, transaction tracking, and name services.\n *\n * @param {SolanaAdapterConfig} config - The configuration object, typically derived from Solana wallet adapter hooks.\n * @returns {TxAdapter} An object conforming to the `TxAdapter` interface.\n */\nexport function solanaAdapter<T extends Transaction<SolanaTransactionTracker>>(\n config: SolanaAdapterConfig,\n): TxAdapter<SolanaTransactionTracker, T, SolanaActionTxKey> {\n const { wallet, connection, explorerUrl, cluster } = config;\n\n return {\n key: TransactionAdapter.SOLANA,\n\n // --- Core Methods ---\n getWalletInfo: () => ({\n walletAddress: wallet?.publicKey?.toBase58() ?? '0x0',\n walletType: wallet?.wallet?.adapter.name.toLowerCase() ?? 'unknown',\n }),\n\n checkChainForTx: async (txCluster) => {\n // Use the rpcEndpoint from the main connection context for pre-flight checks.\n const currentRpcUrl = connection?.connection.rpcEndpoint;\n if (!currentRpcUrl) {\n // This can happen if the adapter is used in a read-only mode without a provider.\n // We warn but do not throw, allowing tracking to continue if the rpcUrl is in the tx.\n console.warn('Cannot check chain: connection context not provided to adapter.');\n return;\n }\n await checkSolanaChain(currentRpcUrl, txCluster as SolanaCluster);\n },\n\n checkTransactionsTracker: (actionTxKey) => {\n // For Solana, the actionTxKey is always the transaction signature.\n return { tracker: SolanaTransactionTracker.Solana, txKey: actionTxKey };\n },\n\n checkAndInitializeTrackerInStore: ({ tx, ...rest }) => {\n // Delegate to the tracker router utility.\n return checkAndInitializeTrackerInStore({\n tracker: tx.tracker,\n tx,\n ...rest,\n });\n },\n\n // --- UI & Explorer Methods ---\n getExplorerUrl: () => {\n return explorerUrl ?? 'https://solscan.io';\n },\n\n getExplorerTxUrl: (txPool: TransactionPool<any, any>, txKey: string) => {\n const baseUrl = explorerUrl ?? 'https://solscan.io';\n return selectSolanaTxExplorerLink(baseUrl, txKey, cluster);\n },\n\n // --- Optional Name Service Methods ---\n getName: async (address: string) => {\n if (!connection) {\n console.warn('Cannot get name: connection context not provided to adapter.');\n return null;\n }\n return getSolanaName(connection, address);\n },\n\n getAvatar: async (name: string) => {\n if (!connection) {\n console.warn('Cannot get avatar: connection context not provided to adapter.');\n return null;\n }\n return getSolanaAvatar(connection, name);\n },\n\n // --- Optional Actions ---\n retryTxAction: async ({ actions, onClose, txKey, handleTransaction, tx }) => {\n onClose(txKey);\n\n if (!wallet) {\n throw new Error('Retry failed: A wallet must be connected to retry a transaction.');\n }\n if (!handleTransaction) {\n throw new Error('Retry failed: handleTransaction function is not provided.');\n }\n\n const actionKey = tx.actionKey;\n if (!actionKey || !actions?.[actionKey]) {\n throw new Error(`Retry failed: No action found for actionKey \"${actionKey}\".`);\n }\n\n const retryAction = actions[actionKey];\n\n // Prioritize the RPC URL from the original transaction, falling back to the current connection.\n const rpcUrlForRetry = tx.rpcUrl ?? connection?.connection.rpcEndpoint;\n if (!rpcUrlForRetry) {\n throw new Error('Retry failed: Could not determine RPC endpoint.');\n }\n\n const rpcForRetry = createSolanaRpc(rpcUrlForRetry);\n\n await handleTransaction({\n actionFunction: () =>\n (retryAction as any)({\n wallet,\n connection: connection?.connection,\n rpc: rpcForRetry,\n ...tx.payload,\n }),\n params: tx,\n defaultTracker: SolanaTransactionTracker.Solana,\n });\n },\n };\n}\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {createSolanaRpc,getBase58Encoder,getBase58Decoder}from'@solana/kit';import {TransactionAdapter,initializePollingTracker,TransactionStatus}from'@tuwaio/pulsar-core';import u from'dayjs';import {getDomainKeysWithReverses,performReverseLookup,getRecord,Record}from'@bonfida/spl-name-service';var S=(n=>(n.Solana="solana",n))(S||{});var d=new Map,b=r=>{if(d.has(r))return d.get(r);let n=createSolanaRpc(r);return d.set(r,n),n};async function N({tx:r,stopPolling:n,onSuccess:t,onFailure:a,onIntervalTick:i}){if(r.adapter!==TransactionAdapter.SOLANA||!r.rpcUrl)throw new Error("RPC URL is missing from the Solana transaction.");let s=(await b(r.rpcUrl).getSignatureStatuses([r.txKey]).send())?.value[0];if(!s)return;let c=s;if(i?.(c),c.err){a(c);return}c.confirmationStatus==="finalized"&&t(c),u().diff(u.unix(r.localTimestamp),"minute")>=30&&(n({withoutRemoving:true}),a(c));}async function x({tx:r,...n}){return initializePollingTracker({tx:r,fetcher:N,removeTxFromPool:n.removeTxFromPool,pollingInterval:2500,maxRetries:720,onSuccess:t=>{n.updateTxParams(r.txKey,{status:TransactionStatus.Success,pending:false,isError:false,finishedTimestamp:u().unix(),confirmations:t.confirmations??1,slot:Number(t.slot)});let a=n.transactionsPool[r.txKey];n.onSucceedCallbacks&&a&&n.onSucceedCallbacks(a);},onIntervalTick:t=>{n.updateTxParams(r.txKey,{confirmations:t.confirmations??0,slot:Number(t.slot)});},onFailure:t=>{let a=t?.err?`Transaction failed: ${JSON.stringify(t.err)}`:"Transaction tracking timed out or the transaction was not found.";n.updateTxParams(r.txKey,{status:TransactionStatus.Failed,pending:false,isError:true,errorMessage:a,finishedTimestamp:u().unix()});}})}async function y({tx:r,tracker:n,...t}){switch(n){case "solana":await x({tx:r,...t});break;default:console.error(`Unknown tracker type for Solana adapter: ${n}`),t.updateTxParams(r.txKey,{status:TransactionStatus.Failed,pending:false,isError:true,errorMessage:`Unsupported tracker type: "${n}"`});break}}var m=class extends Error{name="SolanaChainMismatchError";requiredCluster;currentCluster;constructor(n,t){let a=`Wrong network. The transaction requires ${n}, but you are connected to ${t}.`;super(a),this.requiredCluster=n,this.currentCluster=t;}};var k={"mainnet-beta":"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",devnet:"GH7ome3EiwEr7tu9JuTh2dpYWBJK3z69Xm1ZE3MEE6JC",testnet:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY"},h=async(r,n)=>{let t=k[n];if(!t)throw new Error(`Unknown Solana cluster specified: ${n}`);let i=await createSolanaRpc(r).getGenesisHash().send();if(i!==t){let o=Object.entries(k).find(([,e])=>e===i)?.[0]||"an unknown network";throw new m(n,o)}};var C=(r,n,t)=>{let a=r.endsWith("/")?r.slice(0,-1):r,i=t?`?cluster=${t}`:"";return `${a}/tx/${n}${i}`};var f=class{_bn;constructor(n){this._bn=getBase58Encoder().encode(n);}toBuffer(){return Buffer.from(this._bn)}toString(){let[n]=getBase58Decoder().decode(this._bn);return n}},w=async(r,n)=>{try{let t=new f(n),a=await getDomainKeysWithReverses(r.connection,t);return a.length===0?null:`${await performReverseLookup(r.connection,a[0])}.sol`}catch{return null}},A=async(r,n)=>{try{let t=await getRecord(r.connection,n,Record.Pic);return !t||!t.data?null:t.data.toString("utf-8")}catch{return null}};function Kn(r){let{wallet:n,connection:t,explorerUrl:a,cluster:i}=r;return {key:TransactionAdapter.SOLANA,getWalletInfo:()=>({walletAddress:n?.publicKey?.toBase58()??"0x0",walletType:n?.wallet?.adapter.name.toLowerCase()??"unknown"}),checkChainForTx:async o=>{let e=t?.connection.rpcEndpoint;if(!e){console.warn("Cannot check chain: connection context not provided to adapter.");return}await h(e,o);},checkTransactionsTracker:o=>({tracker:"solana",txKey:o}),checkAndInitializeTrackerInStore:({tx:o,...e})=>y({tracker:o.tracker,tx:o,...e}),getExplorerUrl:()=>a??"https://solscan.io",getExplorerTxUrl:(o,e)=>C(a??"https://solscan.io",e,i),getName:async o=>t?w(t,o):(console.warn("Cannot get name: connection context not provided to adapter."),null),getAvatar:async o=>t?A(t,o):(console.warn("Cannot get avatar: connection context not provided to adapter."),null),retryTxAction:async({actions:o,onClose:e,txKey:s,handleTransaction:c,tx:l})=>{if(e(s),!n)throw new Error("Retry failed: A wallet must be connected to retry a transaction.");if(!c)throw new Error("Retry failed: handleTransaction function is not provided.");let p=l.actionKey;if(!p||!o?.[p])throw new Error(`Retry failed: No action found for actionKey "${p}".`);let R=o[p],T=l.rpcUrl??t?.connection.rpcEndpoint;if(!T)throw new Error("Retry failed: Could not determine RPC endpoint.");let P=createSolanaRpc(T);await c({actionFunction:()=>R({wallet:n,connection:t?.connection,rpc:P,...l.payload}),params:l,defaultTracker:"solana"});}}}
|
|
2
|
+
export{m as SolanaChainMismatchError,S as SolanaTransactionTracker,y as checkAndInitializeTrackerInStore,h as checkSolanaChain,A as getSolanaAvatar,w as getSolanaName,C as selectSolanaTxExplorerLink,Kn as solanaAdapter,N as solanaFetcher,x as solanaTrackerForStore};//# sourceMappingURL=index.mjs.map
|
|
3
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/trackers/solanaTracker.ts","../src/utils/checkAndInitializeTrackerInStore.ts","../src/errors.ts","../src/utils/checkSolanaChain.ts","../src/utils/selectSolanaTxExplorerLink.ts","../src/utils/snsUtils.ts","../src/adapters/solanaAdapter.ts"],"names":["SolanaTransactionTracker","rpcCache","getRpcClient","rpcUrl","newRpc","createSolanaRpc","solanaFetcher","tx","stopPolling","onSuccess","onFailure","onIntervalTick","TransactionAdapter","status","typedStatus","dayjs","solanaTrackerForStore","rest","initializePollingTracker","response","TransactionStatus","updatedTx","errorMessage","checkAndInitializeTrackerInStore","tracker","SolanaChainMismatchError","requiredCluster","currentCluster","message","SOLANA_GENESIS_HASHES","checkSolanaChain","expectedGenesisHash","currentGenesisHash","currentClusterName","hash","selectSolanaTxExplorerLink","baseUrl","txKey","cluster","sanitizedBaseUrl","clusterParam","PublicKey","value","getBase58Encoder","decodedString","getBase58Decoder","getSolanaName","connection","address","pubKey","domainKeys","getDomainKeysWithReverses","performReverseLookup","getSolanaAvatar","name","record","getRecord","Record","solanaAdapter","config","wallet","explorerUrl","txCluster","currentRpcUrl","actionTxKey","txPool","actions","onClose","handleTransaction","actionKey","retryAction","rpcUrlForRetry","rpcForRetry"],"mappings":"ySA8BO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GAEVA,CAAAA,CAAA,MAAA,CAAS,SAFCA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA,ECNZ,IAAMC,CAAAA,CAAW,IAAI,GAAA,CAQfC,EAAgBC,CAAAA,EAAsC,CAC1D,GAAIF,CAAAA,CAAS,GAAA,CAAIE,CAAM,CAAA,CACrB,OAAOF,CAAAA,CAAS,GAAA,CAAIE,CAAM,CAAA,CAE5B,IAAMC,CAAAA,CAASC,eAAAA,CAAgBF,CAAM,CAAA,CACrC,OAAAF,EAAS,GAAA,CAAIE,CAAAA,CAAQC,CAAM,CAAA,CACpBA,CACT,CAAA,CAiCA,eAAsBE,CAAAA,CAAc,CAAE,GAAAC,CAAAA,CAAI,WAAA,CAAAC,EAAa,SAAA,CAAAC,CAAAA,CAAW,SAAA,CAAAC,CAAAA,CAAW,cAAA,CAAAC,CAAe,EAAwB,CACl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@file Defines the core types and enums specific to the @tuwaio/pulsar-solana package.\n */\n\nimport { ConnectionContextState, WalletContextState } from '@solana/wallet-adapter-react';\n\n/**\n * Defines the possible Solana network clusters.\n */\nexport type SolanaCluster = 'mainnet-beta' | 'devnet' | 'testnet';\n\n/**\n * Configuration object for the `solanaAdapter`.\n * All properties are optional and are typically derived from the Solana wallet adapter hooks.\n *\n * @property {WalletContextState} [wallet] - The state object from `useWallet()`. Required for actions that need a connected wallet, like signing or retrying transactions.\n * @property {ConnectionContextState} [connection] - The state object from `useConnection()`. Required for on-chain operations like checking the network or using the Solana Name Service.\n * @property {string} [explorerUrl] - The base URL for the transaction explorer (e.g., \"https://solscan.io\"). Defaults to Solscan if not provided.\n * @property {SolanaCluster} [cluster] - The specific cluster the app is connected to. Used for generating correct explorer links.\n */\nexport interface SolanaAdapterConfig {\n wallet?: WalletContextState;\n connection?: ConnectionContextState;\n explorerUrl?: string;\n cluster?: SolanaCluster;\n}\n\n/**\n * Defines the tracker identifiers available in the Solana adapter.\n */\nexport enum SolanaTransactionTracker {\n /** The default tracker for monitoring standard Solana transaction signatures. */\n Solana = 'solana',\n}\n\n/**\n * Represents the unique key returned by a transaction-creating action on Solana.\n * For standard Solana transactions, this is always the transaction signature as a base58 string.\n */\nexport type SolanaActionTxKey = string;\n","/**\n * @file Implements the transaction tracking logic for standard Solana transactions.\n * It uses a polling mechanism to query the `getSignatureStatuses` RPC method.\n */\n\nimport { createSolanaRpc, Rpc, Signature, SolanaRpcApi, TransactionError } from '@solana/kit';\nimport {\n initializePollingTracker,\n ITxTrackingStore,\n PollingTrackerConfig,\n Transaction,\n TransactionAdapter,\n TransactionStatus,\n} from '@tuwaio/pulsar-core';\nimport dayjs from 'dayjs';\n\nimport { SolanaActionTxKey, SolanaTransactionTracker } from '../types';\n\n// --- RPC Client Caching ---\n\n/**\n * An in-memory cache for RPC clients to avoid re-creating them on every poll.\n * @internal\n */\nconst rpcCache = new Map<string, Rpc<SolanaRpcApi>>();\n\n/**\n * Retrieves a cached RPC client for a given URL or creates a new one.\n * @param rpcUrl - The RPC endpoint URL.\n * @returns The RPC client instance.\n * @internal\n */\nconst getRpcClient = (rpcUrl: string): Rpc<SolanaRpcApi> => {\n if (rpcCache.has(rpcUrl)) {\n return rpcCache.get(rpcUrl)!;\n }\n const newRpc = createSolanaRpc(rpcUrl);\n rpcCache.set(rpcUrl, newRpc);\n return newRpc;\n};\n\n// --- Types ---\n\n/**\n * The shape of the status object returned for each signature from `getSignatureStatuses`.\n * @internal\n */\ntype SolanaSignatureStatusResponse = {\n slot: bigint;\n confirmations: number | null;\n err: TransactionError | null;\n confirmationStatus: 'processed' | 'confirmed' | 'finalized' | null;\n};\n\n/**\n * The parameters for our specific fetcher function.\n * @internal\n */\ntype SolanaFetcherParams = Parameters<\n PollingTrackerConfig<\n SolanaSignatureStatusResponse,\n Transaction<SolanaTransactionTracker>,\n SolanaTransactionTracker\n >['fetcher']\n>[0];\n\n// --- Fetcher Implementation ---\n\n/**\n * A reusable fetcher for `initializePollingTracker` that queries the Solana RPC for a transaction's signature status.\n * This is the core polling logic that powers the tracker.\n */\nexport async function solanaFetcher({ tx, stopPolling, onSuccess, onFailure, onIntervalTick }: SolanaFetcherParams) {\n if (tx.adapter !== TransactionAdapter.SOLANA || !tx.rpcUrl) {\n // This should not happen if the types are correct, but it's a good runtime safeguard.\n throw new Error('RPC URL is missing from the Solana transaction.');\n }\n\n const rpc = getRpcClient(tx.rpcUrl);\n const statuses = await rpc.getSignatureStatuses([tx.txKey as Signature]).send();\n const status = statuses?.value[0];\n\n if (!status) {\n // Continue polling if the transaction is not yet found by the RPC node.\n // The polling tracker will handle the retry delay.\n return;\n }\n\n const typedStatus = status as SolanaSignatureStatusResponse;\n onIntervalTick?.(typedStatus);\n\n if (typedStatus.err) {\n onFailure(typedStatus); // Terminal failure state\n return;\n }\n\n if (typedStatus.confirmationStatus === 'finalized') {\n onSuccess(typedStatus); // Terminal success state\n }\n\n // Safeguard: Stop polling for very old pending transactions.\n if (dayjs().diff(dayjs.unix(tx.localTimestamp), 'minute') >= 30) {\n stopPolling({ withoutRemoving: true });\n // When a timeout occurs, we call `onFailure` with the last known status,\n // but the tracker itself will provide the specific timeout error message.\n onFailure(typedStatus);\n }\n}\n\n// --- Store-Connected Tracker ---\n\n/**\n * A higher-level wrapper that integrates the Solana polling logic with the Pulsar store.\n * It uses the generic `solanaFetcher` and provides store-specific callbacks.\n *\n * @template T - The application-specific transaction type, constrained to Transaction.\n */\nexport async function solanaTrackerForStore<T extends Transaction<SolanaTransactionTracker>>({\n tx,\n ...rest\n}: Pick<\n ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>,\n 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'\n> & {\n tx: T;\n}) {\n return initializePollingTracker<SolanaSignatureStatusResponse, T, SolanaTransactionTracker>({\n tx,\n fetcher: solanaFetcher,\n removeTxFromPool: rest.removeTxFromPool,\n pollingInterval: 2500,\n maxRetries: 720, // 30 minutes timeout (720 intervals * 2.5s = 1800s)\n onSuccess: (response) => {\n rest.updateTxParams(tx.txKey, {\n status: TransactionStatus.Success,\n pending: false,\n isError: false,\n finishedTimestamp: dayjs().unix(),\n confirmations: response.confirmations ?? 1,\n slot: Number(response.slot),\n });\n\n const updatedTx = rest.transactionsPool[tx.txKey];\n if (rest.onSucceedCallbacks && updatedTx) {\n rest.onSucceedCallbacks(updatedTx);\n }\n },\n onIntervalTick: (response) => {\n rest.updateTxParams(tx.txKey, {\n confirmations: response.confirmations ?? 0,\n slot: Number(response.slot),\n });\n },\n onFailure: (response) => {\n // If `response` is undefined, it means the polling timed out from `initializePollingTracker`.\n // Otherwise, the transaction failed on-chain.\n const errorMessage = response?.err\n ? `Transaction failed: ${JSON.stringify(response.err)}`\n : 'Transaction tracking timed out or the transaction was not found.';\n\n rest.updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n errorMessage,\n finishedTimestamp: dayjs().unix(),\n });\n },\n });\n}\n","/**\n * @file This file contains the primary router for initializing transaction trackers.\n */\n\nimport { ITxTrackingStore, Transaction, TransactionStatus } from '@tuwaio/pulsar-core';\n\nimport { solanaTrackerForStore } from '../trackers/solanaTracker';\nimport { SolanaActionTxKey, SolanaTransactionTracker } from '../types';\n\n/**\n * Initializes the correct background tracker for a given Solana transaction.\n * This function acts as a router, selecting the appropriate tracker based on the `tx.tracker` property.\n *\n * @template T - The transaction type, constrained to Solana transactions.\n * @param {object} params - The parameters for initializing the tracker.\n * @param {T} params.tx - The transaction object to be tracked.\n * @param {SolanaTransactionTracker} params.tracker - The specific tracker to use.\n * @param {object} params.rest - The rest of the store's methods and state needed by the tracker.\n * @returns {Promise<void>} A promise that resolves when the tracker has been initialized.\n */\nexport async function checkAndInitializeTrackerInStore<T extends Transaction<SolanaTransactionTracker>>({\n tx,\n tracker,\n ...rest\n}: {\n tx: T;\n tracker: SolanaTransactionTracker;\n} & Pick<\n ITxTrackingStore<SolanaTransactionTracker, T, SolanaActionTxKey>,\n 'transactionsPool' | 'updateTxParams' | 'onSucceedCallbacks' | 'removeTxFromPool'\n>): Promise<void> {\n switch (tracker) {\n case SolanaTransactionTracker.Solana:\n await solanaTrackerForStore({\n tx,\n ...rest,\n });\n break;\n default:\n console.error(`Unknown tracker type for Solana adapter: ${tracker}`);\n // If an unsupported tracker is specified, mark the transaction as failed.\n rest.updateTxParams(tx.txKey, {\n status: TransactionStatus.Failed,\n pending: false,\n isError: true,\n errorMessage: `Unsupported tracker type: \"${tracker}\"`,\n });\n break;\n }\n}\n","/**\n * @file This file defines custom error classes for the @tuwaio/pulsar-solana package.\n */\n\nimport { SolanaCluster } from './types';\n\n/**\n * Thrown when the connected Solana cluster does not match the required cluster for a transaction.\n *\n * This allows consuming applications to `catch` this specific error and\n * implement custom logic, such as prompting the user to switch networks.\n */\nexport class SolanaChainMismatchError extends Error {\n /** The name of the error, for easy identification. */\n name = 'SolanaChainMismatchError';\n /** The cluster that the transaction requires (e.g., 'mainnet-beta'). */\n requiredCluster: SolanaCluster;\n /** The cluster the wallet is currently connected to. */\n currentCluster: SolanaCluster | string;\n\n constructor(requiredCluster: SolanaCluster, currentCluster: SolanaCluster | string) {\n const message = `Wrong network. The transaction requires ${requiredCluster}, but you are connected to ${currentCluster}.`;\n super(message);\n this.requiredCluster = requiredCluster;\n this.currentCluster = currentCluster;\n }\n}\n","/**\n * @file This file contains a utility to robustly verify the Solana cluster by its genesis hash.\n */\n\nimport { createSolanaRpc } from '@solana/kit';\n\nimport { SolanaChainMismatchError } from '../errors';\nimport { SolanaCluster } from '../types';\n\nconst SOLANA_GENESIS_HASHES: Record<SolanaCluster, string> = {\n 'mainnet-beta': '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d',\n devnet: 'GH7ome3EiwEr7tu9JuTh2dpYWBJK3z69Xm1ZE3MEE6JC',\n testnet: '4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY',\n};\n\n/**\n * Checks if an RPC endpoint is connected to the required Solana cluster.\n * It fetches the genesis hash from the RPC endpoint and compares it\n * with a known hash for the specified cluster.\n *\n * @param {string} rpcUrl - The RPC endpoint URL to check.\n * @param {SolanaCluster} requiredCluster - The cluster that the transaction requires (e.g., 'mainnet-beta').\n * @throws {SolanaChainMismatchError} If the connected chain does not match the required cluster.\n * @throws {Error} If the cluster name is unknown or if the RPC call fails for other reasons.\n */\nexport const checkSolanaChain = async (rpcUrl: string, requiredCluster: SolanaCluster): Promise<void> => {\n const expectedGenesisHash = SOLANA_GENESIS_HASHES[requiredCluster];\n if (!expectedGenesisHash) {\n throw new Error(`Unknown Solana cluster specified: ${requiredCluster}`);\n }\n\n // Note: For optimal performance in a high-traffic app, the created RPC client could be cached.\n // However, for a one-off check like this, creating it on the fly is perfectly fine.\n const rpc = createSolanaRpc(rpcUrl);\n const currentGenesisHash = await rpc.getGenesisHash().send();\n\n if (currentGenesisHash !== expectedGenesisHash) {\n const currentClusterName =\n Object.entries(SOLANA_GENESIS_HASHES).find(([, hash]) => hash === currentGenesisHash)?.[0] ||\n 'an unknown network';\n\n throw new SolanaChainMismatchError(requiredCluster, currentClusterName as SolanaCluster | string);\n }\n};\n","/**\n * @file This file contains a utility function for generating Solana transaction explorer links.\n */\n\nimport { SolanaCluster } from '../types';\n\n/**\n * Generates a full URL to a transaction on a Solana explorer like Solscan.\n *\n * @param {string} baseUrl - The base URL of the explorer (e.g., \"https://solscan.io\").\n * @param {string} txKey - The transaction signature (hash).\n * @param {SolanaCluster} [cluster] - The optional cluster name ('devnet', 'testnet') to add as a query parameter.\n * @returns {string} The full URL to the transaction on the explorer.\n */\nexport const selectSolanaTxExplorerLink = (baseUrl: string, txKey: string, cluster?: SolanaCluster): string => {\n // Ensure there are no trailing slashes on the base URL for clean URL construction.\n const sanitizedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n\n // Build the cluster query parameter if provided.\n const clusterParam = cluster ? `?cluster=${cluster}` : '';\n\n return `${sanitizedBaseUrl}/tx/${txKey}${clusterParam}`;\n};\n","/**\n * @file This file contains utility functions for interacting with the Solana Name Service (SNS) provided by Bonfida.\n */\n\nimport { getDomainKeysWithReverses, getRecord, performReverseLookup, Record } from '@bonfida/spl-name-service';\nimport { getBase58Decoder, getBase58Encoder } from '@solana/kit';\nimport { ConnectionContextState } from '@solana/wallet-adapter-react';\n\n// A minimal PublicKey class to satisfy the @bonfida/spl-name-service dependency\n// without importing the entire @solana/web3.js package. This is a form of duck typing.\nclass PublicKey {\n private readonly _bn: Uint8Array;\n\n constructor(value: string) {\n // The return type of `encode` is `ReadonlyUint8Array`, which we cast to `Uint8Array`.\n this._bn = getBase58Encoder().encode(value) as Uint8Array;\n }\n\n toBuffer(): Buffer {\n return Buffer.from(this._bn);\n }\n\n toString(): string {\n // The decoder returns a tuple [decodedString, bytesRead], we need the first element.\n const [decodedString] = getBase58Decoder().decode(this._bn);\n return decodedString;\n }\n}\n\n/**\n * Performs a reverse lookup to find the .sol domain name for a given wallet address.\n * @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.\n * @param {string} address - The public key of the wallet as a string.\n * @returns {Promise<string | null>} The .sol domain name (e.g., \"bonfida.sol\") or null if not found.\n */\nexport const getSolanaName = async (connection: ConnectionContextState, address: string): Promise<string | null> => {\n try {\n const pubKey = new PublicKey(address);\n\n // @ts-expect-error We are duck-typing the PublicKey to avoid a full dependency.\n const domainKeys = await getDomainKeysWithReverses(connection.connection, pubKey);\n\n if (domainKeys.length === 0) {\n return null;\n }\n\n // @ts-expect-error Duck-typing continued for the result.\n const domainName = await performReverseLookup(connection.connection, domainKeys[0]);\n return `${domainName}.sol`;\n } catch {\n // Fails silently if no domain is found.\n return null;\n }\n};\n\n/**\n * Retrieves the avatar URL from the 'pic' record of a .sol domain name.\n * @param {ConnectionContextState} connection - The connection state object from the `useConnection` hook.\n * @param {string} name - The .sol domain name (e.g., \"bonfida.sol\").\n * @returns {Promise<string | null>} The URL of the avatar or null if not found or set.\n */\nexport const getSolanaAvatar = async (connection: ConnectionContextState, name: string): Promise<string | null> => {\n try {\n const record = await getRecord(connection.connection, name, Record.Pic);\n\n if (!record || !record.data) {\n return null;\n }\n\n return record.data.toString('utf-8');\n } catch {\n // Fails silently if the record doesn't exist.\n return null;\n }\n};\n","/**\n * @file This file contains the factory function for creating the Solana adapter for Pulsar.\n */\n\nimport { createSolanaRpc } from '@solana/kit';\nimport { Transaction, TransactionAdapter, TransactionPool, TxAdapter } from '@tuwaio/pulsar-core';\n\nimport { SolanaActionTxKey, SolanaAdapterConfig, SolanaCluster, SolanaTransactionTracker } from '../types';\nimport { checkAndInitializeTrackerInStore } from '../utils/checkAndInitializeTrackerInStore';\nimport { checkSolanaChain } from '../utils/checkSolanaChain';\nimport { selectSolanaTxExplorerLink } from '../utils/selectSolanaTxExplorerLink';\nimport { getSolanaAvatar, getSolanaName } from '../utils/snsUtils';\n\n/**\n * Factory function to create a Solana adapter for Pulsar.\n * This adapter provides all the necessary logic to interact with the Solana ecosystem,\n * including wallet interactions, transaction tracking, and name services.\n *\n * @param {SolanaAdapterConfig} config - The configuration object, typically derived from Solana wallet adapter hooks.\n * @returns {TxAdapter} An object conforming to the `TxAdapter` interface.\n */\nexport function solanaAdapter<T extends Transaction<SolanaTransactionTracker>>(\n config: SolanaAdapterConfig,\n): TxAdapter<SolanaTransactionTracker, T, SolanaActionTxKey> {\n const { wallet, connection, explorerUrl, cluster } = config;\n\n return {\n key: TransactionAdapter.SOLANA,\n\n // --- Core Methods ---\n getWalletInfo: () => ({\n walletAddress: wallet?.publicKey?.toBase58() ?? '0x0',\n walletType: wallet?.wallet?.adapter.name.toLowerCase() ?? 'unknown',\n }),\n\n checkChainForTx: async (txCluster) => {\n // Use the rpcEndpoint from the main connection context for pre-flight checks.\n const currentRpcUrl = connection?.connection.rpcEndpoint;\n if (!currentRpcUrl) {\n // This can happen if the adapter is used in a read-only mode without a provider.\n // We warn but do not throw, allowing tracking to continue if the rpcUrl is in the tx.\n console.warn('Cannot check chain: connection context not provided to adapter.');\n return;\n }\n await checkSolanaChain(currentRpcUrl, txCluster as SolanaCluster);\n },\n\n checkTransactionsTracker: (actionTxKey) => {\n // For Solana, the actionTxKey is always the transaction signature.\n return { tracker: SolanaTransactionTracker.Solana, txKey: actionTxKey };\n },\n\n checkAndInitializeTrackerInStore: ({ tx, ...rest }) => {\n // Delegate to the tracker router utility.\n return checkAndInitializeTrackerInStore({\n tracker: tx.tracker,\n tx,\n ...rest,\n });\n },\n\n // --- UI & Explorer Methods ---\n getExplorerUrl: () => {\n return explorerUrl ?? 'https://solscan.io';\n },\n\n getExplorerTxUrl: (txPool: TransactionPool<any, any>, txKey: string) => {\n const baseUrl = explorerUrl ?? 'https://solscan.io';\n return selectSolanaTxExplorerLink(baseUrl, txKey, cluster);\n },\n\n // --- Optional Name Service Methods ---\n getName: async (address: string) => {\n if (!connection) {\n console.warn('Cannot get name: connection context not provided to adapter.');\n return null;\n }\n return getSolanaName(connection, address);\n },\n\n getAvatar: async (name: string) => {\n if (!connection) {\n console.warn('Cannot get avatar: connection context not provided to adapter.');\n return null;\n }\n return getSolanaAvatar(connection, name);\n },\n\n // --- Optional Actions ---\n retryTxAction: async ({ actions, onClose, txKey, handleTransaction, tx }) => {\n onClose(txKey);\n\n if (!wallet) {\n throw new Error('Retry failed: A wallet must be connected to retry a transaction.');\n }\n if (!handleTransaction) {\n throw new Error('Retry failed: handleTransaction function is not provided.');\n }\n\n const actionKey = tx.actionKey;\n if (!actionKey || !actions?.[actionKey]) {\n throw new Error(`Retry failed: No action found for actionKey \"${actionKey}\".`);\n }\n\n const retryAction = actions[actionKey];\n\n // Prioritize the RPC URL from the original transaction, falling back to the current connection.\n const rpcUrlForRetry = tx.rpcUrl ?? connection?.connection.rpcEndpoint;\n if (!rpcUrlForRetry) {\n throw new Error('Retry failed: Could not determine RPC endpoint.');\n }\n\n const rpcForRetry = createSolanaRpc(rpcUrlForRetry);\n\n await handleTransaction({\n actionFunction: () =>\n (retryAction as any)({\n wallet,\n connection: connection?.connection,\n rpc: rpcForRetry,\n ...tx.payload,\n }),\n params: tx,\n defaultTracker: SolanaTransactionTracker.Solana,\n });\n },\n };\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tuwaio/pulsar-solana",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"author": "Oleksandr Tkach",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"description": "An adapter for the Pulsar Engine that adds support for tracking transactions on the Solana blockchain. Integrates with @solana/kit and @solana/wallet-adapter-react.",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"module": "./dist/index.mjs",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"keywords": [
|
|
18
|
+
"web3",
|
|
19
|
+
"solana",
|
|
20
|
+
"transaction",
|
|
21
|
+
"tracking",
|
|
22
|
+
"@solana/kit",
|
|
23
|
+
"zustand"
|
|
24
|
+
],
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/TuwaIO/pulsar-core.git",
|
|
28
|
+
"directory": "packages/pulsar-solana"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://github.com/TuwaIO/pulsar-core",
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/TuwaIO/pulsar-core/issues"
|
|
33
|
+
},
|
|
34
|
+
"contributors": [
|
|
35
|
+
{
|
|
36
|
+
"name": "Oleksandr Tkach",
|
|
37
|
+
"url": "https://github.com/Argeare5"
|
|
38
|
+
}
|
|
39
|
+
],
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@bonfida/spl-name-service": ">=3",
|
|
42
|
+
"@solana/kit": ">=3",
|
|
43
|
+
"@solana/wallet-adapter-react": ">=0.15",
|
|
44
|
+
"@tuwaio/pulsar-core": ">=0",
|
|
45
|
+
"dayjs": ">=1",
|
|
46
|
+
"immer": ">=10",
|
|
47
|
+
"zustand": ">=5"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@bonfida/spl-name-service": "^3.0.16",
|
|
51
|
+
"@solana/kit": "^3.0.2",
|
|
52
|
+
"@solana/wallet-adapter-react": "^0.15.39",
|
|
53
|
+
"dayjs": "^1.11.18",
|
|
54
|
+
"immer": "^10.1.3",
|
|
55
|
+
"jsdom": "^26.1.0",
|
|
56
|
+
"tsup": "^8.5.0",
|
|
57
|
+
"typescript": "^5.9.2",
|
|
58
|
+
"vitest": "^3.2.4",
|
|
59
|
+
"zustand": "^5.0.8",
|
|
60
|
+
"@tuwaio/pulsar-core": "^0.1.0"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"start": "tsup src/index.ts --watch",
|
|
64
|
+
"build": "tsup",
|
|
65
|
+
"test": "vitest"
|
|
66
|
+
}
|
|
67
|
+
}
|