@injectivelabs/wallet-privy 0.0.0-stage → 1.20.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright © 2021 - 2022 Injective Labs Inc. (https://injectivelabs.org/)
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [2022] [InjectiveLabs]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # 🌟 Injective Protocol - Privy Wallet Strategy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![downloads](https://img.shields.io/npm/dm/@injectivelabs/wallet-privy.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-privy)
4
+ [![npm-version](https://img.shields.io/npm/v/@injectivelabs/wallet-privy.svg)](https://www.npmjs.com/package/@injectivelabs/wallet-privy)
5
+ [![license](https://img.shields.io/npm/l/express.svg)]()
6
+
7
+ _Package to use a Privy embedded wallet on Injective via the wallet strategy._
8
+
9
+ ---
10
+
11
+ ## 📚 Installation
12
+
13
+ ```bash
14
+ pnpm add @injectivelabs/wallet-privy
15
+ ```
16
+
17
+ ---
18
+
19
+ ## 📖 Documentation
20
+
21
+ The strategy does not depend on a Privy SDK. Your app signs the user in with Privy
22
+ (tested with `@privy-io/js-sdk-core` on web) and hands the strategy the embedded
23
+ wallet's address and a function that returns its EIP-1193 provider.
24
+ Privy keeps the key; the strategy only sends requests to that provider, so the
25
+ provider must support these methods:
26
+
27
+ | Strategy method | Provider request |
28
+ | --------------------- | ---------------------------------------------------------------------------- |
29
+ | `signEip712TypedData` | `secp256k1_sign` on the EIP-712 digest, like the Turnkey strategy |
30
+ | `signArbitrary` | `personal_sign` |
31
+ | `sendEvmTransaction` | `secp256k1_sign` on the transaction hash; prepared and sent via `evmOptions` |
32
+ | `sendTransaction` | none: broadcasts the signed Injective transaction over gRPC |
33
+
34
+ Privy only ever sees hashes of EVM transactions, so Privy's transaction policies
35
+ and confirmation screens don't apply to them.
36
+
37
+ `Wallet.Privy` is an EVM wallet, so `MsgBroadcaster` uses the same EIP-712 path as
38
+ `Wallet.Turnkey`, including fee delegation.
39
+
40
+ The Privy wallet only exists after sign-in, so pass it with `setMetadata`:
41
+
42
+ ```typescript
43
+ import { Wallet } from '@injectivelabs/wallet-base'
44
+ import { WalletStrategy } from '@injectivelabs/wallet-strategy'
45
+ import { MsgBroadcaster } from '@injectivelabs/wallet-core'
46
+ import { ChainId, EvmChainId } from '@injectivelabs/ts-types'
47
+ import { Network } from '@injectivelabs/networks'
48
+
49
+ const walletStrategy = new WalletStrategy({
50
+ chainId: ChainId.Testnet,
51
+ strategies: {}, // WalletStrategy loads the Privy strategy itself
52
+ evmOptions: { evmChainId: EvmChainId.TestnetEvm, rpcUrl: '<injective evm rpc>' },
53
+ })
54
+
55
+ // After the user signs in with Privy, e.g. privy.embeddedWallet.getEthereumProvider(...)
56
+ // from @privy-io/js-sdk-core.
57
+ await walletStrategy.setWallet(Wallet.Privy)
58
+ await walletStrategy.setMetadata({
59
+ privy: {
60
+ address: embeddedWalletAddress,
61
+ getProvider: () => getPrivyEthereumProvider(),
62
+ },
63
+ })
64
+
65
+ const broadcaster = new MsgBroadcaster({
66
+ walletStrategy,
67
+ network: Network.Testnet,
68
+ evmChainId: EvmChainId.TestnetEvm,
69
+ })
70
+
71
+ await broadcaster.broadcastWithFeeDelegation({ msgs, injectiveAddress })
72
+ ```
73
+
74
+ When the user switches accounts, call `setMetadata({ privy })` again; other wallets'
75
+ metadata never replaces it. `walletStrategy.disconnect()` forgets the wallet, but
76
+ sign the user out of Privy through the Privy SDK. The strategy reads the metadata on
77
+ every request and refuses to sign for any other address (0x or inj1).
78
+
79
+ Without Privy metadata (signed out, or after a page reload before the app has
80
+ restored the Privy session) every request throws `PrivyWalletSessionException`
81
+ from `@injectivelabs/exceptions`, the Privy counterpart of
82
+ `TurnkeyWalletSessionException`, so apps can treat both the same way: disconnect
83
+ and send the user back to sign-in. A `getProvider` that throws it is passed on
84
+ unchanged.
85
+
86
+ `getEip1193Provider()` returns the same provider as the Turnkey strategy: it signs
87
+ with the Privy wallet and sends through `evmOptions.rpcUrl` / `rpcUrls`, starting on
88
+ `evmOptions.evmChainId` and switching with `wallet_switchEthereumChain`. Privy's
89
+ `supportedChains` doesn't apply to it.
90
+
91
+ The strategy never creates a wallet. Create one with Privy only for users who never
92
+ had an embedded wallet; existing users import their key first (see Privy's Turnkey
93
+ migration guide).
94
+
95
+ ---
96
+
97
+ ## 📜 Contribution
98
+
99
+ **Contribution guides and practices will be available once there is a stable foundation of the whole package set within the `injective-ts` repo.**
100
+
101
+ ---
102
+
103
+ ## ⛑ Support
104
+
105
+ Reach out to us at one of the following places!
106
+
107
+ - Website at <a href="https://injective.com" target="_blank">`injective.com`</a>
108
+ - Twitter at <a href="https://twitter.com/Injective_" target="_blank">`@Injective`</a>
109
+ - Discord at <a href="https://discord.com/invite/NK4qdbv" target="_blank">`Discord`</a>
110
+ - Telegram at <a href="https://t.me/joininjective" target="_blank">`Telegram`</a>
111
+
112
+ ---
113
+
114
+ ## 🔓 License
115
+
116
+ Copyright © 2021 - 2022 Injective Labs Inc. (https://injectivelabs.org/)
117
+
118
+ <a href="https://iili.io/mNneZN.md.png"><img src="https://iili.io/mNneZN.md.png" style="width: 300px; max-width: 100%; height: auto" />
119
+
120
+ Originally released by Injective Labs Inc. under: <br />
121
+ Apache License <br />
122
+ Version 2.0, January 2004 <br />
123
+ http://www.apache.org/licenses/
124
+
125
+ <p>&nbsp;</p>
126
+ <div align="center">
127
+ <sub><em>Powering the future of decentralized finance.</em></sub>
128
+ </div>
@@ -0,0 +1,283 @@
1
+ let viem_accounts = require("viem/accounts");
2
+ let __injectivelabs_sdk_ts_utils = require("@injectivelabs/sdk-ts/utils");
3
+ let __injectivelabs_exceptions = require("@injectivelabs/exceptions");
4
+ let viem = require("viem");
5
+ let __injectivelabs_wallet_base = require("@injectivelabs/wallet-base");
6
+
7
+ //#region \0@oxc-project+runtime@0.99.0/helpers/typeof.js
8
+ function _typeof(o) {
9
+ "@babel/helpers - typeof";
10
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
11
+ return typeof o$1;
12
+ } : function(o$1) {
13
+ return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
14
+ }, _typeof(o);
15
+ }
16
+
17
+ //#endregion
18
+ //#region \0@oxc-project+runtime@0.99.0/helpers/toPrimitive.js
19
+ function toPrimitive(t, r) {
20
+ if ("object" != _typeof(t) || !t) return t;
21
+ var e = t[Symbol.toPrimitive];
22
+ if (void 0 !== e) {
23
+ var i = e.call(t, r || "default");
24
+ if ("object" != _typeof(i)) return i;
25
+ throw new TypeError("@@toPrimitive must return a primitive value.");
26
+ }
27
+ return ("string" === r ? String : Number)(t);
28
+ }
29
+
30
+ //#endregion
31
+ //#region \0@oxc-project+runtime@0.99.0/helpers/toPropertyKey.js
32
+ function toPropertyKey(t) {
33
+ var i = toPrimitive(t, "string");
34
+ return "symbol" == _typeof(i) ? i : i + "";
35
+ }
36
+
37
+ //#endregion
38
+ //#region \0@oxc-project+runtime@0.99.0/helpers/defineProperty.js
39
+ function _defineProperty(e, r, t) {
40
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
41
+ value: t,
42
+ enumerable: !0,
43
+ configurable: !0,
44
+ writable: !0
45
+ }) : e[r] = t, e;
46
+ }
47
+
48
+ //#endregion
49
+ //#region src/strategy/strategy.ts
50
+ const normalizeSignature = (result) => {
51
+ const raw = typeof result === "string" ? result : result && typeof result === "object" && "signature" in result ? String(result.signature) : "";
52
+ if (!/^(0x)?[0-9a-fA-F]+$/.test(raw)) throw new Error("Privy returned an invalid signature");
53
+ const bytes = (0, viem.hexToBytes)(raw.startsWith("0x") ? raw : `0x${raw}`);
54
+ if (bytes.length !== 65) throw new Error(`Expected a 65-byte signature, got ${bytes.length} bytes`);
55
+ if (bytes[64] < 27) bytes[64] += 27;
56
+ return (0, viem.bytesToHex)(bytes);
57
+ };
58
+ const toPersonalSignMessage = (message) => {
59
+ if (typeof message === "string") return (0, viem.stringToHex)(message);
60
+ return typeof message.raw === "string" ? message.raw : (0, viem.bytesToHex)(message.raw);
61
+ };
62
+ const getCauses = (e) => {
63
+ const causes = [];
64
+ for (let error = e; error && typeof error === "object";) {
65
+ if (causes.length === 5 || causes.includes(error)) break;
66
+ causes.push(error);
67
+ error = error.cause;
68
+ }
69
+ return causes;
70
+ };
71
+ /** Signs through the Privy embedded wallet provider passed in `metadata.privy`. */
72
+ var PrivyWalletStrategy = class extends __injectivelabs_wallet_base.BaseConcreteStrategy {
73
+ constructor(args) {
74
+ super(args);
75
+ _defineProperty(this, "evmOptions", void 0);
76
+ this.evmOptions = args.evmOptions;
77
+ }
78
+ async getWalletDeviceType() {
79
+ return Promise.resolve(__injectivelabs_wallet_base.WalletDeviceType.Browser);
80
+ }
81
+ setMetadata(metadata) {
82
+ if (metadata === null || metadata === void 0 ? void 0 : metadata.privy) this.metadata = {
83
+ ...this.metadata,
84
+ privy: metadata.privy
85
+ };
86
+ }
87
+ async enable() {
88
+ var _this$metadata;
89
+ return Promise.resolve(Boolean((_this$metadata = this.metadata) === null || _this$metadata === void 0 || (_this$metadata = _this$metadata.privy) === null || _this$metadata === void 0 ? void 0 : _this$metadata.address));
90
+ }
91
+ async disconnect() {
92
+ var _this$metadata2;
93
+ if ((_this$metadata2 = this.metadata) === null || _this$metadata2 === void 0 ? void 0 : _this$metadata2.privy) this.metadata = {
94
+ ...this.metadata,
95
+ privy: void 0
96
+ };
97
+ }
98
+ async getAddresses() {
99
+ try {
100
+ return [(0, viem.getAddress)(this.getPrivyMetadata(__injectivelabs_wallet_base.WalletAction.GetAccounts).address)];
101
+ } catch (e) {
102
+ throw this.toWalletException(e, __injectivelabs_wallet_base.WalletAction.GetAccounts);
103
+ }
104
+ }
105
+ async getAddressesInfo() {
106
+ throw this.toWalletException(/* @__PURE__ */ new Error("getAddressesInfo is not implemented"), __injectivelabs_wallet_base.WalletAction.GetAccounts);
107
+ }
108
+ async getSessionOrConfirm(address) {
109
+ return Promise.resolve(`0x${(0, __injectivelabs_sdk_ts_utils.uint8ArrayToHex)((0, __injectivelabs_sdk_ts_utils.stringToUint8Array)(`Confirmation for ${address} at time: ${Date.now()}`))}`);
110
+ }
111
+ async sendEvmTransaction(transaction, args) {
112
+ const action = __injectivelabs_wallet_base.WalletAction.SendEvmTransaction;
113
+ try {
114
+ const account = this.getCheckedAccount(args.address, action);
115
+ const chainId = args.evmChainId || this.evmOptions.evmChainId;
116
+ const client = (0, __injectivelabs_wallet_base.getViemWalletClient)({
117
+ chainId,
118
+ account,
119
+ rpcUrl: this.getRpcUrl(chainId)
120
+ });
121
+ return await client.sendTransaction({
122
+ ...(0, __injectivelabs_wallet_base.toViemTransactionRequest)(transaction, account.address, chainId),
123
+ account,
124
+ chain: client.chain
125
+ });
126
+ } catch (e) {
127
+ throw this.toWalletException(e, action);
128
+ }
129
+ }
130
+ async sendTransaction(transaction, options) {
131
+ return (0, __injectivelabs_wallet_base.broadcastTxRaw)(transaction, options);
132
+ }
133
+ async signEip712TypedData(eip712json, address) {
134
+ const action = __injectivelabs_wallet_base.WalletAction.SignTransaction;
135
+ try {
136
+ var _parsedData$domain;
137
+ const account = this.getCheckedAccount(address, action);
138
+ let parsedData;
139
+ try {
140
+ parsedData = JSON.parse(eip712json);
141
+ } catch (_unused) {
142
+ throw new Error("Failed to parse EIP-712 data: Invalid JSON format");
143
+ }
144
+ if (((_parsedData$domain = parsedData.domain) === null || _parsedData$domain === void 0 ? void 0 : _parsedData$domain.chainId) && typeof parsedData.domain.chainId === "string") parsedData.domain.chainId = Number(parsedData.domain.chainId);
145
+ return await account.signTypedData({
146
+ types: parsedData.types,
147
+ domain: parsedData.domain,
148
+ message: parsedData.message,
149
+ primaryType: parsedData.primaryType
150
+ });
151
+ } catch (e) {
152
+ throw this.toWalletException(e, action);
153
+ }
154
+ }
155
+ async signCosmosTransaction(_transaction) {
156
+ throw this.toWalletException(/* @__PURE__ */ new Error("This wallet does not support signing Cosmos transactions"), __injectivelabs_wallet_base.WalletAction.SignTransaction);
157
+ }
158
+ async signAminoCosmosTransaction(_transaction) {
159
+ throw this.toWalletException(/* @__PURE__ */ new Error("This wallet does not support signAminoCosmosTransaction"), __injectivelabs_wallet_base.WalletAction.SignTransaction);
160
+ }
161
+ async signArbitrary(signer, data) {
162
+ const action = __injectivelabs_wallet_base.WalletAction.SignArbitrary;
163
+ try {
164
+ return await this.getCheckedAccount(signer, action).signMessage({ message: typeof data === "string" && !(0, viem.isHex)(data) ? data : { raw: data } });
165
+ } catch (e) {
166
+ throw this.toWalletException(e, action);
167
+ }
168
+ }
169
+ async getEthereumChainId() {
170
+ return Promise.resolve((0, viem.toHex)(this.evmOptions.evmChainId));
171
+ }
172
+ async getEvmTransactionReceipt(txHash, evmChainId) {
173
+ const action = __injectivelabs_wallet_base.WalletAction.GetEvmTransactionReceipt;
174
+ const chainId = evmChainId || this.evmOptions.evmChainId;
175
+ let publicClient;
176
+ try {
177
+ publicClient = (0, __injectivelabs_wallet_base.getViemPublicClient)(chainId, this.getRpcUrl(chainId));
178
+ } catch (e) {
179
+ throw this.toWalletException(e, action);
180
+ }
181
+ try {
182
+ return await publicClient.waitForTransactionReceipt({
183
+ hash: txHash,
184
+ timeout: 3e4,
185
+ pollingInterval: 3e3
186
+ });
187
+ } catch (_unused2) {
188
+ throw this.toWalletException(/* @__PURE__ */ new Error(`Failed to retrieve transaction receipt for txHash: ${txHash}`), action);
189
+ }
190
+ }
191
+ async getPubKey() {
192
+ throw this.toWalletException(/* @__PURE__ */ new Error("You can only fetch PubKey from Cosmos native wallets"), __injectivelabs_wallet_base.WalletAction.GetAccounts);
193
+ }
194
+ async getEip1193Provider() {
195
+ try {
196
+ return await (0, __injectivelabs_wallet_base.getEip1193ProviderForAccount)(this.getAccount(__injectivelabs_wallet_base.WalletAction.GetAccounts), this.evmOptions.evmChainId, {
197
+ rpcUrl: this.evmOptions.rpcUrl,
198
+ rpcUrls: this.evmOptions.rpcUrls
199
+ });
200
+ } catch (e) {
201
+ throw this.toWalletException(e, __injectivelabs_wallet_base.WalletAction.GetAccounts);
202
+ }
203
+ }
204
+ getPrivyMetadata(action) {
205
+ var _this$metadata3;
206
+ const privy = (_this$metadata3 = this.metadata) === null || _this$metadata3 === void 0 ? void 0 : _this$metadata3.privy;
207
+ if (!(privy === null || privy === void 0 ? void 0 : privy.address)) throw new __injectivelabs_exceptions.PrivyWalletSessionException(/* @__PURE__ */ new Error("Privy metadata with an address is required"), {
208
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
209
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
210
+ contextModule: action
211
+ });
212
+ return privy;
213
+ }
214
+ /**
215
+ * The Privy wallet as a viem account. Hashes (transactions, EIP-712) are
216
+ * signed with secp256k1_sign, so Privy never sees the decoded transaction.
217
+ */
218
+ getAccount(action) {
219
+ const address = (0, viem.getAddress)(this.getPrivyMetadata(action).address);
220
+ const requireSameWallet = () => {
221
+ const privy = this.getPrivyMetadata(action);
222
+ if (!(0, viem.isAddressEqual)(privy.address, address)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`The Privy wallet is no longer ${address}`), {
223
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
224
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
225
+ contextModule: action
226
+ });
227
+ return privy;
228
+ };
229
+ const request = async (method, params) => {
230
+ const provider = await requireSameWallet().getProvider();
231
+ requireSameWallet();
232
+ const result = await provider.request({
233
+ method,
234
+ params
235
+ });
236
+ requireSameWallet();
237
+ return result;
238
+ };
239
+ const sign = async ({ hash }) => normalizeSignature(await request("secp256k1_sign", [hash]));
240
+ return (0, viem_accounts.toAccount)({
241
+ address,
242
+ sign,
243
+ signMessage: async ({ message }) => normalizeSignature(await request("personal_sign", [toPersonalSignMessage(message), address])),
244
+ signTypedData: async (typedData) => sign({ hash: (0, viem.hashTypedData)(typedData) }),
245
+ signTransaction: async (transaction, { serializer = viem.serializeTransaction } = {}) => {
246
+ return serializer(transaction, (0, viem.parseSignature)(await sign({ hash: (0, viem.keccak256)(await serializer(transaction.type === "eip4844" ? {
247
+ ...transaction,
248
+ sidecars: false
249
+ } : transaction)) })));
250
+ }
251
+ });
252
+ }
253
+ getCheckedAccount(address, action) {
254
+ const account = this.getAccount(action);
255
+ if ((0, viem.getAddress)((0, __injectivelabs_sdk_ts_utils.getEthereumAddress)(address)) !== account.address) throw new Error(`Address ${address} is not the connected Privy wallet`);
256
+ return account;
257
+ }
258
+ getRpcUrl(chainId) {
259
+ var _this$evmOptions$rpcU;
260
+ const url = ((_this$evmOptions$rpcU = this.evmOptions.rpcUrls) === null || _this$evmOptions$rpcU === void 0 ? void 0 : _this$evmOptions$rpcU[chainId]) || this.evmOptions.rpcUrl;
261
+ if (!url) throw new Error("Please pass rpcUrl within the evmOptions");
262
+ return url;
263
+ }
264
+ toWalletException(e, action) {
265
+ var _causes$at;
266
+ const causes = getCauses(e);
267
+ const thrown = causes.find((error) => (0, __injectivelabs_exceptions.isThrownException)(error));
268
+ if (thrown) return thrown;
269
+ const shortMessage = causes.map((error) => error.shortMessage).find((text$1) => typeof text$1 === "string" && text$1);
270
+ const { message } = (_causes$at = causes.at(-1)) !== null && _causes$at !== void 0 ? _causes$at : {};
271
+ const text = typeof shortMessage === "string" ? shortMessage : typeof message === "string" ? message : String(e);
272
+ const providerCode = causes.map((error) => error.code).reverse().find((code) => typeof code === "number");
273
+ return new __injectivelabs_exceptions.WalletException(new Error(text), {
274
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
275
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
276
+ contextModule: action,
277
+ ...providerCode !== void 0 ? { contextCode: providerCode } : {}
278
+ });
279
+ }
280
+ };
281
+
282
+ //#endregion
283
+ exports.PrivyWalletStrategy = PrivyWalletStrategy;
@@ -0,0 +1,55 @@
1
+ import { BaseConcreteStrategy, ConcreteEvmWalletStrategyArgs, ConcreteWalletStrategy, Eip1193Provider, PrivyMetadata, SendTransactionOptions, StdSignDoc, WalletDeviceType, WalletStrategyEvmOptions } from "@injectivelabs/wallet-base";
2
+ import { AccountAddress, EvmChainId } from "@injectivelabs/ts-types";
3
+ import { AminoSignResponse, DirectSignResponse, TxRaw } from "@injectivelabs/sdk-ts/types";
4
+
5
+ //#region src/strategy/strategy.d.ts
6
+ /** Signs through the Privy embedded wallet provider passed in `metadata.privy`. */
7
+ declare class PrivyWalletStrategy extends BaseConcreteStrategy implements ConcreteWalletStrategy {
8
+ evmOptions: WalletStrategyEvmOptions;
9
+ constructor(args: ConcreteEvmWalletStrategyArgs);
10
+ getWalletDeviceType(): Promise<WalletDeviceType>;
11
+ setMetadata(metadata?: {
12
+ privy?: PrivyMetadata;
13
+ }): void;
14
+ enable(): Promise<boolean>;
15
+ disconnect(): Promise<void>;
16
+ getAddresses(): Promise<string[]>;
17
+ getAddressesInfo(): Promise<{
18
+ address: string;
19
+ derivationPath: string;
20
+ baseDerivationPath: string;
21
+ }[]>;
22
+ getSessionOrConfirm(address: AccountAddress): Promise<string>;
23
+ sendEvmTransaction(transaction: unknown, args: {
24
+ address: AccountAddress;
25
+ evmChainId: EvmChainId;
26
+ }): Promise<string>;
27
+ sendTransaction(transaction: TxRaw, options: SendTransactionOptions): Promise<any>;
28
+ signEip712TypedData(eip712json: string, address: AccountAddress): Promise<string>;
29
+ signCosmosTransaction(_transaction: {
30
+ txRaw: TxRaw;
31
+ accountNumber: number;
32
+ chainId: string;
33
+ address: string;
34
+ }): Promise<DirectSignResponse>;
35
+ signAminoCosmosTransaction(_transaction: {
36
+ address: string;
37
+ signDoc: StdSignDoc;
38
+ }): Promise<AminoSignResponse>;
39
+ signArbitrary(signer: AccountAddress, data: string | Uint8Array): Promise<string>;
40
+ getEthereumChainId(): Promise<string>;
41
+ getEvmTransactionReceipt(txHash: string, evmChainId?: EvmChainId): Promise<Record<string, any>>;
42
+ getPubKey(): Promise<string>;
43
+ getEip1193Provider(): Promise<Eip1193Provider>;
44
+ private getPrivyMetadata;
45
+ /**
46
+ * The Privy wallet as a viem account. Hashes (transactions, EIP-712) are
47
+ * signed with secp256k1_sign, so Privy never sees the decoded transaction.
48
+ */
49
+ private getAccount;
50
+ private getCheckedAccount;
51
+ private getRpcUrl;
52
+ private toWalletException;
53
+ }
54
+ //#endregion
55
+ export { PrivyWalletStrategy };
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,55 @@
1
+ import { BaseConcreteStrategy, ConcreteEvmWalletStrategyArgs, ConcreteWalletStrategy, Eip1193Provider, PrivyMetadata, SendTransactionOptions, StdSignDoc, WalletDeviceType, WalletStrategyEvmOptions } from "@injectivelabs/wallet-base";
2
+ import { AccountAddress, EvmChainId } from "@injectivelabs/ts-types";
3
+ import { AminoSignResponse, DirectSignResponse, TxRaw } from "@injectivelabs/sdk-ts/types";
4
+
5
+ //#region src/strategy/strategy.d.ts
6
+ /** Signs through the Privy embedded wallet provider passed in `metadata.privy`. */
7
+ declare class PrivyWalletStrategy extends BaseConcreteStrategy implements ConcreteWalletStrategy {
8
+ evmOptions: WalletStrategyEvmOptions;
9
+ constructor(args: ConcreteEvmWalletStrategyArgs);
10
+ getWalletDeviceType(): Promise<WalletDeviceType>;
11
+ setMetadata(metadata?: {
12
+ privy?: PrivyMetadata;
13
+ }): void;
14
+ enable(): Promise<boolean>;
15
+ disconnect(): Promise<void>;
16
+ getAddresses(): Promise<string[]>;
17
+ getAddressesInfo(): Promise<{
18
+ address: string;
19
+ derivationPath: string;
20
+ baseDerivationPath: string;
21
+ }[]>;
22
+ getSessionOrConfirm(address: AccountAddress): Promise<string>;
23
+ sendEvmTransaction(transaction: unknown, args: {
24
+ address: AccountAddress;
25
+ evmChainId: EvmChainId;
26
+ }): Promise<string>;
27
+ sendTransaction(transaction: TxRaw, options: SendTransactionOptions): Promise<any>;
28
+ signEip712TypedData(eip712json: string, address: AccountAddress): Promise<string>;
29
+ signCosmosTransaction(_transaction: {
30
+ txRaw: TxRaw;
31
+ accountNumber: number;
32
+ chainId: string;
33
+ address: string;
34
+ }): Promise<DirectSignResponse>;
35
+ signAminoCosmosTransaction(_transaction: {
36
+ address: string;
37
+ signDoc: StdSignDoc;
38
+ }): Promise<AminoSignResponse>;
39
+ signArbitrary(signer: AccountAddress, data: string | Uint8Array): Promise<string>;
40
+ getEthereumChainId(): Promise<string>;
41
+ getEvmTransactionReceipt(txHash: string, evmChainId?: EvmChainId): Promise<Record<string, any>>;
42
+ getPubKey(): Promise<string>;
43
+ getEip1193Provider(): Promise<Eip1193Provider>;
44
+ private getPrivyMetadata;
45
+ /**
46
+ * The Privy wallet as a viem account. Hashes (transactions, EIP-712) are
47
+ * signed with secp256k1_sign, so Privy never sees the decoded transaction.
48
+ */
49
+ private getAccount;
50
+ private getCheckedAccount;
51
+ private getRpcUrl;
52
+ private toWalletException;
53
+ }
54
+ //#endregion
55
+ export { PrivyWalletStrategy };
@@ -0,0 +1,283 @@
1
+ import { toAccount } from "viem/accounts";
2
+ import { getEthereumAddress, stringToUint8Array, uint8ArrayToHex } from "@injectivelabs/sdk-ts/utils";
3
+ import { ErrorType, PrivyWalletSessionException, UnspecifiedErrorCode, WalletException, isThrownException } from "@injectivelabs/exceptions";
4
+ import { bytesToHex, getAddress, hashTypedData, hexToBytes, isAddressEqual, isHex, keccak256, parseSignature, serializeTransaction, stringToHex, toHex } from "viem";
5
+ import { BaseConcreteStrategy, WalletAction, WalletDeviceType, broadcastTxRaw, getEip1193ProviderForAccount, getViemPublicClient, getViemWalletClient, toViemTransactionRequest } from "@injectivelabs/wallet-base";
6
+
7
+ //#region \0@oxc-project+runtime@0.99.0/helpers/typeof.js
8
+ function _typeof(o) {
9
+ "@babel/helpers - typeof";
10
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
11
+ return typeof o$1;
12
+ } : function(o$1) {
13
+ return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
14
+ }, _typeof(o);
15
+ }
16
+
17
+ //#endregion
18
+ //#region \0@oxc-project+runtime@0.99.0/helpers/toPrimitive.js
19
+ function toPrimitive(t, r) {
20
+ if ("object" != _typeof(t) || !t) return t;
21
+ var e = t[Symbol.toPrimitive];
22
+ if (void 0 !== e) {
23
+ var i = e.call(t, r || "default");
24
+ if ("object" != _typeof(i)) return i;
25
+ throw new TypeError("@@toPrimitive must return a primitive value.");
26
+ }
27
+ return ("string" === r ? String : Number)(t);
28
+ }
29
+
30
+ //#endregion
31
+ //#region \0@oxc-project+runtime@0.99.0/helpers/toPropertyKey.js
32
+ function toPropertyKey(t) {
33
+ var i = toPrimitive(t, "string");
34
+ return "symbol" == _typeof(i) ? i : i + "";
35
+ }
36
+
37
+ //#endregion
38
+ //#region \0@oxc-project+runtime@0.99.0/helpers/defineProperty.js
39
+ function _defineProperty(e, r, t) {
40
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
41
+ value: t,
42
+ enumerable: !0,
43
+ configurable: !0,
44
+ writable: !0
45
+ }) : e[r] = t, e;
46
+ }
47
+
48
+ //#endregion
49
+ //#region src/strategy/strategy.ts
50
+ const normalizeSignature = (result) => {
51
+ const raw = typeof result === "string" ? result : result && typeof result === "object" && "signature" in result ? String(result.signature) : "";
52
+ if (!/^(0x)?[0-9a-fA-F]+$/.test(raw)) throw new Error("Privy returned an invalid signature");
53
+ const bytes = hexToBytes(raw.startsWith("0x") ? raw : `0x${raw}`);
54
+ if (bytes.length !== 65) throw new Error(`Expected a 65-byte signature, got ${bytes.length} bytes`);
55
+ if (bytes[64] < 27) bytes[64] += 27;
56
+ return bytesToHex(bytes);
57
+ };
58
+ const toPersonalSignMessage = (message) => {
59
+ if (typeof message === "string") return stringToHex(message);
60
+ return typeof message.raw === "string" ? message.raw : bytesToHex(message.raw);
61
+ };
62
+ const getCauses = (e) => {
63
+ const causes = [];
64
+ for (let error = e; error && typeof error === "object";) {
65
+ if (causes.length === 5 || causes.includes(error)) break;
66
+ causes.push(error);
67
+ error = error.cause;
68
+ }
69
+ return causes;
70
+ };
71
+ /** Signs through the Privy embedded wallet provider passed in `metadata.privy`. */
72
+ var PrivyWalletStrategy = class extends BaseConcreteStrategy {
73
+ constructor(args) {
74
+ super(args);
75
+ _defineProperty(this, "evmOptions", void 0);
76
+ this.evmOptions = args.evmOptions;
77
+ }
78
+ async getWalletDeviceType() {
79
+ return Promise.resolve(WalletDeviceType.Browser);
80
+ }
81
+ setMetadata(metadata) {
82
+ if (metadata === null || metadata === void 0 ? void 0 : metadata.privy) this.metadata = {
83
+ ...this.metadata,
84
+ privy: metadata.privy
85
+ };
86
+ }
87
+ async enable() {
88
+ var _this$metadata;
89
+ return Promise.resolve(Boolean((_this$metadata = this.metadata) === null || _this$metadata === void 0 || (_this$metadata = _this$metadata.privy) === null || _this$metadata === void 0 ? void 0 : _this$metadata.address));
90
+ }
91
+ async disconnect() {
92
+ var _this$metadata2;
93
+ if ((_this$metadata2 = this.metadata) === null || _this$metadata2 === void 0 ? void 0 : _this$metadata2.privy) this.metadata = {
94
+ ...this.metadata,
95
+ privy: void 0
96
+ };
97
+ }
98
+ async getAddresses() {
99
+ try {
100
+ return [getAddress(this.getPrivyMetadata(WalletAction.GetAccounts).address)];
101
+ } catch (e) {
102
+ throw this.toWalletException(e, WalletAction.GetAccounts);
103
+ }
104
+ }
105
+ async getAddressesInfo() {
106
+ throw this.toWalletException(/* @__PURE__ */ new Error("getAddressesInfo is not implemented"), WalletAction.GetAccounts);
107
+ }
108
+ async getSessionOrConfirm(address) {
109
+ return Promise.resolve(`0x${uint8ArrayToHex(stringToUint8Array(`Confirmation for ${address} at time: ${Date.now()}`))}`);
110
+ }
111
+ async sendEvmTransaction(transaction, args) {
112
+ const action = WalletAction.SendEvmTransaction;
113
+ try {
114
+ const account = this.getCheckedAccount(args.address, action);
115
+ const chainId = args.evmChainId || this.evmOptions.evmChainId;
116
+ const client = getViemWalletClient({
117
+ chainId,
118
+ account,
119
+ rpcUrl: this.getRpcUrl(chainId)
120
+ });
121
+ return await client.sendTransaction({
122
+ ...toViemTransactionRequest(transaction, account.address, chainId),
123
+ account,
124
+ chain: client.chain
125
+ });
126
+ } catch (e) {
127
+ throw this.toWalletException(e, action);
128
+ }
129
+ }
130
+ async sendTransaction(transaction, options) {
131
+ return broadcastTxRaw(transaction, options);
132
+ }
133
+ async signEip712TypedData(eip712json, address) {
134
+ const action = WalletAction.SignTransaction;
135
+ try {
136
+ var _parsedData$domain;
137
+ const account = this.getCheckedAccount(address, action);
138
+ let parsedData;
139
+ try {
140
+ parsedData = JSON.parse(eip712json);
141
+ } catch (_unused) {
142
+ throw new Error("Failed to parse EIP-712 data: Invalid JSON format");
143
+ }
144
+ if (((_parsedData$domain = parsedData.domain) === null || _parsedData$domain === void 0 ? void 0 : _parsedData$domain.chainId) && typeof parsedData.domain.chainId === "string") parsedData.domain.chainId = Number(parsedData.domain.chainId);
145
+ return await account.signTypedData({
146
+ types: parsedData.types,
147
+ domain: parsedData.domain,
148
+ message: parsedData.message,
149
+ primaryType: parsedData.primaryType
150
+ });
151
+ } catch (e) {
152
+ throw this.toWalletException(e, action);
153
+ }
154
+ }
155
+ async signCosmosTransaction(_transaction) {
156
+ throw this.toWalletException(/* @__PURE__ */ new Error("This wallet does not support signing Cosmos transactions"), WalletAction.SignTransaction);
157
+ }
158
+ async signAminoCosmosTransaction(_transaction) {
159
+ throw this.toWalletException(/* @__PURE__ */ new Error("This wallet does not support signAminoCosmosTransaction"), WalletAction.SignTransaction);
160
+ }
161
+ async signArbitrary(signer, data) {
162
+ const action = WalletAction.SignArbitrary;
163
+ try {
164
+ return await this.getCheckedAccount(signer, action).signMessage({ message: typeof data === "string" && !isHex(data) ? data : { raw: data } });
165
+ } catch (e) {
166
+ throw this.toWalletException(e, action);
167
+ }
168
+ }
169
+ async getEthereumChainId() {
170
+ return Promise.resolve(toHex(this.evmOptions.evmChainId));
171
+ }
172
+ async getEvmTransactionReceipt(txHash, evmChainId) {
173
+ const action = WalletAction.GetEvmTransactionReceipt;
174
+ const chainId = evmChainId || this.evmOptions.evmChainId;
175
+ let publicClient;
176
+ try {
177
+ publicClient = getViemPublicClient(chainId, this.getRpcUrl(chainId));
178
+ } catch (e) {
179
+ throw this.toWalletException(e, action);
180
+ }
181
+ try {
182
+ return await publicClient.waitForTransactionReceipt({
183
+ hash: txHash,
184
+ timeout: 3e4,
185
+ pollingInterval: 3e3
186
+ });
187
+ } catch (_unused2) {
188
+ throw this.toWalletException(/* @__PURE__ */ new Error(`Failed to retrieve transaction receipt for txHash: ${txHash}`), action);
189
+ }
190
+ }
191
+ async getPubKey() {
192
+ throw this.toWalletException(/* @__PURE__ */ new Error("You can only fetch PubKey from Cosmos native wallets"), WalletAction.GetAccounts);
193
+ }
194
+ async getEip1193Provider() {
195
+ try {
196
+ return await getEip1193ProviderForAccount(this.getAccount(WalletAction.GetAccounts), this.evmOptions.evmChainId, {
197
+ rpcUrl: this.evmOptions.rpcUrl,
198
+ rpcUrls: this.evmOptions.rpcUrls
199
+ });
200
+ } catch (e) {
201
+ throw this.toWalletException(e, WalletAction.GetAccounts);
202
+ }
203
+ }
204
+ getPrivyMetadata(action) {
205
+ var _this$metadata3;
206
+ const privy = (_this$metadata3 = this.metadata) === null || _this$metadata3 === void 0 ? void 0 : _this$metadata3.privy;
207
+ if (!(privy === null || privy === void 0 ? void 0 : privy.address)) throw new PrivyWalletSessionException(/* @__PURE__ */ new Error("Privy metadata with an address is required"), {
208
+ code: UnspecifiedErrorCode,
209
+ type: ErrorType.WalletError,
210
+ contextModule: action
211
+ });
212
+ return privy;
213
+ }
214
+ /**
215
+ * The Privy wallet as a viem account. Hashes (transactions, EIP-712) are
216
+ * signed with secp256k1_sign, so Privy never sees the decoded transaction.
217
+ */
218
+ getAccount(action) {
219
+ const address = getAddress(this.getPrivyMetadata(action).address);
220
+ const requireSameWallet = () => {
221
+ const privy = this.getPrivyMetadata(action);
222
+ if (!isAddressEqual(privy.address, address)) throw new WalletException(/* @__PURE__ */ new Error(`The Privy wallet is no longer ${address}`), {
223
+ code: UnspecifiedErrorCode,
224
+ type: ErrorType.WalletError,
225
+ contextModule: action
226
+ });
227
+ return privy;
228
+ };
229
+ const request = async (method, params) => {
230
+ const provider = await requireSameWallet().getProvider();
231
+ requireSameWallet();
232
+ const result = await provider.request({
233
+ method,
234
+ params
235
+ });
236
+ requireSameWallet();
237
+ return result;
238
+ };
239
+ const sign = async ({ hash }) => normalizeSignature(await request("secp256k1_sign", [hash]));
240
+ return toAccount({
241
+ address,
242
+ sign,
243
+ signMessage: async ({ message }) => normalizeSignature(await request("personal_sign", [toPersonalSignMessage(message), address])),
244
+ signTypedData: async (typedData) => sign({ hash: hashTypedData(typedData) }),
245
+ signTransaction: async (transaction, { serializer = serializeTransaction } = {}) => {
246
+ return serializer(transaction, parseSignature(await sign({ hash: keccak256(await serializer(transaction.type === "eip4844" ? {
247
+ ...transaction,
248
+ sidecars: false
249
+ } : transaction)) })));
250
+ }
251
+ });
252
+ }
253
+ getCheckedAccount(address, action) {
254
+ const account = this.getAccount(action);
255
+ if (getAddress(getEthereumAddress(address)) !== account.address) throw new Error(`Address ${address} is not the connected Privy wallet`);
256
+ return account;
257
+ }
258
+ getRpcUrl(chainId) {
259
+ var _this$evmOptions$rpcU;
260
+ const url = ((_this$evmOptions$rpcU = this.evmOptions.rpcUrls) === null || _this$evmOptions$rpcU === void 0 ? void 0 : _this$evmOptions$rpcU[chainId]) || this.evmOptions.rpcUrl;
261
+ if (!url) throw new Error("Please pass rpcUrl within the evmOptions");
262
+ return url;
263
+ }
264
+ toWalletException(e, action) {
265
+ var _causes$at;
266
+ const causes = getCauses(e);
267
+ const thrown = causes.find((error) => isThrownException(error));
268
+ if (thrown) return thrown;
269
+ const shortMessage = causes.map((error) => error.shortMessage).find((text$1) => typeof text$1 === "string" && text$1);
270
+ const { message } = (_causes$at = causes.at(-1)) !== null && _causes$at !== void 0 ? _causes$at : {};
271
+ const text = typeof shortMessage === "string" ? shortMessage : typeof message === "string" ? message : String(e);
272
+ const providerCode = causes.map((error) => error.code).reverse().find((code) => typeof code === "number");
273
+ return new WalletException(new Error(text), {
274
+ code: UnspecifiedErrorCode,
275
+ type: ErrorType.WalletError,
276
+ contextModule: action,
277
+ ...providerCode !== void 0 ? { contextCode: providerCode } : {}
278
+ });
279
+ }
280
+ };
281
+
282
+ //#endregion
283
+ export { PrivyWalletStrategy };
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@injectivelabs/wallet-privy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.20.65",
4
+ "description": "Privy embedded wallet strategy for use with @injectivelabs/wallet-core.",
5
+ "license": "Apache-2.0",
6
+ "author": {
7
+ "name": "InjectiveLabs",
8
+ "email": "admin@injectivelabs.org"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/InjectiveLabs/injective-ts"
13
+ },
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "exports": {
17
+ ".": {
18
+ "react-native": {
19
+ "import": "./dist/esm/index.js",
20
+ "require": "./dist/cjs/index.cjs",
21
+ "types": "./dist/cjs/index.d.cts",
22
+ "default": "./dist/cjs/index.cjs"
23
+ },
24
+ "require": {
25
+ "types": "./dist/cjs/index.d.cts",
26
+ "default": "./dist/cjs/index.cjs"
27
+ },
28
+ "import": {
29
+ "types": "./dist/esm/index.d.ts",
30
+ "default": "./dist/esm/index.js"
31
+ },
32
+ "default": {
33
+ "types": "./dist/cjs/index.d.cts",
34
+ "default": "./dist/cjs/index.cjs"
35
+ }
36
+ }
37
+ },
38
+ "main": "dist/cjs/index.cjs",
39
+ "module": "dist/esm/index.js",
40
+ "types": "dist/cjs/index.d.cts",
41
+ "files": [
42
+ "dist"
43
+ ],
44
+ "dependencies": {
45
+ "viem": "^2.54.6",
46
+ "@injectivelabs/sdk-ts": "1.20.66",
47
+ "@injectivelabs/exceptions": "1.20.66",
48
+ "@injectivelabs/wallet-base": "1.20.66",
49
+ "@injectivelabs/ts-types": "1.20.66"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "_moduleAliases": {
55
+ "~wallet-privy": "dist"
56
+ },
57
+ "scripts": {
58
+ "build": "pnpm type-check && tsdown",
59
+ "build:fast": "tsdown",
60
+ "build:watch": "tsdown --watch",
61
+ "clean": "shx rm -rf dist coverage *.log junit.xml && shx mkdir -p dist",
62
+ "type-check": "tsc --noEmit",
63
+ "test": "vitest",
64
+ "test:watch": "vitest --watch",
65
+ "test:ci": "vitest run --coverage --reporter=verbose",
66
+ "coverage": "vitest run --coverage",
67
+ "coverage:show": "live-server coverage",
68
+ "lint": "eslint . --ext .ts,.js"
69
+ }
6
70
  }