@pooflabs/web 0.0.73 → 0.0.75

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.
Files changed (65) hide show
  1. package/dist/auth/index.d.ts +4 -5
  2. package/dist/auth/providers/mock-auth-provider.d.ts +3 -3
  3. package/dist/auth/providers/privy-expo-provider.d.ts +105 -0
  4. package/dist/{index-BFJJZKXQ.js → index-BHYrnHi6.js} +357 -7
  5. package/dist/index-BHYrnHi6.js.map +1 -0
  6. package/dist/index-BcDe_euX.js +15928 -0
  7. package/dist/index-BcDe_euX.js.map +1 -0
  8. package/dist/index-Bdcc5821.js +2375 -0
  9. package/dist/index-Bdcc5821.js.map +1 -0
  10. package/dist/{index-TfCOBCez.esm.js → index-BqDvUK9s.esm.js} +352 -2
  11. package/dist/index-BqDvUK9s.esm.js.map +1 -0
  12. package/dist/index-CMeewi-G.js +21553 -0
  13. package/dist/index-CMeewi-G.js.map +1 -0
  14. package/dist/index-CrOVJFX9.esm.js +2373 -0
  15. package/dist/index-CrOVJFX9.esm.js.map +1 -0
  16. package/dist/index-Dho2J3X6.esm.js +21477 -0
  17. package/dist/index-Dho2J3X6.esm.js.map +1 -0
  18. package/dist/index-_vhjpl1l.esm.js +15887 -0
  19. package/dist/index-_vhjpl1l.esm.js.map +1 -0
  20. package/dist/{index.browser-ChrwVq76.esm.js → index.browser-Br0p4bjw.esm.js} +2 -3
  21. package/dist/{index.browser-ChrwVq76.esm.js.map → index.browser-Br0p4bjw.esm.js.map} +1 -1
  22. package/dist/{index.browser-BuIgwfvv.esm.js → index.browser-Btm3sRKb.esm.js} +2 -3
  23. package/dist/{index.browser-BuIgwfvv.esm.js.map → index.browser-Btm3sRKb.esm.js.map} +1 -1
  24. package/dist/{index.browser-wsb8xknL.js → index.browser-BzHjnrpD.js} +2 -3
  25. package/dist/{index.browser-wsb8xknL.js.map → index.browser-BzHjnrpD.js.map} +1 -1
  26. package/dist/index.browser-CGfjPfzM.esm.js +1468 -0
  27. package/dist/index.browser-CGfjPfzM.esm.js.map +1 -0
  28. package/dist/{index.browser-BO1XxDi0.js → index.browser-Dapjfbl6.js} +2 -3
  29. package/dist/{index.browser-BO1XxDi0.js.map → index.browser-Dapjfbl6.js.map} +1 -1
  30. package/dist/index.browser-JX3F6oPV.js +1471 -0
  31. package/dist/index.browser-JX3F6oPV.js.map +1 -0
  32. package/dist/index.d.ts +4 -0
  33. package/dist/index.esm.js +1 -2
  34. package/dist/index.esm.js.map +1 -1
  35. package/dist/index.js +6 -2
  36. package/dist/index.js.map +1 -1
  37. package/dist/index.native-BB7er4-z.esm.js +13269 -0
  38. package/dist/index.native-BB7er4-z.esm.js.map +1 -0
  39. package/dist/index.native-DcKDTqvq.js +13348 -0
  40. package/dist/index.native-DcKDTqvq.js.map +1 -0
  41. package/dist/index.native.d.ts +24 -0
  42. package/dist/index.native.esm.js +6 -0
  43. package/dist/index.native.esm.js.map +1 -0
  44. package/dist/index.native.js +59 -0
  45. package/dist/index.native.js.map +1 -0
  46. package/dist/phantom-wallet-provider-DHok8ui3.esm.js +1307 -0
  47. package/dist/phantom-wallet-provider-DHok8ui3.esm.js.map +1 -0
  48. package/dist/phantom-wallet-provider-DMxFAUC4.js +1328 -0
  49. package/dist/phantom-wallet-provider-DMxFAUC4.js.map +1 -0
  50. package/dist/platform.d.ts +81 -0
  51. package/dist/privy-wallet-provider-Bhvw0t1d.js +3942 -0
  52. package/dist/privy-wallet-provider-Bhvw0t1d.js.map +1 -0
  53. package/dist/privy-wallet-provider-CFuoQYuv.esm.js +3921 -0
  54. package/dist/privy-wallet-provider-CFuoQYuv.esm.js.map +1 -0
  55. package/dist/solana-mobile-wallet-provider-BpQghAgC.esm.js +558 -0
  56. package/dist/solana-mobile-wallet-provider-BpQghAgC.esm.js.map +1 -0
  57. package/dist/solana-mobile-wallet-provider-D8b5y-By.js +579 -0
  58. package/dist/solana-mobile-wallet-provider-D8b5y-By.js.map +1 -0
  59. package/package.json +19 -3
  60. package/dist/index-BFJJZKXQ.js.map +0 -1
  61. package/dist/index-BV8MOXXy.js +0 -36033
  62. package/dist/index-BV8MOXXy.js.map +0 -1
  63. package/dist/index-D0yz-P8G.esm.js +0 -35962
  64. package/dist/index-D0yz-P8G.esm.js.map +0 -1
  65. package/dist/index-TfCOBCez.esm.js.map +0 -1
@@ -0,0 +1,3921 @@
1
+ import { S as SOLANA_MAINNET_RPC_URL, a as SOLANA_DEVNET_RPC_URL, W as WebSessionManager, c as convertRemainingAccounts, b as buildSetDocumentsTransaction, d as bs58, e as confirmAndCheckTransaction, s as setCurrentUser, g as getPlatform, f as createSessionWithPrivy } from './index.native-BB7er4-z.esm.js';
2
+ import { Connection, VersionedTransaction, PublicKey, Transaction } from '@solana/web3.js';
3
+ import * as anchor from '@coral-xyz/anchor';
4
+ import 'axios';
5
+ import 'react';
6
+
7
+ // src/codes.ts
8
+ var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;
9
+ var SOLANA_ERROR__INVALID_NONCE = 2;
10
+ var SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;
11
+ var SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;
12
+ var SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;
13
+ var SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;
14
+ var SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;
15
+ var SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;
16
+ var SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;
17
+ var SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;
18
+ var SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;
19
+ var SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;
20
+ var SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;
21
+ var SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;
22
+ var SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;
23
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;
24
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;
25
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;
26
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;
27
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;
28
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;
29
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;
30
+ var SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;
31
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;
32
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;
33
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;
34
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;
35
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;
36
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;
37
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;
38
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;
39
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;
40
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;
41
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;
42
+ var SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 28e5;
43
+ var SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;
44
+ var SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;
45
+ var SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;
46
+ var SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;
47
+ var SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;
48
+ var SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;
49
+ var SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;
50
+ var SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;
51
+ var SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;
52
+ var SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;
53
+ var SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;
54
+ var SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 323e4;
55
+ var SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;
56
+ var SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;
57
+ var SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;
58
+ var SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;
59
+ var SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 361e4;
60
+ var SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;
61
+ var SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;
62
+ var SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;
63
+ var SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;
64
+ var SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;
65
+ var SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;
66
+ var SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;
67
+ var SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611e3;
68
+ var SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704e3;
69
+ var SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;
70
+ var SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;
71
+ var SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;
72
+ var SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;
73
+ var SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128e3;
74
+ var SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;
75
+ var SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;
76
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615e3;
77
+ var SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;
78
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;
79
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;
80
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;
81
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;
82
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;
83
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;
84
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;
85
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;
86
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;
87
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;
88
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;
89
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;
90
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;
91
+ var SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;
92
+ var SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;
93
+ var SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;
94
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;
95
+ var SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;
96
+ var SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;
97
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;
98
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;
99
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;
100
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;
101
+ var SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;
102
+ var SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;
103
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;
104
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;
105
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;
106
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;
107
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;
108
+ var SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;
109
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;
110
+ var SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;
111
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;
112
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;
113
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;
114
+ var SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;
115
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;
116
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;
117
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;
118
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;
119
+ var SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;
120
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;
121
+ var SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;
122
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;
123
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;
124
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;
125
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;
126
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;
127
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;
128
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;
129
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;
130
+ var SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;
131
+ var SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508e3;
132
+ var SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;
133
+ var SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;
134
+ var SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;
135
+ var SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;
136
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;
137
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;
138
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;
139
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;
140
+ var SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;
141
+ var SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;
142
+ var SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;
143
+ var SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663e3;
144
+ var SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;
145
+ var SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;
146
+ var SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;
147
+ var SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;
148
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;
149
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;
150
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;
151
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;
152
+ var SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;
153
+ var SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;
154
+ var SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;
155
+ var SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;
156
+ var SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;
157
+ var SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;
158
+ var SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;
159
+ var SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;
160
+ var SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;
161
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;
162
+ var SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;
163
+ var SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;
164
+ var SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;
165
+ var SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;
166
+ var SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 705e4;
167
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;
168
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;
169
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;
170
+ var SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;
171
+ var SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;
172
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;
173
+ var SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;
174
+ var SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;
175
+ var SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;
176
+ var SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;
177
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;
178
+ var SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;
179
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;
180
+ var SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;
181
+ var SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;
182
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;
183
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;
184
+ var SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;
185
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;
186
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;
187
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;
188
+ var SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;
189
+ var SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;
190
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;
191
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;
192
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;
193
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;
194
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;
195
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;
196
+ var SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;
197
+ var SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;
198
+ var SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;
199
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;
200
+ var SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;
201
+ var SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;
202
+ var SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;
203
+ var SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618e3;
204
+ var SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;
205
+ var SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;
206
+ var SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;
207
+ var SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078e3;
208
+ var SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;
209
+ var SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;
210
+ var SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;
211
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;
212
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;
213
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;
214
+ var SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;
215
+ var SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;
216
+ var SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;
217
+ var SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;
218
+ var SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;
219
+ var SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;
220
+ var SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;
221
+ var SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;
222
+ var SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;
223
+ var SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;
224
+ var SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;
225
+ var SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;
226
+ var SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;
227
+ var SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;
228
+ var SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;
229
+ var SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;
230
+ var SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;
231
+ var SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 81e5;
232
+ var SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;
233
+ var SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;
234
+ var SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;
235
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 819e4;
236
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;
237
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;
238
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;
239
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;
240
+ var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 99e5;
241
+ var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;
242
+ var SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;
243
+ var SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;
244
+ var SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;
245
+ var SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;
246
+ var SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;
247
+
248
+ // src/context.ts
249
+ function encodeValue(value) {
250
+ if (Array.isArray(value)) {
251
+ const commaSeparatedValues = value.map(encodeValue).join(
252
+ "%2C%20"
253
+ /* ", " */
254
+ );
255
+ return "%5B" + commaSeparatedValues + /* "]" */
256
+ "%5D";
257
+ } else if (typeof value === "bigint") {
258
+ return `${value}n`;
259
+ } else {
260
+ return encodeURIComponent(
261
+ String(
262
+ value != null && Object.getPrototypeOf(value) === null ? (
263
+ // Plain objects with no prototype don't have a `toString` method.
264
+ // Convert them before stringifying them.
265
+ { ...value }
266
+ ) : value
267
+ )
268
+ );
269
+ }
270
+ }
271
+ function encodeObjectContextEntry([key, value]) {
272
+ return `${key}=${encodeValue(value)}`;
273
+ }
274
+ function encodeContextObject(context) {
275
+ const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join("&");
276
+ return btoa(searchParamsString);
277
+ }
278
+
279
+ // src/messages.ts
280
+ var SolanaErrorMessages = {
281
+ [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: "Account not found at address: $address",
282
+ [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: "Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",
283
+ [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: "Expected decoded account at address: $address",
284
+ [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: "Failed to decode account data at address: $address",
285
+ [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: "Accounts not found at addresses: $addresses",
286
+ [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]: "Unable to find a viable program address bump seed.",
287
+ [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: "$putativeAddress is not a base58-encoded address.",
288
+ [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: "Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",
289
+ [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: "The `CryptoKey` must be an `Ed25519` public key.",
290
+ [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]: "$putativeOffCurveAddress is not a base58-encoded off-curve address.",
291
+ [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: "Invalid seeds; point must fall off the Ed25519 curve.",
292
+ [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]: "Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",
293
+ [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: "A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",
294
+ [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: "The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",
295
+ [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: "Expected program derived address bump to be in the range [0, 255], got: $bump.",
296
+ [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: "Program address cannot end with PDA marker.",
297
+ [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",
298
+ [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",
299
+ [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: "The network has progressed past the last block for which this transaction could have been committed.",
300
+ [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: "Codec [$codecDescription] cannot decode empty byte arrays.",
301
+ [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: "Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",
302
+ [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: "Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",
303
+ [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: "Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",
304
+ [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: "Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",
305
+ [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]: "Encoder and decoder must either both be fixed-size or variable-size.",
306
+ [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: "Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",
307
+ [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: "Expected a fixed-size codec, got a variable-size one.",
308
+ [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: "Codec [$codecDescription] expected a positive byte length, got $bytesLength.",
309
+ [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: "Expected a variable-size codec, got a fixed-size one.",
310
+ [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: "Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",
311
+ [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: "Codec [$codecDescription] expected $expected bytes, got $bytesLength.",
312
+ [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: "Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",
313
+ [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: "Invalid discriminated union variant. Expected one of [$variants], got $value.",
314
+ [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: "Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",
315
+ [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: "Invalid literal union variant. Expected one of [$variants], got $value.",
316
+ [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: "Expected [$codecDescription] to have $expected items, got $actual.",
317
+ [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: "Invalid value $value for base $base with alphabet $alphabet.",
318
+ [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: "Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",
319
+ [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: "Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",
320
+ [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: "Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",
321
+ [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: "Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",
322
+ [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: "Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",
323
+ [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: "This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",
324
+ [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: "No random values implementation could be found.",
325
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: "instruction requires an uninitialized account",
326
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]: "instruction tries to borrow reference for an account which is already borrowed",
327
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: "instruction left account with an outstanding borrowed reference",
328
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]: "program other than the account's owner changed the size of the account data",
329
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: "account data too small for instruction",
330
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: "instruction expected an executable account",
331
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]: "An account does not have enough lamports to be rent-exempt",
332
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: "Program arithmetic overflowed",
333
+ [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: "Failed to serialize or deserialize account data: $encodedData",
334
+ [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]: "Builtin programs must consume compute units",
335
+ [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: "Cross-program invocation call depth too deep",
336
+ [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: "Computational budget exceeded",
337
+ [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: "custom program error: #$code",
338
+ [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: "instruction contains duplicate accounts",
339
+ [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]: "instruction modifications of multiply-passed account differ",
340
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: "executable accounts must be rent exempt",
341
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: "instruction changed executable accounts data",
342
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]: "instruction changed the balance of an executable account",
343
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: "instruction changed executable bit of an account",
344
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]: "instruction modified data of an account it does not own",
345
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]: "instruction spent from the balance of an account it does not own",
346
+ [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: "generic instruction error",
347
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: "Provided owner is not allowed",
348
+ [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: "Account is immutable",
349
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: "Incorrect authority provided",
350
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: "incorrect program id for instruction",
351
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: "insufficient funds for instruction",
352
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: "invalid account data for instruction",
353
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: "Invalid account owner",
354
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: "invalid program argument",
355
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: "program returned invalid error code",
356
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: "invalid instruction data",
357
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: "Failed to reallocate account data",
358
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: "Provided seeds do not result in a valid address",
359
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]: "Accounts data allocations exceeded the maximum allowed per transaction",
360
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: "Max accounts exceeded",
361
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: "Max instruction trace length exceeded",
362
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]: "Length of the seed is too long for address generation",
363
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: "An account required by the instruction is missing",
364
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: "missing required signature for instruction",
365
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]: "instruction illegally modified the program id of an account",
366
+ [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: "insufficient account keys for instruction",
367
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]: "Cross-program invocation with unauthorized signer or writable account",
368
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]: "Failed to create program execution environment",
369
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: "Program failed to compile",
370
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: "Program failed to complete",
371
+ [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: "instruction modified data of a read-only account",
372
+ [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]: "instruction changed the balance of a read-only account",
373
+ [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]: "Cross-program invocation reentrancy not allowed for this instruction",
374
+ [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: "instruction modified rent epoch of an account",
375
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]: "sum of account balances before and after instruction do not match",
376
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: "instruction requires an initialized account",
377
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: "",
378
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: "Unsupported program id",
379
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: "Unsupported sysvar",
380
+ [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: "Invalid instruction plan kind: $kind.",
381
+ [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: "The provided instruction plan is empty.",
382
+ [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: "The provided transaction plan failed to execute. See the `transactionPlanResult` attribute and the `cause` error for more details.",
383
+ [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: "The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",
384
+ [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: "Invalid transaction plan kind: $kind.",
385
+ [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]: "No more instructions to pack; the message packer has completed the instruction plan.",
386
+ [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: "The instruction does not have any accounts.",
387
+ [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: "The instruction does not have any data.",
388
+ [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: "Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",
389
+ [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: "Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",
390
+ [SOLANA_ERROR__INVALID_NONCE]: "The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",
391
+ [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: "Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
392
+ [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: "Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",
393
+ [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]: "Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
394
+ [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]: "Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
395
+ [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: "Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
396
+ [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: "JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",
397
+ [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: "JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",
398
+ [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: "JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",
399
+ [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: "JSON-RPC error: The method does not exist / is not available ($__serverMessage)",
400
+ [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: "JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",
401
+ [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: "$__serverMessage",
402
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: "$__serverMessage",
403
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: "$__serverMessage",
404
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: "$__serverMessage",
405
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: "Epoch rewards period still active at slot $slot",
406
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: "$__serverMessage",
407
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: "$__serverMessage",
408
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]: "Failed to query long-term storage; please try again",
409
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: "Minimum context slot has not been reached",
410
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: "Node is unhealthy; behind by $numSlotsBehind slots",
411
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: "No snapshot",
412
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: "Transaction simulation failed",
413
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: "Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",
414
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: "$__serverMessage",
415
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]: "Transaction history is not available from this node",
416
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: "$__serverMessage",
417
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: "Transaction signature length mismatch",
418
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]: "Transaction signature verification failure",
419
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: "$__serverMessage",
420
+ [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: "Key pair bytes must be of length 64, got $byteLength.",
421
+ [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: "Expected private key bytes with length 32. Actual length: $actualLength.",
422
+ [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: "Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",
423
+ [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]: "The provided private key does not match the provided public key.",
424
+ [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",
425
+ [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: "Lamports value must be in the range [0, 2e64-1]",
426
+ [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: "`$value` cannot be parsed as a `BigInt`",
427
+ [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: "$message",
428
+ [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: "`$value` cannot be parsed as a `Number`",
429
+ [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: "No nonce account could be found at address `$nonceAccountAddress`",
430
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: "The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",
431
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]: "WebSocket was closed before payload could be added to the send buffer",
432
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: "WebSocket connection closed",
433
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: "WebSocket failed to connect",
434
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]: "Failed to obtain a subscription id from the server",
435
+ [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: "Could not find an API plan for RPC method: `$method`",
436
+ [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: "The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",
437
+ [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: "HTTP error ($statusCode): $message",
438
+ [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: "HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",
439
+ [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: "Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",
440
+ [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: "The provided value does not implement the `KeyPairSigner` interface",
441
+ [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: "The provided value does not implement the `MessageModifyingSigner` interface",
442
+ [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: "The provided value does not implement the `MessagePartialSigner` interface",
443
+ [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: "The provided value does not implement any of the `MessageSigner` interfaces",
444
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: "The provided value does not implement the `TransactionModifyingSigner` interface",
445
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: "The provided value does not implement the `TransactionPartialSigner` interface",
446
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: "The provided value does not implement the `TransactionSendingSigner` interface",
447
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: "The provided value does not implement any of the `TransactionSigner` interfaces",
448
+ [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]: "More than one `TransactionSendingSigner` was identified.",
449
+ [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]: "No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",
450
+ [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]: "Wallet account signers do not support signing multiple messages/transactions in a single operation",
451
+ [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: "Cannot export a non-extractable key.",
452
+ [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: "No digest implementation could be found.",
453
+ [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]: "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",
454
+ [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]: "This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",
455
+ [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]: "No signature verification implementation could be found.",
456
+ [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: "No key generation implementation could be found.",
457
+ [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: "No signing implementation could be found.",
458
+ [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: "No key export implementation could be found.",
459
+ [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: "Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",
460
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: "Transaction processing left an account with an outstanding borrowed reference",
461
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: "Account in use",
462
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: "Account loaded twice",
463
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]: "Attempt to debit an account but found no record of a prior credit.",
464
+ [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]: "Transaction loads an address table account that doesn't exist",
465
+ [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: "This transaction has already been processed",
466
+ [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: "Blockhash not found",
467
+ [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: "Loader call chain is too deep",
468
+ [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]: "Transactions are currently disabled due to cluster maintenance",
469
+ [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: "Transaction contains a duplicate instruction ($index) that is not allowed",
470
+ [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: "Insufficient funds for fee",
471
+ [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: "Transaction results in an account ($accountIndex) with insufficient funds for rent",
472
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: "This account may not be used to pay transaction fees",
473
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: "Transaction contains an invalid account reference",
474
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]: "Transaction loads an address table account with invalid data",
475
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]: "Transaction address table lookup uses an invalid index",
476
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]: "Transaction loads an address table account with an invalid owner",
477
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]: "LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",
478
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]: "This program may not be used for executing instructions",
479
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]: "Transaction leaves an account with a lower balance than rent-exempt minimum",
480
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]: "Transaction loads a writable account that cannot be written",
481
+ [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]: "Transaction exceeded max loaded accounts data size cap",
482
+ [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]: "Transaction requires a fee but has no signature present",
483
+ [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: "Attempt to load a program that does not exist",
484
+ [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: "Execution of the program referenced by account at index $accountIndex is temporarily restricted.",
485
+ [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: "ResanitizationNeeded",
486
+ [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: "Transaction failed to sanitize accounts offsets correctly",
487
+ [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: "Transaction did not pass signature verification",
488
+ [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: "Transaction locked too many accounts",
489
+ [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]: "Sum of account balances before and after transaction do not match",
490
+ [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: "The transaction failed with the error `$errorName`",
491
+ [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: "Transaction version is unsupported",
492
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]: "Transaction would exceed account data limit within the block",
493
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]: "Transaction would exceed total account data limit",
494
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]: "Transaction would exceed max account limit within the block",
495
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]: "Transaction would exceed max Block Cost Limit",
496
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: "Transaction would exceed max Vote Cost Limit",
497
+ [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: "Attempted to sign a transaction with an address that is not a signer for it",
498
+ [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: "Transaction is missing an address at index: $index.",
499
+ [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]: "Transaction has no expected signers therefore it cannot be encoded",
500
+ [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: "Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",
501
+ [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: "Transaction does not have a blockhash lifetime",
502
+ [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: "Transaction is not a durable nonce transaction",
503
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: "Contents of these address lookup tables unknown: $lookupTableAddresses",
504
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: "Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",
505
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: "No fee payer set in CompiledTransaction",
506
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: "Could not find program address at index $index",
507
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]: "Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",
508
+ [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: "Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",
509
+ [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: "Transaction is missing a fee payer.",
510
+ [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]: "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",
511
+ [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]: "Transaction first instruction is not advance nonce account instruction.",
512
+ [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]: "Transaction with no instructions cannot be durable nonce transaction.",
513
+ [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: "This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",
514
+ [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: "This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",
515
+ [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: "The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",
516
+ [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: "Transaction is missing signatures for addresses: $addresses.",
517
+ [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: "Transaction version must be in the range [0, 127]. `$actualVersion` given",
518
+ [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: "This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",
519
+ [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: "The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."
520
+ };
521
+
522
+ // src/message-formatter.ts
523
+ var START_INDEX = "i";
524
+ var TYPE = "t";
525
+ function getHumanReadableErrorMessage(code, context = {}) {
526
+ const messageFormatString = SolanaErrorMessages[code];
527
+ if (messageFormatString.length === 0) {
528
+ return "";
529
+ }
530
+ let state;
531
+ function commitStateUpTo(endIndex) {
532
+ if (state[TYPE] === 2 /* Variable */) {
533
+ const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);
534
+ fragments.push(
535
+ variableName in context ? (
536
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
537
+ `${context[variableName]}`
538
+ ) : `$${variableName}`
539
+ );
540
+ } else if (state[TYPE] === 1 /* Text */) {
541
+ fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));
542
+ }
543
+ }
544
+ const fragments = [];
545
+ messageFormatString.split("").forEach((char, ii) => {
546
+ if (ii === 0) {
547
+ state = {
548
+ [START_INDEX]: 0,
549
+ [TYPE]: messageFormatString[0] === "\\" ? 0 /* EscapeSequence */ : messageFormatString[0] === "$" ? 2 /* Variable */ : 1 /* Text */
550
+ };
551
+ return;
552
+ }
553
+ let nextState;
554
+ switch (state[TYPE]) {
555
+ case 0 /* EscapeSequence */:
556
+ nextState = { [START_INDEX]: ii, [TYPE]: 1 /* Text */ };
557
+ break;
558
+ case 1 /* Text */:
559
+ if (char === "\\") {
560
+ nextState = { [START_INDEX]: ii, [TYPE]: 0 /* EscapeSequence */ };
561
+ } else if (char === "$") {
562
+ nextState = { [START_INDEX]: ii, [TYPE]: 2 /* Variable */ };
563
+ }
564
+ break;
565
+ case 2 /* Variable */:
566
+ if (char === "\\") {
567
+ nextState = { [START_INDEX]: ii, [TYPE]: 0 /* EscapeSequence */ };
568
+ } else if (char === "$") {
569
+ nextState = { [START_INDEX]: ii, [TYPE]: 2 /* Variable */ };
570
+ } else if (!char.match(/\w/)) {
571
+ nextState = { [START_INDEX]: ii, [TYPE]: 1 /* Text */ };
572
+ }
573
+ break;
574
+ }
575
+ if (nextState) {
576
+ if (state !== nextState) {
577
+ commitStateUpTo(ii);
578
+ }
579
+ state = nextState;
580
+ }
581
+ });
582
+ commitStateUpTo();
583
+ return fragments.join("");
584
+ }
585
+ function getErrorMessage(code, context = {}) {
586
+ if (process.env.NODE_ENV !== "production") {
587
+ return getHumanReadableErrorMessage(code, context);
588
+ } else {
589
+ let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;
590
+ if (Object.keys(context).length) {
591
+ decodingAdviceMessage += ` '${encodeContextObject(context)}'`;
592
+ }
593
+ return `${decodingAdviceMessage}\``;
594
+ }
595
+ }
596
+
597
+ // src/error.ts
598
+ function isSolanaError(e, code) {
599
+ const isSolanaError2 = e instanceof Error && e.name === "SolanaError";
600
+ if (isSolanaError2) {
601
+ {
602
+ return e.context.__code === code;
603
+ }
604
+ }
605
+ return false;
606
+ }
607
+ var SolanaError = class extends Error {
608
+ /**
609
+ * Indicates the root cause of this {@link SolanaError}, if any.
610
+ *
611
+ * For example, a transaction error might have an instruction error as its root cause. In this
612
+ * case, you will be able to access the instruction error on the transaction error as `cause`.
613
+ */
614
+ cause = this.cause;
615
+ /**
616
+ * Contains context that can assist in understanding or recovering from a {@link SolanaError}.
617
+ */
618
+ context;
619
+ constructor(...[code, contextAndErrorOptions]) {
620
+ let context;
621
+ let errorOptions;
622
+ if (contextAndErrorOptions) {
623
+ Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {
624
+ if (name === "cause") {
625
+ errorOptions = { cause: descriptor.value };
626
+ } else {
627
+ if (context === void 0) {
628
+ context = {};
629
+ }
630
+ Object.defineProperty(context, name, descriptor);
631
+ }
632
+ });
633
+ }
634
+ const message = getErrorMessage(code, context);
635
+ super(message, errorOptions);
636
+ this.context = context === void 0 ? {} : context;
637
+ this.context.__code = code;
638
+ this.name = "SolanaError";
639
+ }
640
+ };
641
+
642
+ // src/stack-trace.ts
643
+ function safeCaptureStackTrace(...args) {
644
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
645
+ Error.captureStackTrace(...args);
646
+ }
647
+ }
648
+
649
+ // src/rpc-enum-errors.ts
650
+ function getSolanaErrorFromRpcError({ errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }, constructorOpt) {
651
+ let rpcErrorName;
652
+ let rpcErrorContext;
653
+ if (typeof rpcEnumError === "string") {
654
+ rpcErrorName = rpcEnumError;
655
+ } else {
656
+ rpcErrorName = Object.keys(rpcEnumError)[0];
657
+ rpcErrorContext = rpcEnumError[rpcErrorName];
658
+ }
659
+ const codeOffset = orderedErrorNames.indexOf(rpcErrorName);
660
+ const errorCode = errorCodeBaseOffset + codeOffset;
661
+ const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);
662
+ const err = new SolanaError(errorCode, errorContext);
663
+ safeCaptureStackTrace(err, constructorOpt);
664
+ return err;
665
+ }
666
+
667
+ // src/instruction-error.ts
668
+ var ORDERED_ERROR_NAMES = [
669
+ // Keep synced with RPC source: https://github.com/anza-xyz/solana-sdk/blob/master/instruction-error/src/lib.rs
670
+ // If this list ever gets too large, consider implementing a compression strategy like this:
671
+ // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47
672
+ "GenericError",
673
+ "InvalidArgument",
674
+ "InvalidInstructionData",
675
+ "InvalidAccountData",
676
+ "AccountDataTooSmall",
677
+ "InsufficientFunds",
678
+ "IncorrectProgramId",
679
+ "MissingRequiredSignature",
680
+ "AccountAlreadyInitialized",
681
+ "UninitializedAccount",
682
+ "UnbalancedInstruction",
683
+ "ModifiedProgramId",
684
+ "ExternalAccountLamportSpend",
685
+ "ExternalAccountDataModified",
686
+ "ReadonlyLamportChange",
687
+ "ReadonlyDataModified",
688
+ "DuplicateAccountIndex",
689
+ "ExecutableModified",
690
+ "RentEpochModified",
691
+ "NotEnoughAccountKeys",
692
+ "AccountDataSizeChanged",
693
+ "AccountNotExecutable",
694
+ "AccountBorrowFailed",
695
+ "AccountBorrowOutstanding",
696
+ "DuplicateAccountOutOfSync",
697
+ "Custom",
698
+ "InvalidError",
699
+ "ExecutableDataModified",
700
+ "ExecutableLamportChange",
701
+ "ExecutableAccountNotRentExempt",
702
+ "UnsupportedProgramId",
703
+ "CallDepth",
704
+ "MissingAccount",
705
+ "ReentrancyNotAllowed",
706
+ "MaxSeedLengthExceeded",
707
+ "InvalidSeeds",
708
+ "InvalidRealloc",
709
+ "ComputationalBudgetExceeded",
710
+ "PrivilegeEscalation",
711
+ "ProgramEnvironmentSetupFailure",
712
+ "ProgramFailedToComplete",
713
+ "ProgramFailedToCompile",
714
+ "Immutable",
715
+ "IncorrectAuthority",
716
+ "BorshIoError",
717
+ "AccountNotRentExempt",
718
+ "InvalidAccountOwner",
719
+ "ArithmeticOverflow",
720
+ "UnsupportedSysvar",
721
+ "IllegalOwner",
722
+ "MaxAccountsDataAllocationsExceeded",
723
+ "MaxAccountsExceeded",
724
+ "MaxInstructionTraceLengthExceeded",
725
+ "BuiltinProgramsMustConsumeComputeUnits"
726
+ ];
727
+ function getSolanaErrorFromInstructionError(index, instructionError) {
728
+ const numberIndex = Number(index);
729
+ return getSolanaErrorFromRpcError(
730
+ {
731
+ errorCodeBaseOffset: 4615001,
732
+ getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {
733
+ if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {
734
+ return {
735
+ errorName: rpcErrorName,
736
+ index: numberIndex,
737
+ ...rpcErrorContext !== void 0 ? { instructionErrorContext: rpcErrorContext } : null
738
+ };
739
+ } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {
740
+ return {
741
+ code: Number(rpcErrorContext),
742
+ index: numberIndex
743
+ };
744
+ }
745
+ return { index: numberIndex };
746
+ },
747
+ orderedErrorNames: ORDERED_ERROR_NAMES,
748
+ rpcEnumError: instructionError
749
+ },
750
+ getSolanaErrorFromInstructionError
751
+ );
752
+ }
753
+
754
+ // src/transaction-error.ts
755
+ var ORDERED_ERROR_NAMES2 = [
756
+ // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs
757
+ // If this list ever gets too large, consider implementing a compression strategy like this:
758
+ // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47
759
+ "AccountInUse",
760
+ "AccountLoadedTwice",
761
+ "AccountNotFound",
762
+ "ProgramAccountNotFound",
763
+ "InsufficientFundsForFee",
764
+ "InvalidAccountForFee",
765
+ "AlreadyProcessed",
766
+ "BlockhashNotFound",
767
+ // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`
768
+ "CallChainTooDeep",
769
+ "MissingSignatureForFee",
770
+ "InvalidAccountIndex",
771
+ "SignatureFailure",
772
+ "InvalidProgramForExecution",
773
+ "SanitizeFailure",
774
+ "ClusterMaintenance",
775
+ "AccountBorrowOutstanding",
776
+ "WouldExceedMaxBlockCostLimit",
777
+ "UnsupportedVersion",
778
+ "InvalidWritableAccount",
779
+ "WouldExceedMaxAccountCostLimit",
780
+ "WouldExceedAccountDataBlockLimit",
781
+ "TooManyAccountLocks",
782
+ "AddressLookupTableNotFound",
783
+ "InvalidAddressLookupTableOwner",
784
+ "InvalidAddressLookupTableData",
785
+ "InvalidAddressLookupTableIndex",
786
+ "InvalidRentPayingAccount",
787
+ "WouldExceedMaxVoteCostLimit",
788
+ "WouldExceedAccountDataTotalLimit",
789
+ "DuplicateInstruction",
790
+ "InsufficientFundsForRent",
791
+ "MaxLoadedAccountsDataSizeExceeded",
792
+ "InvalidLoadedAccountsDataSizeLimit",
793
+ "ResanitizationNeeded",
794
+ "ProgramExecutionTemporarilyRestricted",
795
+ "UnbalancedTransaction"
796
+ ];
797
+ function getSolanaErrorFromTransactionError(transactionError) {
798
+ if (typeof transactionError === "object" && "InstructionError" in transactionError) {
799
+ return getSolanaErrorFromInstructionError(
800
+ ...transactionError.InstructionError
801
+ );
802
+ }
803
+ return getSolanaErrorFromRpcError(
804
+ {
805
+ errorCodeBaseOffset: 7050001,
806
+ getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {
807
+ if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {
808
+ return {
809
+ errorName: rpcErrorName,
810
+ ...rpcErrorContext !== void 0 ? { transactionErrorContext: rpcErrorContext } : null
811
+ };
812
+ } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {
813
+ return {
814
+ index: Number(rpcErrorContext)
815
+ };
816
+ } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT || errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED) {
817
+ return {
818
+ accountIndex: Number(rpcErrorContext.account_index)
819
+ };
820
+ }
821
+ },
822
+ orderedErrorNames: ORDERED_ERROR_NAMES2,
823
+ rpcEnumError: transactionError
824
+ },
825
+ getSolanaErrorFromTransactionError
826
+ );
827
+ }
828
+
829
+ // src/json-rpc-error.ts
830
+ function getSolanaErrorFromJsonRpcError(putativeErrorResponse) {
831
+ let out;
832
+ if (isRpcErrorResponse(putativeErrorResponse)) {
833
+ const { code: rawCode, data, message } = putativeErrorResponse;
834
+ const code = Number(rawCode);
835
+ if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {
836
+ const { err, ...preflightErrorContext } = data;
837
+ const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;
838
+ out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {
839
+ ...preflightErrorContext,
840
+ ...causeObject
841
+ });
842
+ } else {
843
+ let errorContext;
844
+ switch (code) {
845
+ case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:
846
+ case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:
847
+ case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:
848
+ case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:
849
+ case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:
850
+ case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:
851
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:
852
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:
853
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:
854
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:
855
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:
856
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:
857
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:
858
+ case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:
859
+ errorContext = { __serverMessage: message };
860
+ break;
861
+ default:
862
+ if (typeof data === "object" && !Array.isArray(data)) {
863
+ errorContext = data;
864
+ }
865
+ }
866
+ out = new SolanaError(code, errorContext);
867
+ }
868
+ } else {
869
+ const message = typeof putativeErrorResponse === "object" && putativeErrorResponse !== null && "message" in putativeErrorResponse && typeof putativeErrorResponse.message === "string" ? putativeErrorResponse.message : "Malformed JSON-RPC error with no message attribute";
870
+ out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });
871
+ }
872
+ safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);
873
+ return out;
874
+ }
875
+ function isRpcErrorResponse(value) {
876
+ return typeof value === "object" && value !== null && "code" in value && "message" in value && (typeof value.code === "number" || typeof value.code === "bigint") && typeof value.message === "string";
877
+ }
878
+
879
+ // src/pipe.ts
880
+ function pipe(init, ...fns) {
881
+ return fns.reduce((acc, fn) => fn(acc), init);
882
+ }
883
+
884
+ // src/race.ts
885
+ function isObject(value) {
886
+ return value !== null && (typeof value === "object" || typeof value === "function");
887
+ }
888
+ function addRaceContender(contender) {
889
+ const deferreds = /* @__PURE__ */ new Set();
890
+ const record = { deferreds, settled: false };
891
+ Promise.resolve(contender).then(
892
+ (value) => {
893
+ for (const { resolve } of deferreds) {
894
+ resolve(value);
895
+ }
896
+ deferreds.clear();
897
+ record.settled = true;
898
+ },
899
+ (err) => {
900
+ for (const { reject } of deferreds) {
901
+ reject(err);
902
+ }
903
+ deferreds.clear();
904
+ record.settled = true;
905
+ }
906
+ );
907
+ return record;
908
+ }
909
+ var wm = /* @__PURE__ */ new WeakMap();
910
+ async function safeRace(contenders) {
911
+ let deferred;
912
+ const result = new Promise((resolve, reject) => {
913
+ deferred = { reject, resolve };
914
+ for (const contender of contenders) {
915
+ if (!isObject(contender)) {
916
+ Promise.resolve(contender).then(resolve, reject);
917
+ continue;
918
+ }
919
+ let record = wm.get(contender);
920
+ if (record === void 0) {
921
+ record = addRaceContender(contender);
922
+ record.deferreds.add(deferred);
923
+ wm.set(contender, record);
924
+ } else if (record.settled) {
925
+ Promise.resolve(contender).then(resolve, reject);
926
+ } else {
927
+ record.deferreds.add(deferred);
928
+ }
929
+ }
930
+ });
931
+ return await result.finally(() => {
932
+ for (const contender of contenders) {
933
+ if (isObject(contender)) {
934
+ const record = wm.get(contender);
935
+ record.deferreds.delete(deferred);
936
+ }
937
+ }
938
+ });
939
+ }
940
+
941
+ // src/parse-json-with-bigints.ts
942
+ function parseJsonWithBigInts(json) {
943
+ return JSON.parse(wrapIntegersInBigIntValueObject(json), (_, value) => {
944
+ return isBigIntValueObject(value) ? unwrapBigIntValueObject(value) : value;
945
+ });
946
+ }
947
+ function wrapIntegersInBigIntValueObject(json) {
948
+ const out = [];
949
+ let inQuote = false;
950
+ for (let ii = 0; ii < json.length; ii++) {
951
+ let isEscaped = false;
952
+ if (json[ii] === "\\") {
953
+ out.push(json[ii++]);
954
+ isEscaped = !isEscaped;
955
+ }
956
+ if (json[ii] === '"') {
957
+ out.push(json[ii]);
958
+ if (!isEscaped) {
959
+ inQuote = !inQuote;
960
+ }
961
+ continue;
962
+ }
963
+ if (!inQuote) {
964
+ const consumedNumber = consumeNumber(json, ii);
965
+ if (consumedNumber?.length) {
966
+ ii += consumedNumber.length - 1;
967
+ if (consumedNumber.match(/\.|[eE]-/)) {
968
+ out.push(consumedNumber);
969
+ } else {
970
+ out.push(wrapBigIntValueObject(consumedNumber));
971
+ }
972
+ continue;
973
+ }
974
+ }
975
+ out.push(json[ii]);
976
+ }
977
+ return out.join("");
978
+ }
979
+ function consumeNumber(json, ii) {
980
+ const JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/;
981
+ if (!json[ii]?.match(/[-\d]/)) {
982
+ return null;
983
+ }
984
+ const numberMatch = json.slice(ii).match(JSON_NUMBER_REGEX);
985
+ return numberMatch ? numberMatch[0] : null;
986
+ }
987
+ function wrapBigIntValueObject(value) {
988
+ return `{"$n":"${value}"}`;
989
+ }
990
+ function unwrapBigIntValueObject({ $n }) {
991
+ if ($n.match(/[eE]/)) {
992
+ const [units, exponent] = $n.split(/[eE]/);
993
+ return BigInt(units) * BigInt(10) ** BigInt(exponent);
994
+ }
995
+ return BigInt($n);
996
+ }
997
+ function isBigIntValueObject(value) {
998
+ return !!value && typeof value === "object" && "$n" in value && typeof value.$n === "string";
999
+ }
1000
+
1001
+ // src/rpc-message.ts
1002
+ var _nextMessageId = 0n;
1003
+ function getNextMessageId() {
1004
+ const id = _nextMessageId;
1005
+ _nextMessageId++;
1006
+ return id.toString();
1007
+ }
1008
+ function createRpcMessage(request) {
1009
+ return {
1010
+ id: getNextMessageId(),
1011
+ jsonrpc: "2.0",
1012
+ method: request.methodName,
1013
+ params: request.params
1014
+ };
1015
+ }
1016
+
1017
+ // src/stringify-json-with-bigints.ts
1018
+ function stringifyJsonWithBigInts(value, space) {
1019
+ return unwrapBigIntValueObject2(
1020
+ JSON.stringify(value, (_, v) => typeof v === "bigint" ? wrapBigIntValueObject2(v) : v, space)
1021
+ );
1022
+ }
1023
+ function wrapBigIntValueObject2(value) {
1024
+ return { $n: `${value}` };
1025
+ }
1026
+ function unwrapBigIntValueObject2(value) {
1027
+ return value.replace(/\{\s*"\$n"\s*:\s*"(-?\d+)"\s*\}/g, "$1");
1028
+ }
1029
+
1030
+ // src/rpc.ts
1031
+ function createRpc(rpcConfig) {
1032
+ return makeProxy(rpcConfig);
1033
+ }
1034
+ function makeProxy(rpcConfig) {
1035
+ return new Proxy(rpcConfig.api, {
1036
+ defineProperty() {
1037
+ return false;
1038
+ },
1039
+ deleteProperty() {
1040
+ return false;
1041
+ },
1042
+ get(target, p, receiver) {
1043
+ if (p === "then") {
1044
+ return void 0;
1045
+ }
1046
+ return function(...rawParams) {
1047
+ const methodName = p.toString();
1048
+ const getApiPlan = Reflect.get(target, methodName, receiver);
1049
+ if (!getApiPlan) {
1050
+ throw new SolanaError(SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, {
1051
+ method: methodName,
1052
+ params: rawParams
1053
+ });
1054
+ }
1055
+ const apiPlan = getApiPlan(...rawParams);
1056
+ return createPendingRpcRequest(rpcConfig, apiPlan);
1057
+ };
1058
+ }
1059
+ });
1060
+ }
1061
+ function createPendingRpcRequest({ transport }, plan) {
1062
+ return {
1063
+ async send(options) {
1064
+ return await plan.execute({ signal: options?.abortSignal, transport });
1065
+ }
1066
+ };
1067
+ }
1068
+ function createJsonRpcApi(config) {
1069
+ return new Proxy({}, {
1070
+ defineProperty() {
1071
+ return false;
1072
+ },
1073
+ deleteProperty() {
1074
+ return false;
1075
+ },
1076
+ get(...args) {
1077
+ const [_, p] = args;
1078
+ const methodName = p.toString();
1079
+ return function(...rawParams) {
1080
+ const rawRequest = Object.freeze({ methodName, params: rawParams });
1081
+ const request = config?.requestTransformer ? config?.requestTransformer(rawRequest) : rawRequest;
1082
+ return Object.freeze({
1083
+ execute: async ({ signal, transport }) => {
1084
+ const payload = createRpcMessage(request);
1085
+ const response = await transport({ payload, signal });
1086
+ if (!config?.responseTransformer) {
1087
+ return response;
1088
+ }
1089
+ return config.responseTransformer(response, request);
1090
+ }
1091
+ });
1092
+ };
1093
+ }
1094
+ });
1095
+ }
1096
+
1097
+ // src/rpc-transport.ts
1098
+ function isJsonRpcPayload(payload) {
1099
+ if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
1100
+ return false;
1101
+ }
1102
+ return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
1103
+ }
1104
+
1105
+ // src/request-transformer.ts
1106
+
1107
+ // src/request-transformer-bigint-downcast-internal.ts
1108
+ function downcastNodeToNumberIfBigint(value) {
1109
+ return typeof value === "bigint" ? (
1110
+ // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana
1111
+ // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely
1112
+ // downcasting `bigints` to `numbers`.
1113
+ Number(value)
1114
+ ) : value;
1115
+ }
1116
+
1117
+ // src/tree-traversal.ts
1118
+ var KEYPATH_WILDCARD = {};
1119
+ function getTreeWalker(visitors) {
1120
+ return function traverse(node, state) {
1121
+ if (Array.isArray(node)) {
1122
+ return node.map((element, ii) => {
1123
+ const nextState = {
1124
+ ...state,
1125
+ keyPath: [...state.keyPath, ii]
1126
+ };
1127
+ return traverse(element, nextState);
1128
+ });
1129
+ } else if (typeof node === "object" && node !== null) {
1130
+ const out = {};
1131
+ for (const propName in node) {
1132
+ if (!Object.prototype.hasOwnProperty.call(node, propName)) {
1133
+ continue;
1134
+ }
1135
+ const nextState = {
1136
+ ...state,
1137
+ keyPath: [...state.keyPath, propName]
1138
+ };
1139
+ out[propName] = traverse(node[propName], nextState);
1140
+ }
1141
+ return out;
1142
+ } else {
1143
+ return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);
1144
+ }
1145
+ };
1146
+ }
1147
+ function getTreeWalkerRequestTransformer(visitors, initialState) {
1148
+ return (request) => {
1149
+ const traverse = getTreeWalker(visitors);
1150
+ return Object.freeze({
1151
+ ...request,
1152
+ params: traverse(request.params, initialState)
1153
+ });
1154
+ };
1155
+ }
1156
+ function getTreeWalkerResponseTransformer(visitors, initialState) {
1157
+ return (json) => getTreeWalker(visitors)(json, initialState);
1158
+ }
1159
+
1160
+ // src/request-transformer-bigint-downcast.ts
1161
+ function getBigIntDowncastRequestTransformer() {
1162
+ return getTreeWalkerRequestTransformer([downcastNodeToNumberIfBigint], { keyPath: [] });
1163
+ }
1164
+
1165
+ // src/request-transformer-default-commitment-internal.ts
1166
+ function applyDefaultCommitment({
1167
+ commitmentPropertyName,
1168
+ params,
1169
+ optionsObjectPositionInParams,
1170
+ overrideCommitment
1171
+ }) {
1172
+ const paramInTargetPosition = params[optionsObjectPositionInParams];
1173
+ if (
1174
+ // There's no config.
1175
+ paramInTargetPosition === void 0 || // There is a config object.
1176
+ paramInTargetPosition && typeof paramInTargetPosition === "object" && !Array.isArray(paramInTargetPosition)
1177
+ ) {
1178
+ if (
1179
+ // The config object already has a commitment set.
1180
+ paramInTargetPosition && commitmentPropertyName in paramInTargetPosition
1181
+ ) {
1182
+ if (!paramInTargetPosition[commitmentPropertyName] || paramInTargetPosition[commitmentPropertyName] === "finalized") {
1183
+ const nextParams = [...params];
1184
+ const {
1185
+ [commitmentPropertyName]: _,
1186
+ // eslint-disable-line @typescript-eslint/no-unused-vars
1187
+ ...rest
1188
+ } = paramInTargetPosition;
1189
+ if (Object.keys(rest).length > 0) {
1190
+ nextParams[optionsObjectPositionInParams] = rest;
1191
+ } else {
1192
+ if (optionsObjectPositionInParams === nextParams.length - 1) {
1193
+ nextParams.length--;
1194
+ } else {
1195
+ nextParams[optionsObjectPositionInParams] = void 0;
1196
+ }
1197
+ }
1198
+ return nextParams;
1199
+ }
1200
+ } else if (overrideCommitment !== "finalized") {
1201
+ const nextParams = [...params];
1202
+ nextParams[optionsObjectPositionInParams] = {
1203
+ ...paramInTargetPosition,
1204
+ [commitmentPropertyName]: overrideCommitment
1205
+ };
1206
+ return nextParams;
1207
+ }
1208
+ }
1209
+ return params;
1210
+ }
1211
+
1212
+ // src/request-transformer-default-commitment.ts
1213
+ function getDefaultCommitmentRequestTransformer({
1214
+ defaultCommitment,
1215
+ optionsObjectPositionByMethod
1216
+ }) {
1217
+ return (request) => {
1218
+ const { params, methodName } = request;
1219
+ if (!Array.isArray(params)) {
1220
+ return request;
1221
+ }
1222
+ const optionsObjectPositionInParams = optionsObjectPositionByMethod[methodName];
1223
+ if (optionsObjectPositionInParams == null) {
1224
+ return request;
1225
+ }
1226
+ return Object.freeze({
1227
+ methodName,
1228
+ params: applyDefaultCommitment({
1229
+ commitmentPropertyName: methodName === "sendTransaction" ? "preflightCommitment" : "commitment",
1230
+ optionsObjectPositionInParams,
1231
+ overrideCommitment: defaultCommitment,
1232
+ params
1233
+ })
1234
+ });
1235
+ };
1236
+ }
1237
+
1238
+ // src/request-transformer-integer-overflow-internal.ts
1239
+ function getIntegerOverflowNodeVisitor(onIntegerOverflow) {
1240
+ return (value, { keyPath }) => {
1241
+ if (typeof value === "bigint") {
1242
+ if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {
1243
+ onIntegerOverflow(keyPath, value);
1244
+ }
1245
+ }
1246
+ return value;
1247
+ };
1248
+ }
1249
+
1250
+ // src/request-transformer-integer-overflow.ts
1251
+ function getIntegerOverflowRequestTransformer(onIntegerOverflow) {
1252
+ return (request) => {
1253
+ const transformer = getTreeWalkerRequestTransformer(
1254
+ [getIntegerOverflowNodeVisitor((...args) => onIntegerOverflow(request, ...args))],
1255
+ { keyPath: [] }
1256
+ );
1257
+ return transformer(request);
1258
+ };
1259
+ }
1260
+
1261
+ // src/request-transformer-options-object-position-config.ts
1262
+ var OPTIONS_OBJECT_POSITION_BY_METHOD = {
1263
+ accountNotifications: 1,
1264
+ blockNotifications: 1,
1265
+ getAccountInfo: 1,
1266
+ getBalance: 1,
1267
+ getBlock: 1,
1268
+ getBlockHeight: 0,
1269
+ getBlockProduction: 0,
1270
+ getBlocks: 2,
1271
+ getBlocksWithLimit: 2,
1272
+ getEpochInfo: 0,
1273
+ getFeeForMessage: 1,
1274
+ getInflationGovernor: 0,
1275
+ getInflationReward: 1,
1276
+ getLargestAccounts: 0,
1277
+ getLatestBlockhash: 0,
1278
+ getLeaderSchedule: 1,
1279
+ getMinimumBalanceForRentExemption: 1,
1280
+ getMultipleAccounts: 1,
1281
+ getProgramAccounts: 1,
1282
+ getSignaturesForAddress: 1,
1283
+ getSlot: 0,
1284
+ getSlotLeader: 0,
1285
+ getStakeMinimumDelegation: 0,
1286
+ getSupply: 0,
1287
+ getTokenAccountBalance: 1,
1288
+ getTokenAccountsByDelegate: 2,
1289
+ getTokenAccountsByOwner: 2,
1290
+ getTokenLargestAccounts: 1,
1291
+ getTokenSupply: 1,
1292
+ getTransaction: 1,
1293
+ getTransactionCount: 0,
1294
+ getVoteAccounts: 0,
1295
+ isBlockhashValid: 1,
1296
+ logsNotifications: 1,
1297
+ programNotifications: 1,
1298
+ requestAirdrop: 2,
1299
+ sendTransaction: 1,
1300
+ signatureNotifications: 1,
1301
+ simulateTransaction: 1
1302
+ };
1303
+
1304
+ // src/request-transformer.ts
1305
+ function getDefaultRequestTransformerForSolanaRpc(config) {
1306
+ const handleIntegerOverflow = config?.onIntegerOverflow;
1307
+ return (request) => {
1308
+ return pipe(
1309
+ request,
1310
+ handleIntegerOverflow ? getIntegerOverflowRequestTransformer(handleIntegerOverflow) : (r) => r,
1311
+ getBigIntDowncastRequestTransformer(),
1312
+ getDefaultCommitmentRequestTransformer({
1313
+ defaultCommitment: config?.defaultCommitment,
1314
+ optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD
1315
+ })
1316
+ );
1317
+ };
1318
+ }
1319
+
1320
+ // src/response-transformer-bigint-upcast-internal.ts
1321
+ function getBigIntUpcastVisitor(allowedNumericKeyPaths) {
1322
+ return function upcastNodeToBigIntIfNumber(value, { keyPath }) {
1323
+ const isInteger = typeof value === "number" && Number.isInteger(value) || typeof value === "bigint";
1324
+ if (!isInteger) return value;
1325
+ if (keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) {
1326
+ return Number(value);
1327
+ } else {
1328
+ return BigInt(value);
1329
+ }
1330
+ };
1331
+ }
1332
+ function keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths) {
1333
+ return allowedNumericKeyPaths.some((prohibitedKeyPath) => {
1334
+ if (prohibitedKeyPath.length !== keyPath.length) {
1335
+ return false;
1336
+ }
1337
+ for (let ii = keyPath.length - 1; ii >= 0; ii--) {
1338
+ const keyPathPart = keyPath[ii];
1339
+ const prohibitedKeyPathPart = prohibitedKeyPath[ii];
1340
+ if (prohibitedKeyPathPart !== keyPathPart && (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== "number")) {
1341
+ return false;
1342
+ }
1343
+ }
1344
+ return true;
1345
+ });
1346
+ }
1347
+
1348
+ // src/response-transformer-bigint-upcast.ts
1349
+ function getBigIntUpcastResponseTransformer(allowedNumericKeyPaths) {
1350
+ return getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(allowedNumericKeyPaths)], { keyPath: [] });
1351
+ }
1352
+
1353
+ // src/response-transformer-result.ts
1354
+ function getResultResponseTransformer() {
1355
+ return (json) => json.result;
1356
+ }
1357
+ function getThrowSolanaErrorResponseTransformer() {
1358
+ return (json) => {
1359
+ const jsonRpcResponse = json;
1360
+ if ("error" in jsonRpcResponse) {
1361
+ throw getSolanaErrorFromJsonRpcError(jsonRpcResponse.error);
1362
+ }
1363
+ return jsonRpcResponse;
1364
+ };
1365
+ }
1366
+
1367
+ // src/response-transformer.ts
1368
+ function getDefaultResponseTransformerForSolanaRpc(config) {
1369
+ return (response, request) => {
1370
+ const methodName = request.methodName;
1371
+ const keyPaths = config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : void 0;
1372
+ return pipe(
1373
+ response,
1374
+ (r) => getThrowSolanaErrorResponseTransformer()(r, request),
1375
+ (r) => getResultResponseTransformer()(r, request),
1376
+ (r) => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request)
1377
+ );
1378
+ };
1379
+ }
1380
+ function getDefaultResponseTransformerForSolanaRpcSubscriptions(config) {
1381
+ return (response, request) => {
1382
+ const methodName = request.methodName;
1383
+ const keyPaths = config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : void 0;
1384
+ return pipe(response, (r) => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));
1385
+ };
1386
+ }
1387
+
1388
+ // src/response-transformer-allowed-numeric-values.ts
1389
+ var jsonParsedTokenAccountsConfigs = [
1390
+ // parsed Token/Token22 token account
1391
+ ["data", "parsed", "info", "tokenAmount", "decimals"],
1392
+ ["data", "parsed", "info", "tokenAmount", "uiAmount"],
1393
+ ["data", "parsed", "info", "rentExemptReserve", "decimals"],
1394
+ ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
1395
+ ["data", "parsed", "info", "delegatedAmount", "decimals"],
1396
+ ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
1397
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "olderTransferFee", "transferFeeBasisPoints"],
1398
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "newerTransferFee", "transferFeeBasisPoints"],
1399
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
1400
+ ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
1401
+ ];
1402
+ var jsonParsedAccountsConfigs = [
1403
+ ...jsonParsedTokenAccountsConfigs,
1404
+ // parsed AddressTableLookup account
1405
+ ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
1406
+ // parsed Config account
1407
+ ["data", "parsed", "info", "slashPenalty"],
1408
+ ["data", "parsed", "info", "warmupCooldownRate"],
1409
+ // parsed Token/Token22 mint account
1410
+ ["data", "parsed", "info", "decimals"],
1411
+ // parsed Token/Token22 multisig account
1412
+ ["data", "parsed", "info", "numRequiredSigners"],
1413
+ ["data", "parsed", "info", "numValidSigners"],
1414
+ // parsed Stake account
1415
+ ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
1416
+ // parsed Sysvar rent account
1417
+ ["data", "parsed", "info", "exemptionThreshold"],
1418
+ ["data", "parsed", "info", "burnPercent"],
1419
+ // parsed Vote account
1420
+ ["data", "parsed", "info", "commission"],
1421
+ ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
1422
+ ];
1423
+ var innerInstructionsConfigs = [
1424
+ ["index"],
1425
+ ["instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
1426
+ ["instructions", KEYPATH_WILDCARD, "programIdIndex"],
1427
+ ["instructions", KEYPATH_WILDCARD, "stackHeight"]
1428
+ ];
1429
+ var messageConfig = [
1430
+ ["addressTableLookups", KEYPATH_WILDCARD, "writableIndexes", KEYPATH_WILDCARD],
1431
+ ["addressTableLookups", KEYPATH_WILDCARD, "readonlyIndexes", KEYPATH_WILDCARD],
1432
+ ["header", "numReadonlySignedAccounts"],
1433
+ ["header", "numReadonlyUnsignedAccounts"],
1434
+ ["header", "numRequiredSignatures"],
1435
+ ["instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
1436
+ ["instructions", KEYPATH_WILDCARD, "programIdIndex"],
1437
+ ["instructions", KEYPATH_WILDCARD, "stackHeight"]
1438
+ ];
1439
+
1440
+ // src/index.ts
1441
+ function createSolanaRpcApi(config) {
1442
+ return createJsonRpcApi({
1443
+ requestTransformer: getDefaultRequestTransformerForSolanaRpc(config),
1444
+ responseTransformer: getDefaultResponseTransformerForSolanaRpc({
1445
+ allowedNumericKeyPaths: getAllowedNumericKeypaths$1()
1446
+ })
1447
+ });
1448
+ }
1449
+ var memoizedKeypaths$1;
1450
+ function getAllowedNumericKeypaths$1() {
1451
+ if (!memoizedKeypaths$1) {
1452
+ memoizedKeypaths$1 = {
1453
+ getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
1454
+ getBlock: [
1455
+ ["transactions", KEYPATH_WILDCARD, "meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1456
+ [
1457
+ "transactions",
1458
+ KEYPATH_WILDCARD,
1459
+ "meta",
1460
+ "preTokenBalances",
1461
+ KEYPATH_WILDCARD,
1462
+ "uiTokenAmount",
1463
+ "decimals"
1464
+ ],
1465
+ ["transactions", KEYPATH_WILDCARD, "meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1466
+ [
1467
+ "transactions",
1468
+ KEYPATH_WILDCARD,
1469
+ "meta",
1470
+ "postTokenBalances",
1471
+ KEYPATH_WILDCARD,
1472
+ "uiTokenAmount",
1473
+ "decimals"
1474
+ ],
1475
+ ["transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
1476
+ ...innerInstructionsConfigs.map((c) => [
1477
+ "transactions",
1478
+ KEYPATH_WILDCARD,
1479
+ "meta",
1480
+ "innerInstructions",
1481
+ KEYPATH_WILDCARD,
1482
+ ...c
1483
+ ]),
1484
+ ...messageConfig.map((c) => ["transactions", KEYPATH_WILDCARD, "transaction", "message", ...c]),
1485
+ ["rewards", KEYPATH_WILDCARD, "commission"]
1486
+ ],
1487
+ getClusterNodes: [
1488
+ [KEYPATH_WILDCARD, "featureSet"],
1489
+ [KEYPATH_WILDCARD, "shredVersion"]
1490
+ ],
1491
+ getInflationGovernor: [["initial"], ["foundation"], ["foundationTerm"], ["taper"], ["terminal"]],
1492
+ getInflationRate: [["foundation"], ["total"], ["validator"]],
1493
+ getInflationReward: [[KEYPATH_WILDCARD, "commission"]],
1494
+ getMultipleAccounts: jsonParsedAccountsConfigs.map((c) => ["value", KEYPATH_WILDCARD, ...c]),
1495
+ getProgramAccounts: jsonParsedAccountsConfigs.flatMap((c) => [
1496
+ ["value", KEYPATH_WILDCARD, "account", ...c],
1497
+ [KEYPATH_WILDCARD, "account", ...c]
1498
+ ]),
1499
+ getRecentPerformanceSamples: [[KEYPATH_WILDCARD, "samplePeriodSecs"]],
1500
+ getTokenAccountBalance: [
1501
+ ["value", "decimals"],
1502
+ ["value", "uiAmount"]
1503
+ ],
1504
+ getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map((c) => [
1505
+ "value",
1506
+ KEYPATH_WILDCARD,
1507
+ "account",
1508
+ ...c
1509
+ ]),
1510
+ getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map((c) => [
1511
+ "value",
1512
+ KEYPATH_WILDCARD,
1513
+ "account",
1514
+ ...c
1515
+ ]),
1516
+ getTokenLargestAccounts: [
1517
+ ["value", KEYPATH_WILDCARD, "decimals"],
1518
+ ["value", KEYPATH_WILDCARD, "uiAmount"]
1519
+ ],
1520
+ getTokenSupply: [
1521
+ ["value", "decimals"],
1522
+ ["value", "uiAmount"]
1523
+ ],
1524
+ getTransaction: [
1525
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1526
+ ["meta", "preTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
1527
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
1528
+ ["meta", "postTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
1529
+ ["meta", "rewards", KEYPATH_WILDCARD, "commission"],
1530
+ ...innerInstructionsConfigs.map((c) => ["meta", "innerInstructions", KEYPATH_WILDCARD, ...c]),
1531
+ ...messageConfig.map((c) => ["transaction", "message", ...c])
1532
+ ],
1533
+ getVersion: [["feature-set"]],
1534
+ getVoteAccounts: [
1535
+ ["current", KEYPATH_WILDCARD, "commission"],
1536
+ ["delinquent", KEYPATH_WILDCARD, "commission"]
1537
+ ],
1538
+ simulateTransaction: [
1539
+ ["value", "loadedAccountsDataSize"],
1540
+ ...jsonParsedAccountsConfigs.map((c) => ["value", "accounts", KEYPATH_WILDCARD, ...c]),
1541
+ ...innerInstructionsConfigs.map((c) => ["value", "innerInstructions", KEYPATH_WILDCARD, ...c])
1542
+ ]
1543
+ };
1544
+ }
1545
+ return memoizedKeypaths$1;
1546
+ }
1547
+
1548
+ // src/http-transport.ts
1549
+ var DISALLOWED_HEADERS = {
1550
+ accept: true,
1551
+ "content-length": true,
1552
+ "content-type": true
1553
+ };
1554
+ var FORBIDDEN_HEADERS = /* @__PURE__ */ Object.assign(
1555
+ {
1556
+ "accept-charset": true,
1557
+ "access-control-request-headers": true,
1558
+ "access-control-request-method": true,
1559
+ connection: true,
1560
+ "content-length": true,
1561
+ cookie: true,
1562
+ date: true,
1563
+ dnt: true,
1564
+ expect: true,
1565
+ host: true,
1566
+ "keep-alive": true,
1567
+ "permissions-policy": true,
1568
+ // Prefix matching is implemented in code, below.
1569
+ // 'proxy-': true,
1570
+ // 'sec-': true,
1571
+ referer: true,
1572
+ te: true,
1573
+ trailer: true,
1574
+ "transfer-encoding": true,
1575
+ upgrade: true,
1576
+ via: true
1577
+ },
1578
+ { "accept-encoding": true },
1579
+ { origin: true }
1580
+ );
1581
+ function assertIsAllowedHttpRequestHeaders(headers) {
1582
+ const badHeaders = Object.keys(headers).filter((headerName) => {
1583
+ const lowercaseHeaderName = headerName.toLowerCase();
1584
+ return DISALLOWED_HEADERS[headerName.toLowerCase()] === true || FORBIDDEN_HEADERS[headerName.toLowerCase()] === true || lowercaseHeaderName.startsWith("proxy-") || lowercaseHeaderName.startsWith("sec-");
1585
+ });
1586
+ if (badHeaders.length > 0) {
1587
+ throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, {
1588
+ headers: badHeaders
1589
+ });
1590
+ }
1591
+ }
1592
+ function normalizeHeaders$1(headers) {
1593
+ const out = {};
1594
+ for (const headerName in headers) {
1595
+ out[headerName.toLowerCase()] = headers[headerName];
1596
+ }
1597
+ return out;
1598
+ }
1599
+
1600
+ // src/http-transport.ts
1601
+ var didWarnDispatcherWasSuppliedInNonNodeEnvironment = false;
1602
+ function warnDispatcherWasSuppliedInNonNodeEnvironment() {
1603
+ if (didWarnDispatcherWasSuppliedInNonNodeEnvironment) {
1604
+ return;
1605
+ }
1606
+ didWarnDispatcherWasSuppliedInNonNodeEnvironment = true;
1607
+ console.warn(
1608
+ "You have supplied a `Dispatcher` to `createHttpTransport()`. It has been ignored because Undici dispatchers only work in Node environments. To eliminate this warning, omit the `dispatcher_NODE_ONLY` property from your config when running in a non-Node environment."
1609
+ );
1610
+ }
1611
+ function createHttpTransport(config) {
1612
+ if (process.env.NODE_ENV !== "production" && true && "dispatcher_NODE_ONLY" in config) {
1613
+ warnDispatcherWasSuppliedInNonNodeEnvironment();
1614
+ }
1615
+ const { fromJson, headers, toJson, url } = config;
1616
+ if (process.env.NODE_ENV !== "production" && headers) {
1617
+ assertIsAllowedHttpRequestHeaders(headers);
1618
+ }
1619
+ let dispatcherConfig;
1620
+ const customHeaders = headers && normalizeHeaders$1(headers);
1621
+ return async function makeHttpRequest({
1622
+ payload,
1623
+ signal
1624
+ }) {
1625
+ const body = toJson ? toJson(payload) : JSON.stringify(payload);
1626
+ const requestInfo = {
1627
+ ...dispatcherConfig,
1628
+ body,
1629
+ headers: {
1630
+ ...customHeaders,
1631
+ // Keep these headers lowercase so they will override any user-supplied headers above.
1632
+ accept: "application/json",
1633
+ "content-length": body.length.toString(),
1634
+ "content-type": "application/json; charset=utf-8"
1635
+ },
1636
+ method: "POST",
1637
+ signal
1638
+ };
1639
+ const response = await fetch(url, requestInfo);
1640
+ if (!response.ok) {
1641
+ throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {
1642
+ headers: response.headers,
1643
+ message: response.statusText,
1644
+ statusCode: response.status
1645
+ });
1646
+ }
1647
+ if (fromJson) {
1648
+ return fromJson(await response.text(), payload);
1649
+ }
1650
+ return await response.json();
1651
+ };
1652
+ }
1653
+ var SOLANA_RPC_METHODS = [
1654
+ "getAccountInfo",
1655
+ "getBalance",
1656
+ "getBlock",
1657
+ "getBlockCommitment",
1658
+ "getBlockHeight",
1659
+ "getBlockProduction",
1660
+ "getBlocks",
1661
+ "getBlocksWithLimit",
1662
+ "getBlockTime",
1663
+ "getClusterNodes",
1664
+ "getEpochInfo",
1665
+ "getEpochSchedule",
1666
+ "getFeeForMessage",
1667
+ "getFirstAvailableBlock",
1668
+ "getGenesisHash",
1669
+ "getHealth",
1670
+ "getHighestSnapshotSlot",
1671
+ "getIdentity",
1672
+ "getInflationGovernor",
1673
+ "getInflationRate",
1674
+ "getInflationReward",
1675
+ "getLargestAccounts",
1676
+ "getLatestBlockhash",
1677
+ "getLeaderSchedule",
1678
+ "getMaxRetransmitSlot",
1679
+ "getMaxShredInsertSlot",
1680
+ "getMinimumBalanceForRentExemption",
1681
+ "getMultipleAccounts",
1682
+ "getProgramAccounts",
1683
+ "getRecentPerformanceSamples",
1684
+ "getRecentPrioritizationFees",
1685
+ "getSignaturesForAddress",
1686
+ "getSignatureStatuses",
1687
+ "getSlot",
1688
+ "getSlotLeader",
1689
+ "getSlotLeaders",
1690
+ "getStakeMinimumDelegation",
1691
+ "getSupply",
1692
+ "getTokenAccountBalance",
1693
+ "getTokenAccountsByDelegate",
1694
+ "getTokenAccountsByOwner",
1695
+ "getTokenLargestAccounts",
1696
+ "getTokenSupply",
1697
+ "getTransaction",
1698
+ "getTransactionCount",
1699
+ "getVersion",
1700
+ "getVoteAccounts",
1701
+ "index",
1702
+ "isBlockhashValid",
1703
+ "minimumLedgerSlot",
1704
+ "requestAirdrop",
1705
+ "sendTransaction",
1706
+ "simulateTransaction"
1707
+ ];
1708
+ function isSolanaRequest(payload) {
1709
+ return isJsonRpcPayload(payload) && SOLANA_RPC_METHODS.includes(payload.method);
1710
+ }
1711
+
1712
+ // src/http-transport-for-solana-rpc.ts
1713
+ function createHttpTransportForSolanaRpc(config) {
1714
+ return createHttpTransport({
1715
+ ...config,
1716
+ fromJson: (rawResponse, payload) => isSolanaRequest(payload) ? parseJsonWithBigInts(rawResponse) : JSON.parse(rawResponse),
1717
+ toJson: (payload) => isSolanaRequest(payload) ? stringifyJsonWithBigInts(payload) : JSON.stringify(payload)
1718
+ });
1719
+ }
1720
+
1721
+ // src/index.ts
1722
+ var objToString = Object.prototype.toString;
1723
+ var objKeys = Object.keys || function(obj) {
1724
+ const keys = [];
1725
+ for (const name in obj) {
1726
+ keys.push(name);
1727
+ }
1728
+ return keys;
1729
+ };
1730
+ function stringify(val, isArrayProp) {
1731
+ let i, max, str, keys, key, propVal, toStr;
1732
+ if (val === true) {
1733
+ return "true";
1734
+ }
1735
+ if (val === false) {
1736
+ return "false";
1737
+ }
1738
+ switch (typeof val) {
1739
+ case "object":
1740
+ if (val === null) {
1741
+ return null;
1742
+ } else if ("toJSON" in val && typeof val.toJSON === "function") {
1743
+ return stringify(val.toJSON(), isArrayProp);
1744
+ } else {
1745
+ toStr = objToString.call(val);
1746
+ if (toStr === "[object Array]") {
1747
+ str = "[";
1748
+ max = val.length - 1;
1749
+ for (i = 0; i < max; i++) {
1750
+ str += stringify(val[i], true) + ",";
1751
+ }
1752
+ if (max > -1) {
1753
+ str += stringify(val[i], true);
1754
+ }
1755
+ return str + "]";
1756
+ } else if (toStr === "[object Object]") {
1757
+ keys = objKeys(val).sort();
1758
+ max = keys.length;
1759
+ str = "";
1760
+ i = 0;
1761
+ while (i < max) {
1762
+ key = keys[i];
1763
+ propVal = stringify(val[key], false);
1764
+ if (propVal !== void 0) {
1765
+ if (str) {
1766
+ str += ",";
1767
+ }
1768
+ str += JSON.stringify(key) + ":" + propVal;
1769
+ }
1770
+ i++;
1771
+ }
1772
+ return "{" + str + "}";
1773
+ } else {
1774
+ return JSON.stringify(val);
1775
+ }
1776
+ }
1777
+ case "function":
1778
+ case "undefined":
1779
+ return isArrayProp ? null : void 0;
1780
+ case "bigint":
1781
+ return `${val.toString()}n`;
1782
+ case "string":
1783
+ return JSON.stringify(val);
1784
+ default:
1785
+ return isFinite(val) ? val : null;
1786
+ }
1787
+ }
1788
+ function index_default(val) {
1789
+ const returnVal = stringify(val, false);
1790
+ if (returnVal !== void 0) {
1791
+ return "" + returnVal;
1792
+ }
1793
+ }
1794
+
1795
+ // src/index.ts
1796
+ function createSolanaJsonRpcIntegerOverflowError$1(methodName, keyPath, value) {
1797
+ let argumentLabel = "";
1798
+ if (typeof keyPath[0] === "number") {
1799
+ const argPosition = keyPath[0] + 1;
1800
+ const lastDigit = argPosition % 10;
1801
+ const lastTwoDigits = argPosition % 100;
1802
+ if (lastDigit == 1 && lastTwoDigits != 11) {
1803
+ argumentLabel = argPosition + "st";
1804
+ } else if (lastDigit == 2 && lastTwoDigits != 12) {
1805
+ argumentLabel = argPosition + "nd";
1806
+ } else if (lastDigit == 3 && lastTwoDigits != 13) {
1807
+ argumentLabel = argPosition + "rd";
1808
+ } else {
1809
+ argumentLabel = argPosition + "th";
1810
+ }
1811
+ } else {
1812
+ argumentLabel = `\`${keyPath[0].toString()}\``;
1813
+ }
1814
+ const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
1815
+ const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {
1816
+ argumentLabel,
1817
+ keyPath,
1818
+ methodName,
1819
+ optionalPathLabel: path ? ` at path \`${path}\`` : "",
1820
+ value,
1821
+ ...path !== void 0 ? { path } : void 0
1822
+ });
1823
+ safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError$1);
1824
+ return error;
1825
+ }
1826
+
1827
+ // src/rpc-default-config.ts
1828
+ var DEFAULT_RPC_CONFIG = {
1829
+ defaultCommitment: "confirmed",
1830
+ onIntegerOverflow(request, keyPath, value) {
1831
+ throw createSolanaJsonRpcIntegerOverflowError$1(request.methodName, keyPath, value);
1832
+ }
1833
+ };
1834
+
1835
+ // ../event-target-impl/dist/index.browser.mjs
1836
+ var o$3 = globalThis.AbortController;
1837
+
1838
+ // src/rpc-request-coalescer.ts
1839
+ var EXPLICIT_ABORT_TOKEN$1;
1840
+ function createExplicitAbortToken$1() {
1841
+ return process.env.NODE_ENV !== "production" ? {
1842
+ EXPLICIT_ABORT_TOKEN: "This object is thrown from the request that underlies a series of coalesced requests when the last request in that series aborts"
1843
+ } : {};
1844
+ }
1845
+ function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
1846
+ let coalescedRequestsByDeduplicationKey;
1847
+ return async function makeCoalescedHttpRequest(request) {
1848
+ const { payload, signal } = request;
1849
+ const deduplicationKey = getDeduplicationKey(payload);
1850
+ if (deduplicationKey === void 0) {
1851
+ return await transport(request);
1852
+ }
1853
+ if (!coalescedRequestsByDeduplicationKey) {
1854
+ queueMicrotask(() => {
1855
+ coalescedRequestsByDeduplicationKey = void 0;
1856
+ });
1857
+ coalescedRequestsByDeduplicationKey = {};
1858
+ }
1859
+ if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {
1860
+ const abortController = new o$3();
1861
+ const responsePromise = (async () => {
1862
+ try {
1863
+ return await transport({
1864
+ ...request,
1865
+ signal: abortController.signal
1866
+ });
1867
+ } catch (e) {
1868
+ if (e === (EXPLICIT_ABORT_TOKEN$1 ||= createExplicitAbortToken$1())) {
1869
+ return;
1870
+ }
1871
+ throw e;
1872
+ }
1873
+ })();
1874
+ coalescedRequestsByDeduplicationKey[deduplicationKey] = {
1875
+ abortController,
1876
+ numConsumers: 0,
1877
+ responsePromise
1878
+ };
1879
+ }
1880
+ const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];
1881
+ coalescedRequest.numConsumers++;
1882
+ if (signal) {
1883
+ const responsePromise = coalescedRequest.responsePromise;
1884
+ return await new Promise((resolve, reject) => {
1885
+ const handleAbort = (e) => {
1886
+ signal.removeEventListener("abort", handleAbort);
1887
+ coalescedRequest.numConsumers -= 1;
1888
+ queueMicrotask(() => {
1889
+ if (coalescedRequest.numConsumers === 0) {
1890
+ const abortController = coalescedRequest.abortController;
1891
+ abortController.abort(EXPLICIT_ABORT_TOKEN$1 ||= createExplicitAbortToken$1());
1892
+ }
1893
+ });
1894
+ reject(e.target.reason);
1895
+ };
1896
+ signal.addEventListener("abort", handleAbort);
1897
+ responsePromise.then(resolve).catch(reject).finally(() => {
1898
+ signal.removeEventListener("abort", handleAbort);
1899
+ });
1900
+ });
1901
+ } else {
1902
+ return await coalescedRequest.responsePromise;
1903
+ }
1904
+ };
1905
+ }
1906
+ function getSolanaRpcPayloadDeduplicationKey(payload) {
1907
+ return isJsonRpcPayload(payload) ? index_default([payload.method, payload.params]) : void 0;
1908
+ }
1909
+
1910
+ // src/rpc-transport.ts
1911
+ function normalizeHeaders(headers) {
1912
+ const out = {};
1913
+ for (const headerName in headers) {
1914
+ out[headerName.toLowerCase()] = headers[headerName];
1915
+ }
1916
+ return out;
1917
+ }
1918
+ function createDefaultRpcTransport(config) {
1919
+ return pipe(
1920
+ createHttpTransportForSolanaRpc({
1921
+ ...config,
1922
+ headers: {
1923
+ ...false,
1924
+ ...config.headers ? normalizeHeaders(config.headers) : void 0,
1925
+ ...{
1926
+ // Keep these headers lowercase so they will override any user-supplied headers above.
1927
+ "solana-client": `js/${"5.0.0"}`
1928
+ }
1929
+ }
1930
+ }),
1931
+ (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
1932
+ );
1933
+ }
1934
+
1935
+ // src/rpc.ts
1936
+ function createSolanaRpc(clusterUrl, config) {
1937
+ return createSolanaRpcFromTransport(createDefaultRpcTransport({ url: clusterUrl, ...config }));
1938
+ }
1939
+ function createSolanaRpcFromTransport(transport) {
1940
+ return createRpc({
1941
+ api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),
1942
+ transport
1943
+ });
1944
+ }
1945
+
1946
+ // src/async-iterable.ts
1947
+
1948
+ // ../event-target-impl/dist/index.browser.mjs
1949
+ var o$2 = globalThis.AbortController;
1950
+ var t$1 = globalThis.EventTarget;
1951
+
1952
+ // src/async-iterable.ts
1953
+ var EXPLICIT_ABORT_TOKEN;
1954
+ function createExplicitAbortToken() {
1955
+ return Symbol(
1956
+ process.env.NODE_ENV !== "production" ? "This symbol is thrown from a socket's iterator when the connection is explicitly aborted by the user" : void 0
1957
+ );
1958
+ }
1959
+ var UNINITIALIZED = Symbol();
1960
+ function createAsyncIterableFromDataPublisher({
1961
+ abortSignal,
1962
+ dataChannelName,
1963
+ dataPublisher,
1964
+ errorChannelName
1965
+ }) {
1966
+ const iteratorState = /* @__PURE__ */ new Map();
1967
+ function publishErrorToAllIterators(reason) {
1968
+ for (const [iteratorKey, state] of iteratorState.entries()) {
1969
+ if (state.__hasPolled) {
1970
+ iteratorState.delete(iteratorKey);
1971
+ state.onError(reason);
1972
+ } else {
1973
+ state.publishQueue.push({
1974
+ __type: 1 /* ERROR */,
1975
+ err: reason
1976
+ });
1977
+ }
1978
+ }
1979
+ }
1980
+ const abortController = new o$2();
1981
+ abortSignal.addEventListener("abort", () => {
1982
+ abortController.abort();
1983
+ publishErrorToAllIterators(EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken());
1984
+ });
1985
+ const options = { signal: abortController.signal };
1986
+ let firstError = UNINITIALIZED;
1987
+ dataPublisher.on(
1988
+ errorChannelName,
1989
+ (err) => {
1990
+ if (firstError === UNINITIALIZED) {
1991
+ firstError = err;
1992
+ abortController.abort();
1993
+ publishErrorToAllIterators(err);
1994
+ }
1995
+ },
1996
+ options
1997
+ );
1998
+ dataPublisher.on(
1999
+ dataChannelName,
2000
+ (data) => {
2001
+ iteratorState.forEach((state, iteratorKey) => {
2002
+ if (state.__hasPolled) {
2003
+ const { onData } = state;
2004
+ iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });
2005
+ onData(data);
2006
+ } else {
2007
+ state.publishQueue.push({
2008
+ __type: 0 /* DATA */,
2009
+ data
2010
+ });
2011
+ }
2012
+ });
2013
+ },
2014
+ options
2015
+ );
2016
+ return {
2017
+ async *[Symbol.asyncIterator]() {
2018
+ if (abortSignal.aborted) {
2019
+ return;
2020
+ }
2021
+ if (firstError !== UNINITIALIZED) {
2022
+ throw firstError;
2023
+ }
2024
+ const iteratorKey = Symbol();
2025
+ iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });
2026
+ try {
2027
+ while (true) {
2028
+ const state = iteratorState.get(iteratorKey);
2029
+ if (!state) {
2030
+ throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);
2031
+ }
2032
+ if (state.__hasPolled) {
2033
+ throw new SolanaError(
2034
+ SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE
2035
+ );
2036
+ }
2037
+ const publishQueue = state.publishQueue;
2038
+ try {
2039
+ if (publishQueue.length) {
2040
+ state.publishQueue = [];
2041
+ for (const item of publishQueue) {
2042
+ if (item.__type === 0 /* DATA */) {
2043
+ yield item.data;
2044
+ } else {
2045
+ throw item.err;
2046
+ }
2047
+ }
2048
+ } else {
2049
+ yield await new Promise((resolve, reject) => {
2050
+ iteratorState.set(iteratorKey, {
2051
+ __hasPolled: true,
2052
+ onData: resolve,
2053
+ onError: reject
2054
+ });
2055
+ });
2056
+ }
2057
+ } catch (e) {
2058
+ if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {
2059
+ return;
2060
+ } else {
2061
+ throw e;
2062
+ }
2063
+ }
2064
+ }
2065
+ } finally {
2066
+ iteratorState.delete(iteratorKey);
2067
+ }
2068
+ }
2069
+ };
2070
+ }
2071
+
2072
+ // src/data-publisher.ts
2073
+ function getDataPublisherFromEventEmitter(eventEmitter) {
2074
+ return {
2075
+ on(channelName, subscriber, options) {
2076
+ function innerListener(ev) {
2077
+ if (ev instanceof CustomEvent) {
2078
+ const data = ev.detail;
2079
+ subscriber(data);
2080
+ } else {
2081
+ subscriber();
2082
+ }
2083
+ }
2084
+ eventEmitter.addEventListener(channelName, innerListener, options);
2085
+ return () => {
2086
+ eventEmitter.removeEventListener(channelName, innerListener);
2087
+ };
2088
+ }
2089
+ };
2090
+ }
2091
+
2092
+ // src/demultiplex.ts
2093
+ function demultiplexDataPublisher(publisher, sourceChannelName, messageTransformer) {
2094
+ let innerPublisherState;
2095
+ const eventTarget = new t$1();
2096
+ const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);
2097
+ return {
2098
+ ...demultiplexedDataPublisher,
2099
+ on(channelName, subscriber, options) {
2100
+ if (!innerPublisherState) {
2101
+ const innerPublisherUnsubscribe = publisher.on(sourceChannelName, (sourceMessage) => {
2102
+ const transformResult = messageTransformer(sourceMessage);
2103
+ if (!transformResult) {
2104
+ return;
2105
+ }
2106
+ const [destinationChannelName, message] = transformResult;
2107
+ eventTarget.dispatchEvent(
2108
+ new CustomEvent(destinationChannelName, {
2109
+ detail: message
2110
+ })
2111
+ );
2112
+ });
2113
+ innerPublisherState = {
2114
+ dispose: innerPublisherUnsubscribe,
2115
+ numSubscribers: 0
2116
+ };
2117
+ }
2118
+ innerPublisherState.numSubscribers++;
2119
+ const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);
2120
+ let isActive = true;
2121
+ function handleUnsubscribe() {
2122
+ if (!isActive) {
2123
+ return;
2124
+ }
2125
+ isActive = false;
2126
+ options?.signal.removeEventListener("abort", handleUnsubscribe);
2127
+ innerPublisherState.numSubscribers--;
2128
+ if (innerPublisherState.numSubscribers === 0) {
2129
+ innerPublisherState.dispose();
2130
+ innerPublisherState = void 0;
2131
+ }
2132
+ unsubscribe();
2133
+ }
2134
+ options?.signal.addEventListener("abort", handleUnsubscribe);
2135
+ return handleUnsubscribe;
2136
+ }
2137
+ };
2138
+ }
2139
+
2140
+ // src/rpc-subscriptions.ts
2141
+ function createSubscriptionRpc(rpcConfig) {
2142
+ return new Proxy(rpcConfig.api, {
2143
+ defineProperty() {
2144
+ return false;
2145
+ },
2146
+ deleteProperty() {
2147
+ return false;
2148
+ },
2149
+ get(target, p, receiver) {
2150
+ if (p === "then") {
2151
+ return void 0;
2152
+ }
2153
+ return function(...rawParams) {
2154
+ const notificationName = p.toString();
2155
+ const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);
2156
+ if (!createRpcSubscriptionPlan) {
2157
+ throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {
2158
+ notificationName
2159
+ });
2160
+ }
2161
+ const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);
2162
+ return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);
2163
+ };
2164
+ }
2165
+ });
2166
+ }
2167
+ function createPendingRpcSubscription(transport, subscriptionsPlan) {
2168
+ return {
2169
+ async subscribe({ abortSignal }) {
2170
+ const notificationsDataPublisher = await transport({
2171
+ signal: abortSignal,
2172
+ ...subscriptionsPlan
2173
+ });
2174
+ return createAsyncIterableFromDataPublisher({
2175
+ abortSignal,
2176
+ dataChannelName: "notification",
2177
+ dataPublisher: notificationsDataPublisher,
2178
+ errorChannelName: "error"
2179
+ });
2180
+ }
2181
+ };
2182
+ }
2183
+
2184
+ // src/rpc-subscriptions-api.ts
2185
+ function createRpcSubscriptionsApi(config) {
2186
+ return new Proxy({}, {
2187
+ defineProperty() {
2188
+ return false;
2189
+ },
2190
+ deleteProperty() {
2191
+ return false;
2192
+ },
2193
+ get(...args) {
2194
+ const [_, p] = args;
2195
+ const methodName = p.toString();
2196
+ return function(...params) {
2197
+ const rawRequest = { methodName, params };
2198
+ const request = config.requestTransformer ? config.requestTransformer(rawRequest) : rawRequest;
2199
+ return {
2200
+ execute(planConfig) {
2201
+ return config.planExecutor({ ...planConfig, request });
2202
+ },
2203
+ request
2204
+ };
2205
+ };
2206
+ }
2207
+ });
2208
+ }
2209
+
2210
+ // src/rpc-subscriptions-channel.ts
2211
+ function transformChannelInboundMessages(channel, transform) {
2212
+ return Object.freeze({
2213
+ ...channel,
2214
+ on(type, subscriber, options) {
2215
+ if (type !== "message") {
2216
+ return channel.on(
2217
+ type,
2218
+ subscriber,
2219
+ options
2220
+ );
2221
+ }
2222
+ return channel.on(
2223
+ "message",
2224
+ (message) => subscriber(transform(message)),
2225
+ options
2226
+ );
2227
+ }
2228
+ });
2229
+ }
2230
+ function transformChannelOutboundMessages(channel, transform) {
2231
+ return Object.freeze({
2232
+ ...channel,
2233
+ send: (message) => channel.send(transform(message))
2234
+ });
2235
+ }
2236
+
2237
+ // ../event-target-impl/dist/index.browser.mjs
2238
+ var o$1 = globalThis.AbortController;
2239
+ var subscriberCountBySubscriptionIdByChannel = /* @__PURE__ */ new WeakMap();
2240
+ function decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) {
2241
+ return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);
2242
+ }
2243
+ function incrementSubscriberCount(channel, subscriptionId) {
2244
+ augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);
2245
+ }
2246
+ function getSubscriberCountBySubscriptionIdForChannel(channel) {
2247
+ let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);
2248
+ if (!subscriberCountBySubscriptionId) {
2249
+ subscriberCountBySubscriptionIdByChannel.set(channel, subscriberCountBySubscriptionId = {});
2250
+ }
2251
+ return subscriberCountBySubscriptionId;
2252
+ }
2253
+ function augmentSubscriberCountAndReturnNewCount(amount, channel, subscriptionId) {
2254
+ if (subscriptionId === void 0) {
2255
+ return;
2256
+ }
2257
+ const subscriberCountBySubscriptionId = getSubscriberCountBySubscriptionIdForChannel(channel);
2258
+ if (!subscriberCountBySubscriptionId[subscriptionId] && amount > 0) {
2259
+ subscriberCountBySubscriptionId[subscriptionId] = 0;
2260
+ }
2261
+ const newCount = amount + subscriberCountBySubscriptionId[subscriptionId];
2262
+ if (newCount <= 0) {
2263
+ delete subscriberCountBySubscriptionId[subscriptionId];
2264
+ } else {
2265
+ subscriberCountBySubscriptionId[subscriptionId] = newCount;
2266
+ }
2267
+ return newCount;
2268
+ }
2269
+ var cache = /* @__PURE__ */ new WeakMap();
2270
+ function getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(channel, subscribeRequest, responseTransformer) {
2271
+ let publisherByResponseTransformer = cache.get(channel);
2272
+ if (!publisherByResponseTransformer) {
2273
+ cache.set(channel, publisherByResponseTransformer = /* @__PURE__ */ new WeakMap());
2274
+ }
2275
+ const responseTransformerKey = responseTransformer ?? channel;
2276
+ let publisher = publisherByResponseTransformer.get(responseTransformerKey);
2277
+ if (!publisher) {
2278
+ publisherByResponseTransformer.set(
2279
+ responseTransformerKey,
2280
+ publisher = demultiplexDataPublisher(channel, "message", (rawMessage) => {
2281
+ const message = rawMessage;
2282
+ if (!("method" in message)) {
2283
+ return;
2284
+ }
2285
+ const transformedNotification = responseTransformer ? responseTransformer(message.params.result, subscribeRequest) : message.params.result;
2286
+ return [`notification:${message.params.subscription}`, transformedNotification];
2287
+ })
2288
+ );
2289
+ }
2290
+ return publisher;
2291
+ }
2292
+ async function executeRpcPubSubSubscriptionPlan({
2293
+ channel,
2294
+ responseTransformer,
2295
+ signal,
2296
+ subscribeRequest,
2297
+ unsubscribeMethodName
2298
+ }) {
2299
+ let subscriptionId;
2300
+ channel.on(
2301
+ "error",
2302
+ () => {
2303
+ subscriptionId = void 0;
2304
+ subscriberCountBySubscriptionIdByChannel.delete(channel);
2305
+ },
2306
+ { signal }
2307
+ );
2308
+ const abortPromise = new Promise((_, reject) => {
2309
+ function handleAbort() {
2310
+ if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {
2311
+ const unsubscribePayload = createRpcMessage({
2312
+ methodName: unsubscribeMethodName,
2313
+ params: [subscriptionId]
2314
+ });
2315
+ subscriptionId = void 0;
2316
+ channel.send(unsubscribePayload).catch(() => {
2317
+ });
2318
+ }
2319
+ reject(this.reason);
2320
+ }
2321
+ if (signal.aborted) {
2322
+ handleAbort.call(signal);
2323
+ } else {
2324
+ signal.addEventListener("abort", handleAbort);
2325
+ }
2326
+ });
2327
+ const subscribePayload = createRpcMessage(subscribeRequest);
2328
+ await channel.send(subscribePayload);
2329
+ const subscriptionIdPromise = new Promise((resolve, reject) => {
2330
+ const abortController = new o$1();
2331
+ signal.addEventListener("abort", abortController.abort.bind(abortController));
2332
+ const options = { signal: abortController.signal };
2333
+ channel.on(
2334
+ "error",
2335
+ (err) => {
2336
+ abortController.abort();
2337
+ reject(err);
2338
+ },
2339
+ options
2340
+ );
2341
+ channel.on(
2342
+ "message",
2343
+ (message) => {
2344
+ if (message && typeof message === "object" && "id" in message && message.id === subscribePayload.id) {
2345
+ abortController.abort();
2346
+ if ("error" in message) {
2347
+ reject(getSolanaErrorFromJsonRpcError(message.error));
2348
+ } else {
2349
+ resolve(message.result);
2350
+ }
2351
+ }
2352
+ },
2353
+ options
2354
+ );
2355
+ });
2356
+ subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);
2357
+ if (subscriptionId == null) {
2358
+ throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);
2359
+ }
2360
+ incrementSubscriberCount(channel, subscriptionId);
2361
+ const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(
2362
+ channel,
2363
+ subscribeRequest,
2364
+ responseTransformer
2365
+ );
2366
+ const notificationKey = `notification:${subscriptionId}`;
2367
+ return {
2368
+ on(type, listener, options) {
2369
+ switch (type) {
2370
+ case "notification":
2371
+ return notificationPublisher.on(
2372
+ notificationKey,
2373
+ listener,
2374
+ options
2375
+ );
2376
+ case "error":
2377
+ return channel.on(
2378
+ "error",
2379
+ listener,
2380
+ options
2381
+ );
2382
+ default:
2383
+ throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {
2384
+ channelName: type,
2385
+ supportedChannelNames: ["notification", "error"]
2386
+ });
2387
+ }
2388
+ }
2389
+ };
2390
+ }
2391
+
2392
+ // src/index.ts
2393
+ function createSolanaRpcSubscriptionsApi_INTERNAL(config) {
2394
+ const requestTransformer = getDefaultRequestTransformerForSolanaRpc(config);
2395
+ const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({
2396
+ allowedNumericKeyPaths: getAllowedNumericKeypaths()
2397
+ });
2398
+ return createRpcSubscriptionsApi({
2399
+ planExecutor({ request, ...rest }) {
2400
+ return executeRpcPubSubSubscriptionPlan({
2401
+ ...rest,
2402
+ responseTransformer,
2403
+ subscribeRequest: { ...request, methodName: request.methodName.replace(/Notifications$/, "Subscribe") },
2404
+ unsubscribeMethodName: request.methodName.replace(/Notifications$/, "Unsubscribe")
2405
+ });
2406
+ },
2407
+ requestTransformer
2408
+ });
2409
+ }
2410
+ function createSolanaRpcSubscriptionsApi(config) {
2411
+ return createSolanaRpcSubscriptionsApi_INTERNAL(config);
2412
+ }
2413
+ var memoizedKeypaths;
2414
+ function getAllowedNumericKeypaths() {
2415
+ if (!memoizedKeypaths) {
2416
+ memoizedKeypaths = {
2417
+ accountNotifications: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
2418
+ blockNotifications: [
2419
+ [
2420
+ "value",
2421
+ "block",
2422
+ "transactions",
2423
+ KEYPATH_WILDCARD,
2424
+ "meta",
2425
+ "preTokenBalances",
2426
+ KEYPATH_WILDCARD,
2427
+ "accountIndex"
2428
+ ],
2429
+ [
2430
+ "value",
2431
+ "block",
2432
+ "transactions",
2433
+ KEYPATH_WILDCARD,
2434
+ "meta",
2435
+ "preTokenBalances",
2436
+ KEYPATH_WILDCARD,
2437
+ "uiTokenAmount",
2438
+ "decimals"
2439
+ ],
2440
+ [
2441
+ "value",
2442
+ "block",
2443
+ "transactions",
2444
+ KEYPATH_WILDCARD,
2445
+ "meta",
2446
+ "postTokenBalances",
2447
+ KEYPATH_WILDCARD,
2448
+ "accountIndex"
2449
+ ],
2450
+ [
2451
+ "value",
2452
+ "block",
2453
+ "transactions",
2454
+ KEYPATH_WILDCARD,
2455
+ "meta",
2456
+ "postTokenBalances",
2457
+ KEYPATH_WILDCARD,
2458
+ "uiTokenAmount",
2459
+ "decimals"
2460
+ ],
2461
+ ["value", "block", "transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
2462
+ [
2463
+ "value",
2464
+ "block",
2465
+ "transactions",
2466
+ KEYPATH_WILDCARD,
2467
+ "meta",
2468
+ "innerInstructions",
2469
+ KEYPATH_WILDCARD,
2470
+ "index"
2471
+ ],
2472
+ [
2473
+ "value",
2474
+ "block",
2475
+ "transactions",
2476
+ KEYPATH_WILDCARD,
2477
+ "meta",
2478
+ "innerInstructions",
2479
+ KEYPATH_WILDCARD,
2480
+ "instructions",
2481
+ KEYPATH_WILDCARD,
2482
+ "programIdIndex"
2483
+ ],
2484
+ [
2485
+ "value",
2486
+ "block",
2487
+ "transactions",
2488
+ KEYPATH_WILDCARD,
2489
+ "meta",
2490
+ "innerInstructions",
2491
+ KEYPATH_WILDCARD,
2492
+ "instructions",
2493
+ KEYPATH_WILDCARD,
2494
+ "accounts",
2495
+ KEYPATH_WILDCARD
2496
+ ],
2497
+ [
2498
+ "value",
2499
+ "block",
2500
+ "transactions",
2501
+ KEYPATH_WILDCARD,
2502
+ "transaction",
2503
+ "message",
2504
+ "addressTableLookups",
2505
+ KEYPATH_WILDCARD,
2506
+ "writableIndexes",
2507
+ KEYPATH_WILDCARD
2508
+ ],
2509
+ [
2510
+ "value",
2511
+ "block",
2512
+ "transactions",
2513
+ KEYPATH_WILDCARD,
2514
+ "transaction",
2515
+ "message",
2516
+ "addressTableLookups",
2517
+ KEYPATH_WILDCARD,
2518
+ "readonlyIndexes",
2519
+ KEYPATH_WILDCARD
2520
+ ],
2521
+ [
2522
+ "value",
2523
+ "block",
2524
+ "transactions",
2525
+ KEYPATH_WILDCARD,
2526
+ "transaction",
2527
+ "message",
2528
+ "instructions",
2529
+ KEYPATH_WILDCARD,
2530
+ "programIdIndex"
2531
+ ],
2532
+ [
2533
+ "value",
2534
+ "block",
2535
+ "transactions",
2536
+ KEYPATH_WILDCARD,
2537
+ "transaction",
2538
+ "message",
2539
+ "instructions",
2540
+ KEYPATH_WILDCARD,
2541
+ "accounts",
2542
+ KEYPATH_WILDCARD
2543
+ ],
2544
+ [
2545
+ "value",
2546
+ "block",
2547
+ "transactions",
2548
+ KEYPATH_WILDCARD,
2549
+ "transaction",
2550
+ "message",
2551
+ "header",
2552
+ "numReadonlySignedAccounts"
2553
+ ],
2554
+ [
2555
+ "value",
2556
+ "block",
2557
+ "transactions",
2558
+ KEYPATH_WILDCARD,
2559
+ "transaction",
2560
+ "message",
2561
+ "header",
2562
+ "numReadonlyUnsignedAccounts"
2563
+ ],
2564
+ [
2565
+ "value",
2566
+ "block",
2567
+ "transactions",
2568
+ KEYPATH_WILDCARD,
2569
+ "transaction",
2570
+ "message",
2571
+ "header",
2572
+ "numRequiredSignatures"
2573
+ ],
2574
+ ["value", "block", "rewards", KEYPATH_WILDCARD, "commission"]
2575
+ ],
2576
+ programNotifications: jsonParsedAccountsConfigs.flatMap((c) => [
2577
+ ["value", KEYPATH_WILDCARD, "account", ...c],
2578
+ [KEYPATH_WILDCARD, "account", ...c]
2579
+ ])
2580
+ };
2581
+ }
2582
+ return memoizedKeypaths;
2583
+ }
2584
+
2585
+ // src/websocket-channel.ts
2586
+ var t = globalThis.EventTarget;
2587
+
2588
+ // ../ws-impl/dist/index.browser.mjs
2589
+ var e = globalThis.WebSocket;
2590
+
2591
+ // src/websocket-channel.ts
2592
+ var NORMAL_CLOSURE_CODE = 1e3;
2593
+ function createWebSocketChannel({
2594
+ sendBufferHighWatermark,
2595
+ signal,
2596
+ url
2597
+ }) {
2598
+ if (signal.aborted) {
2599
+ return Promise.reject(signal.reason);
2600
+ }
2601
+ let bufferDrainWatcher;
2602
+ let hasConnected = false;
2603
+ const listenerRemovers = /* @__PURE__ */ new Set();
2604
+ function cleanupListeners() {
2605
+ listenerRemovers.forEach((r) => {
2606
+ r();
2607
+ });
2608
+ listenerRemovers.clear();
2609
+ }
2610
+ function handleAbort() {
2611
+ cleanupListeners();
2612
+ if (!hasConnected) {
2613
+ rejectOpen(signal.reason);
2614
+ }
2615
+ if (webSocket.readyState !== e.CLOSED && webSocket.readyState !== e.CLOSING) {
2616
+ webSocket.close(NORMAL_CLOSURE_CODE);
2617
+ }
2618
+ }
2619
+ function handleClose(ev) {
2620
+ cleanupListeners();
2621
+ bufferDrainWatcher?.onCancel();
2622
+ signal.removeEventListener("abort", handleAbort);
2623
+ webSocket.removeEventListener("close", handleClose);
2624
+ webSocket.removeEventListener("error", handleError);
2625
+ webSocket.removeEventListener("message", handleMessage);
2626
+ webSocket.removeEventListener("open", handleOpen);
2627
+ if (!signal.aborted && !(ev.wasClean && ev.code === NORMAL_CLOSURE_CODE)) {
2628
+ eventTarget.dispatchEvent(
2629
+ new CustomEvent("error", {
2630
+ detail: new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, {
2631
+ cause: ev
2632
+ })
2633
+ })
2634
+ );
2635
+ }
2636
+ }
2637
+ function handleError(ev) {
2638
+ if (signal.aborted) {
2639
+ return;
2640
+ }
2641
+ if (!hasConnected) {
2642
+ const failedToConnectError = new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, {
2643
+ errorEvent: ev
2644
+ });
2645
+ rejectOpen(failedToConnectError);
2646
+ eventTarget.dispatchEvent(
2647
+ new CustomEvent("error", {
2648
+ detail: failedToConnectError
2649
+ })
2650
+ );
2651
+ }
2652
+ }
2653
+ function handleMessage(ev) {
2654
+ if (signal.aborted) {
2655
+ return;
2656
+ }
2657
+ eventTarget.dispatchEvent(new CustomEvent("message", { detail: ev.data }));
2658
+ }
2659
+ const eventTarget = new t();
2660
+ const dataPublisher = getDataPublisherFromEventEmitter(eventTarget);
2661
+ function handleOpen() {
2662
+ hasConnected = true;
2663
+ resolveOpen({
2664
+ ...dataPublisher,
2665
+ async send(message) {
2666
+ if (webSocket.readyState !== e.OPEN) {
2667
+ throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED);
2668
+ }
2669
+ if (!bufferDrainWatcher && webSocket.bufferedAmount > sendBufferHighWatermark) {
2670
+ let onCancel;
2671
+ const promise = new Promise((resolve, reject) => {
2672
+ const intervalId = setInterval(() => {
2673
+ if (webSocket.readyState !== e.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
2674
+ clearInterval(intervalId);
2675
+ bufferDrainWatcher = void 0;
2676
+ resolve();
2677
+ }
2678
+ }, 16);
2679
+ onCancel = () => {
2680
+ bufferDrainWatcher = void 0;
2681
+ clearInterval(intervalId);
2682
+ reject(
2683
+ new SolanaError(
2684
+ SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED
2685
+ )
2686
+ );
2687
+ };
2688
+ });
2689
+ bufferDrainWatcher = {
2690
+ onCancel,
2691
+ promise
2692
+ };
2693
+ }
2694
+ if (bufferDrainWatcher) {
2695
+ if (ArrayBuffer.isView(message) && !(message instanceof DataView)) {
2696
+ const TypedArrayConstructor = message.constructor;
2697
+ message = new TypedArrayConstructor(message);
2698
+ }
2699
+ await bufferDrainWatcher.promise;
2700
+ }
2701
+ webSocket.send(message);
2702
+ }
2703
+ });
2704
+ }
2705
+ const webSocket = new e(url);
2706
+ signal.addEventListener("abort", handleAbort);
2707
+ webSocket.addEventListener("close", handleClose);
2708
+ webSocket.addEventListener("error", handleError);
2709
+ webSocket.addEventListener("message", handleMessage);
2710
+ webSocket.addEventListener("open", handleOpen);
2711
+ let rejectOpen;
2712
+ let resolveOpen;
2713
+ return new Promise((resolve, reject) => {
2714
+ rejectOpen = reject;
2715
+ resolveOpen = resolve;
2716
+ });
2717
+ }
2718
+
2719
+ // src/index.ts
2720
+ function createSolanaJsonRpcIntegerOverflowError(methodName, keyPath, value) {
2721
+ let argumentLabel = "";
2722
+ if (typeof keyPath[0] === "number") {
2723
+ const argPosition = keyPath[0] + 1;
2724
+ const lastDigit = argPosition % 10;
2725
+ const lastTwoDigits = argPosition % 100;
2726
+ if (lastDigit == 1 && lastTwoDigits != 11) {
2727
+ argumentLabel = argPosition + "st";
2728
+ } else if (lastDigit == 2 && lastTwoDigits != 12) {
2729
+ argumentLabel = argPosition + "nd";
2730
+ } else if (lastDigit == 3 && lastTwoDigits != 13) {
2731
+ argumentLabel = argPosition + "rd";
2732
+ } else {
2733
+ argumentLabel = argPosition + "th";
2734
+ }
2735
+ } else {
2736
+ argumentLabel = `\`${keyPath[0].toString()}\``;
2737
+ }
2738
+ const path = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
2739
+ const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {
2740
+ argumentLabel,
2741
+ keyPath,
2742
+ methodName,
2743
+ optionalPathLabel: path ? ` at path \`${path}\`` : "",
2744
+ value,
2745
+ ...path !== void 0 ? { path } : void 0
2746
+ });
2747
+ safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);
2748
+ return error;
2749
+ }
2750
+
2751
+ // src/rpc-default-config.ts
2752
+ var DEFAULT_RPC_SUBSCRIPTIONS_CONFIG = {
2753
+ defaultCommitment: "confirmed",
2754
+ onIntegerOverflow(request, keyPath, value) {
2755
+ throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);
2756
+ }
2757
+ };
2758
+
2759
+ // ../event-target-impl/dist/index.browser.mjs
2760
+ var o = globalThis.AbortController;
2761
+
2762
+ // src/rpc-subscriptions-autopinger.ts
2763
+ var PING_PAYLOAD = {
2764
+ jsonrpc: "2.0",
2765
+ method: "ping"
2766
+ };
2767
+ function getRpcSubscriptionsChannelWithAutoping({
2768
+ abortSignal: callerAbortSignal,
2769
+ channel,
2770
+ intervalMs
2771
+ }) {
2772
+ let intervalId;
2773
+ function sendPing() {
2774
+ channel.send(PING_PAYLOAD).catch((e) => {
2775
+ if (isSolanaError(e, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED)) {
2776
+ pingerAbortController.abort();
2777
+ }
2778
+ });
2779
+ }
2780
+ function restartPingTimer() {
2781
+ clearInterval(intervalId);
2782
+ intervalId = setInterval(sendPing, intervalMs);
2783
+ }
2784
+ const pingerAbortController = new o();
2785
+ pingerAbortController.signal.addEventListener("abort", () => {
2786
+ clearInterval(intervalId);
2787
+ });
2788
+ callerAbortSignal.addEventListener("abort", () => {
2789
+ pingerAbortController.abort();
2790
+ });
2791
+ channel.on(
2792
+ "error",
2793
+ () => {
2794
+ pingerAbortController.abort();
2795
+ },
2796
+ { signal: pingerAbortController.signal }
2797
+ );
2798
+ channel.on("message", restartPingTimer, { signal: pingerAbortController.signal });
2799
+ if (globalThis.navigator.onLine) {
2800
+ restartPingTimer();
2801
+ }
2802
+ {
2803
+ globalThis.addEventListener(
2804
+ "offline",
2805
+ function handleOffline() {
2806
+ clearInterval(intervalId);
2807
+ },
2808
+ { signal: pingerAbortController.signal }
2809
+ );
2810
+ globalThis.addEventListener(
2811
+ "online",
2812
+ function handleOnline() {
2813
+ sendPing();
2814
+ restartPingTimer();
2815
+ },
2816
+ { signal: pingerAbortController.signal }
2817
+ );
2818
+ }
2819
+ return {
2820
+ ...channel,
2821
+ send(...args) {
2822
+ if (!pingerAbortController.signal.aborted) {
2823
+ restartPingTimer();
2824
+ }
2825
+ return channel.send(...args);
2826
+ }
2827
+ };
2828
+ }
2829
+
2830
+ // src/rpc-subscriptions-channel-pool-internal.ts
2831
+ function createChannelPool() {
2832
+ return {
2833
+ entries: [],
2834
+ freeChannelIndex: -1
2835
+ };
2836
+ }
2837
+
2838
+ // src/rpc-subscriptions-channel-pool.ts
2839
+ function getChannelPoolingChannelCreator(createChannel, { maxSubscriptionsPerChannel, minChannels }) {
2840
+ const pool = createChannelPool();
2841
+ function recomputeFreeChannelIndex() {
2842
+ if (pool.entries.length < minChannels) {
2843
+ pool.freeChannelIndex = -1;
2844
+ return;
2845
+ }
2846
+ let mostFreeChannel;
2847
+ for (let ii = 0; ii < pool.entries.length; ii++) {
2848
+ const nextPoolIndex = (pool.freeChannelIndex + ii + 2) % pool.entries.length;
2849
+ const nextPoolEntry = (
2850
+ // Start from the item two positions after the current item. This way, the
2851
+ // search will finish on the item after the current one. This ensures that, if
2852
+ // any channels tie for having the most capacity, the one that will be chosen is
2853
+ // the one immediately to the current one's right (wrapping around).
2854
+ pool.entries[nextPoolIndex]
2855
+ );
2856
+ if (nextPoolEntry.subscriptionCount < maxSubscriptionsPerChannel && (!mostFreeChannel || mostFreeChannel.subscriptionCount >= nextPoolEntry.subscriptionCount)) {
2857
+ mostFreeChannel = {
2858
+ poolIndex: nextPoolIndex,
2859
+ subscriptionCount: nextPoolEntry.subscriptionCount
2860
+ };
2861
+ }
2862
+ }
2863
+ pool.freeChannelIndex = mostFreeChannel?.poolIndex ?? -1;
2864
+ }
2865
+ return function getExistingChannelWithMostCapacityOrCreateChannel({ abortSignal }) {
2866
+ let poolEntry;
2867
+ function destroyPoolEntry() {
2868
+ const index = pool.entries.findIndex((entry) => entry === poolEntry);
2869
+ pool.entries.splice(index, 1);
2870
+ poolEntry.dispose();
2871
+ recomputeFreeChannelIndex();
2872
+ }
2873
+ if (pool.freeChannelIndex === -1) {
2874
+ const abortController = new o();
2875
+ const newChannelPromise = createChannel({ abortSignal: abortController.signal });
2876
+ newChannelPromise.then((newChannel) => {
2877
+ newChannel.on("error", destroyPoolEntry, { signal: abortController.signal });
2878
+ }).catch(destroyPoolEntry);
2879
+ poolEntry = {
2880
+ channel: newChannelPromise,
2881
+ dispose() {
2882
+ abortController.abort();
2883
+ },
2884
+ subscriptionCount: 0
2885
+ };
2886
+ pool.entries.push(poolEntry);
2887
+ } else {
2888
+ poolEntry = pool.entries[pool.freeChannelIndex];
2889
+ }
2890
+ poolEntry.subscriptionCount++;
2891
+ abortSignal.addEventListener("abort", function destroyConsumer() {
2892
+ poolEntry.subscriptionCount--;
2893
+ if (poolEntry.subscriptionCount === 0) {
2894
+ destroyPoolEntry();
2895
+ } else if (pool.freeChannelIndex !== -1) {
2896
+ pool.freeChannelIndex--;
2897
+ recomputeFreeChannelIndex();
2898
+ }
2899
+ });
2900
+ recomputeFreeChannelIndex();
2901
+ return poolEntry.channel;
2902
+ };
2903
+ }
2904
+ function getRpcSubscriptionsChannelWithBigIntJSONSerialization(channel) {
2905
+ return pipe(
2906
+ channel,
2907
+ (c) => transformChannelInboundMessages(c, parseJsonWithBigInts),
2908
+ (c) => transformChannelOutboundMessages(c, stringifyJsonWithBigInts)
2909
+ );
2910
+ }
2911
+
2912
+ // src/rpc-subscriptions-channel.ts
2913
+ function createDefaultSolanaRpcSubscriptionsChannelCreator(config) {
2914
+ return createDefaultRpcSubscriptionsChannelCreatorImpl({
2915
+ ...config,
2916
+ jsonSerializer: getRpcSubscriptionsChannelWithBigIntJSONSerialization
2917
+ });
2918
+ }
2919
+ function createDefaultRpcSubscriptionsChannelCreatorImpl(config) {
2920
+ if (/^wss?:/i.test(config.url) === false) {
2921
+ const protocolMatch = config.url.match(/^([^:]+):/);
2922
+ throw new DOMException(
2923
+ protocolMatch ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.` : `Failed to construct 'WebSocket': The URL '${config.url}' is invalid.`
2924
+ );
2925
+ }
2926
+ const { intervalMs, ...rest } = config;
2927
+ const createDefaultRpcSubscriptionsChannel = ({ abortSignal }) => {
2928
+ return createWebSocketChannel({
2929
+ ...rest,
2930
+ sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
2931
+ 131072,
2932
+ signal: abortSignal
2933
+ }).then(config.jsonSerializer).then(
2934
+ (channel) => getRpcSubscriptionsChannelWithAutoping({
2935
+ abortSignal,
2936
+ channel,
2937
+ intervalMs: intervalMs ?? 5e3
2938
+ })
2939
+ );
2940
+ };
2941
+ return getChannelPoolingChannelCreator(createDefaultRpcSubscriptionsChannel, {
2942
+ maxSubscriptionsPerChannel: config.maxSubscriptionsPerChannel ?? /**
2943
+ * A note about this default. The idea here is that, because some RPC providers impose
2944
+ * an upper limit on the number of subscriptions you can make per channel, we must
2945
+ * choose a number low enough to avoid hitting that limit. Without knowing what provider
2946
+ * a given person is using, or what their limit is, we have to choose the lowest of all
2947
+ * known limits. As of this writing (October 2024) that is the public mainnet RPC node
2948
+ * (api.mainnet-beta.solana.com) at 100 subscriptions.
2949
+ */
2950
+ 100,
2951
+ minChannels: config.minChannels ?? 1
2952
+ });
2953
+ }
2954
+ function getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport) {
2955
+ const cache = /* @__PURE__ */ new Map();
2956
+ return function rpcSubscriptionsTransportWithSubscriptionCoalescing(config) {
2957
+ const { request, signal } = config;
2958
+ const subscriptionConfigurationHash = index_default([request.methodName, request.params]);
2959
+ let cachedDataPublisherPromise = cache.get(subscriptionConfigurationHash);
2960
+ if (!cachedDataPublisherPromise) {
2961
+ const abortController = new o();
2962
+ const dataPublisherPromise = transport({
2963
+ ...config,
2964
+ signal: abortController.signal
2965
+ });
2966
+ dataPublisherPromise.then((dataPublisher) => {
2967
+ dataPublisher.on(
2968
+ "error",
2969
+ () => {
2970
+ cache.delete(subscriptionConfigurationHash);
2971
+ abortController.abort();
2972
+ },
2973
+ { signal: abortController.signal }
2974
+ );
2975
+ }).catch(() => {
2976
+ });
2977
+ cache.set(
2978
+ subscriptionConfigurationHash,
2979
+ cachedDataPublisherPromise = {
2980
+ abortController,
2981
+ dataPublisherPromise,
2982
+ numSubscribers: 0
2983
+ }
2984
+ );
2985
+ }
2986
+ cachedDataPublisherPromise.numSubscribers++;
2987
+ signal.addEventListener(
2988
+ "abort",
2989
+ () => {
2990
+ cachedDataPublisherPromise.numSubscribers--;
2991
+ if (cachedDataPublisherPromise.numSubscribers === 0) {
2992
+ queueMicrotask(() => {
2993
+ if (cachedDataPublisherPromise.numSubscribers === 0) {
2994
+ cache.delete(subscriptionConfigurationHash);
2995
+ cachedDataPublisherPromise.abortController.abort();
2996
+ }
2997
+ });
2998
+ }
2999
+ },
3000
+ { signal: cachedDataPublisherPromise.abortController.signal }
3001
+ );
3002
+ return cachedDataPublisherPromise.dataPublisherPromise;
3003
+ };
3004
+ }
3005
+ function createDefaultRpcSubscriptionsTransport({
3006
+ createChannel
3007
+ }) {
3008
+ return pipe(
3009
+ createRpcSubscriptionsTransportFromChannelCreator(
3010
+ createChannel
3011
+ ),
3012
+ (transport) => getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport)
3013
+ );
3014
+ }
3015
+ function createRpcSubscriptionsTransportFromChannelCreator(createChannel) {
3016
+ return async ({ execute, signal }) => {
3017
+ const channel = await createChannel({ abortSignal: signal });
3018
+ return await execute({ channel, signal });
3019
+ };
3020
+ }
3021
+ function createSolanaRpcSubscriptionsImpl(clusterUrl, config) {
3022
+ const transport = createDefaultRpcSubscriptionsTransport({
3023
+ createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({ ...config, url: clusterUrl })
3024
+ });
3025
+ return createSolanaRpcSubscriptionsFromTransport(transport);
3026
+ }
3027
+ function createSolanaRpcSubscriptions(clusterUrl, config) {
3028
+ return createSolanaRpcSubscriptionsImpl(clusterUrl, config);
3029
+ }
3030
+ function createSolanaRpcSubscriptionsFromTransport(transport) {
3031
+ return createSubscriptionRpc({
3032
+ api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_SUBSCRIPTIONS_CONFIG),
3033
+ transport
3034
+ });
3035
+ }
3036
+
3037
+ const SURFNET_RPC_URL = "https://surfpool.fly.dev";
3038
+ let React;
3039
+ let ReactDOM;
3040
+ let privyImports;
3041
+ let privySolana;
3042
+ // Only load React and Privy dependencies if we're in a browser
3043
+ if (typeof window !== 'undefined') {
3044
+ React = require('react');
3045
+ ReactDOM = require('react-dom/client');
3046
+ privyImports = require('@privy-io/react-auth');
3047
+ privySolana = require('@privy-io/react-auth/solana');
3048
+ }
3049
+ const defaultPrivyConfig = {
3050
+ appId: "cm4ve714908o27dk2yurpnfhd",
3051
+ config: {
3052
+ embeddedWallets: {
3053
+ solana: {
3054
+ createOnLogin: "users-without-wallets"
3055
+ }
3056
+ },
3057
+ appearance: {
3058
+ walletChainType: 'solana-only'
3059
+ },
3060
+ externalWallets: { solana: { connectors: privySolana.toSolanaWalletConnectors() } }
3061
+ }
3062
+ };
3063
+ class PrivyWalletProvider {
3064
+ constructor(appName, appLogoUrl, privyConfig, networkUrl = null) {
3065
+ this.containerElement = null;
3066
+ this.chainId = 'solana:mainnet';
3067
+ this.root = null;
3068
+ this.privyMethods = null;
3069
+ this.privyConfig = defaultPrivyConfig;
3070
+ this.pendingLogin = null;
3071
+ // This is used to store the pending transaction until the wallet is connected for workaround for the wallet not being connected after login completion
3072
+ this.pendingTransaction = null;
3073
+ // This is used to store pending signTransaction calls until the wallet is connected
3074
+ this.pendingSignTransaction = null;
3075
+ // This is used to store pending signMessage calls until the wallet is connected
3076
+ this.pendingSignMessage = null;
3077
+ // This is used to store pending signAndSubmitTransaction calls until the wallet is connected
3078
+ this.pendingSignAndSubmitTransaction = null;
3079
+ this.networkUrl = networkUrl;
3080
+ if (typeof window === 'undefined') {
3081
+ throw new Error('PrivyWalletProvider can only be instantiated in a browser environment');
3082
+ }
3083
+ if (PrivyWalletProvider.instance) {
3084
+ return PrivyWalletProvider.instance;
3085
+ }
3086
+ this.containerElement = null;
3087
+ this.root = null;
3088
+ this.privyMethods = null;
3089
+ this.privyConfig = privyConfig !== null && privyConfig !== void 0 ? privyConfig : defaultPrivyConfig;
3090
+ // Only use the appName and appLogoUrl if no privyConfig is provided
3091
+ if (privyConfig == null) {
3092
+ if (appName != null && appName != '') {
3093
+ this.privyConfig.config.appearance.landingHeader = appName;
3094
+ }
3095
+ if (appLogoUrl != null && appLogoUrl != '') {
3096
+ this.privyConfig.config.appearance.logo = appLogoUrl;
3097
+ }
3098
+ }
3099
+ // Ensure externalWallets connectors are always configured — required for
3100
+ // useWallets().ready to resolve even when no browser extension is present
3101
+ if (!this.privyConfig.config.externalWallets) {
3102
+ this.privyConfig.config.externalWallets = {
3103
+ solana: { connectors: privySolana.toSolanaWalletConnectors() }
3104
+ };
3105
+ }
3106
+ // Add Solana RPC configuration for v3
3107
+ let devnetUrl = SOLANA_DEVNET_RPC_URL;
3108
+ let mainnetUrl = SOLANA_MAINNET_RPC_URL;
3109
+ if (networkUrl != null) {
3110
+ if (networkUrl.includes('mainnet')) {
3111
+ mainnetUrl = networkUrl;
3112
+ this.chainId = 'solana:mainnet';
3113
+ }
3114
+ else if (networkUrl.includes('devnet')) {
3115
+ devnetUrl = networkUrl;
3116
+ this.chainId = 'solana:devnet';
3117
+ }
3118
+ }
3119
+ if (!this.privyConfig.config.solana) {
3120
+ this.privyConfig.config.solana = {};
3121
+ }
3122
+ this.privyConfig.config.solana.rpcs = {
3123
+ 'solana:devnet': {
3124
+ rpc: createSolanaRpc(devnetUrl),
3125
+ rpcSubscriptions: createSolanaRpcSubscriptions(devnetUrl.replace('https://', 'wss://'))
3126
+ },
3127
+ 'solana:mainnet': {
3128
+ rpc: createSolanaRpc(mainnetUrl),
3129
+ rpcSubscriptions: createSolanaRpcSubscriptions(mainnetUrl.replace('https://', 'wss://'))
3130
+ }
3131
+ };
3132
+ const existingProviders = document.querySelectorAll('[data-privy-provider]');
3133
+ existingProviders.forEach(el => el.remove());
3134
+ this.initialize();
3135
+ // Assign this instance to the static instance property
3136
+ PrivyWalletProvider.instance = this;
3137
+ }
3138
+ // Optional: Provide a static method to get the instance
3139
+ static getInstance(appName, appLogoUrl, privyConfig) {
3140
+ if (!PrivyWalletProvider.instance) {
3141
+ new PrivyWalletProvider(appName, appLogoUrl, privyConfig);
3142
+ }
3143
+ return PrivyWalletProvider.instance;
3144
+ }
3145
+ initialize() {
3146
+ if (!this.containerElement) {
3147
+ this.containerElement = document.createElement('div');
3148
+ this.containerElement.setAttribute('data-privy-provider', 'true');
3149
+ document.body.appendChild(this.containerElement);
3150
+ const that = this;
3151
+ const PrivyComponent = () => {
3152
+ const privy = privyImports.usePrivy();
3153
+ const useOAuthTokens = privyImports.useOAuthTokens();
3154
+ const useFundWalletSolana = privySolana.useFundWallet();
3155
+ const useSendTransactionSolana = privySolana.useSignAndSendTransaction();
3156
+ const { signTransaction } = privySolana.useSignTransaction();
3157
+ const { signMessage: signMessageHook } = privySolana.useSignMessage();
3158
+ const { ready: walletReady, wallets } = privySolana.useWallets();
3159
+ const { createWallet } = privySolana.useCreateWallet();
3160
+ const { exportWallet } = privySolana.useExportWallet();
3161
+ const useSolanaWallets = { createWallet, exportWallet, ready: walletReady, wallets };
3162
+ const useIdentityToken = privyImports.useIdentityToken();
3163
+ const { connectWallet } = privyImports.useConnectWallet({
3164
+ onSuccess: async ({ wallet }) => {
3165
+ await that.createSession(wallet.address, await privy.getAccessToken(), useIdentityToken.identityToken);
3166
+ // If there's a pending transaction, execute it now
3167
+ if (that.pendingTransaction) {
3168
+ const { evmTransactionData, solTransactionData, options, resolve, reject } = that.pendingTransaction;
3169
+ try {
3170
+ const result = await that.runTransaction(evmTransactionData, solTransactionData, options);
3171
+ resolve(result);
3172
+ }
3173
+ catch (error) {
3174
+ reject(error);
3175
+ }
3176
+ that.pendingTransaction = null;
3177
+ }
3178
+ // If there's a pending signTransaction, execute it now
3179
+ if (that.pendingSignTransaction) {
3180
+ const { transaction, resolve, reject } = that.pendingSignTransaction;
3181
+ try {
3182
+ const result = await that.signTransaction(transaction);
3183
+ resolve(result);
3184
+ }
3185
+ catch (error) {
3186
+ reject(error);
3187
+ }
3188
+ that.pendingSignTransaction = null;
3189
+ }
3190
+ // If there's a pending signMessage, execute it now
3191
+ if (that.pendingSignMessage) {
3192
+ const { message, resolve, reject } = that.pendingSignMessage;
3193
+ try {
3194
+ const result = await that.signMessage(message);
3195
+ resolve(result);
3196
+ }
3197
+ catch (error) {
3198
+ reject(error);
3199
+ }
3200
+ that.pendingSignMessage = null;
3201
+ }
3202
+ // If there's a pending signAndSubmitTransaction, execute it now
3203
+ if (that.pendingSignAndSubmitTransaction) {
3204
+ const { transaction, feePayer, resolve, reject } = that.pendingSignAndSubmitTransaction;
3205
+ try {
3206
+ const result = await that.signAndSubmitTransaction(transaction, feePayer);
3207
+ resolve(result);
3208
+ }
3209
+ catch (error) {
3210
+ reject(error);
3211
+ }
3212
+ that.pendingSignAndSubmitTransaction = null;
3213
+ }
3214
+ },
3215
+ onError: (error) => {
3216
+ // Only log errors that aren't user-initiated cancellations
3217
+ if (error !== 'exited_auth_flow' && (error === null || error === void 0 ? void 0 : error.message) !== 'exited_auth_flow') {
3218
+ console.error('Wallet connection error:', error);
3219
+ }
3220
+ if (that.pendingTransaction) {
3221
+ that.pendingTransaction.reject(error);
3222
+ that.pendingTransaction = null;
3223
+ }
3224
+ if (that.pendingSignTransaction) {
3225
+ that.pendingSignTransaction.reject(error);
3226
+ that.pendingSignTransaction = null;
3227
+ }
3228
+ if (that.pendingSignMessage) {
3229
+ that.pendingSignMessage.reject(error);
3230
+ that.pendingSignMessage = null;
3231
+ }
3232
+ if (that.pendingSignAndSubmitTransaction) {
3233
+ that.pendingSignAndSubmitTransaction.reject(error);
3234
+ that.pendingSignAndSubmitTransaction = null;
3235
+ }
3236
+ }
3237
+ });
3238
+ const { login } = privyImports.useLogin({
3239
+ onComplete: async ({ user }) => {
3240
+ var _a;
3241
+ // This is a hack to indicate to the app that privy login is not complete
3242
+ // @ts-ignore
3243
+ window.runningPrivyOnComplete = true;
3244
+ if (!user) {
3245
+ WebSessionManager.clearSession();
3246
+ return;
3247
+ }
3248
+ const solanaLinkedAccounts = user.linkedAccounts.filter((account) => account.chainType === 'solana');
3249
+ const sortedLinkedAccounts = solanaLinkedAccounts.sort((a, b) => new Date(b.latestVerifiedAt).getTime() - new Date(a.latestVerifiedAt).getTime());
3250
+ let finalAddress = (_a = sortedLinkedAccounts[0]) === null || _a === void 0 ? void 0 : _a.address;
3251
+ if (!finalAddress) {
3252
+ const solanaWallet = await createWallet();
3253
+ finalAddress = solanaWallet.address;
3254
+ WebSessionManager.clearSession();
3255
+ return;
3256
+ }
3257
+ const session = await WebSessionManager.getSession();
3258
+ if (!session || finalAddress !== session.address) {
3259
+ try {
3260
+ const accessToken = await privy.getAccessToken();
3261
+ const idToken = useIdentityToken.identityToken;
3262
+ await that.createSession(finalAddress, accessToken, idToken);
3263
+ }
3264
+ catch (error) {
3265
+ console.error('Error creating session:', error);
3266
+ }
3267
+ }
3268
+ // @ts-ignore
3269
+ window.runningPrivyOnComplete = false;
3270
+ setCurrentUser({ address: finalAddress, provider: that });
3271
+ if (that.pendingLogin) {
3272
+ that.pendingLogin.resolve({ address: finalAddress, provider: that });
3273
+ that.pendingLogin = null;
3274
+ }
3275
+ },
3276
+ onError: (error) => {
3277
+ // Only log errors that aren't user-initiated cancellations
3278
+ if (error !== 'exited_auth_flow' && (error === null || error === void 0 ? void 0 : error.message) !== 'exited_auth_flow') {
3279
+ console.error('Login error:', error);
3280
+ }
3281
+ if (that.pendingLogin) {
3282
+ that.pendingLogin.reject(error);
3283
+ that.pendingLogin = null;
3284
+ }
3285
+ }
3286
+ });
3287
+ const { logout } = privyImports.useLogout({
3288
+ onSuccess: () => {
3289
+ WebSessionManager.clearSession();
3290
+ setCurrentUser(null);
3291
+ }
3292
+ });
3293
+ React.useEffect(() => {
3294
+ if (privy.ready) {
3295
+ that.privyMethods = {
3296
+ ready: privy.ready,
3297
+ walletReady: walletReady,
3298
+ authenticated: privy.authenticated,
3299
+ wallets,
3300
+ login,
3301
+ logout,
3302
+ connectWallet,
3303
+ getAccessToken: privy.getAccessToken,
3304
+ identityToken: useIdentityToken.identityToken,
3305
+ usePrivy: privy,
3306
+ useOAuthTokens: useOAuthTokens,
3307
+ useFundWalletSolana: useFundWalletSolana,
3308
+ useSendTransactionSolana: useSendTransactionSolana,
3309
+ useSolanaWallets: useSolanaWallets,
3310
+ signTransaction: signTransaction,
3311
+ signMessage: signMessageHook,
3312
+ };
3313
+ }
3314
+ }, [privy.ready, privy.authenticated, wallets, login, logout, walletReady]);
3315
+ return null;
3316
+ };
3317
+ const FinalPrivyComponent = () => {
3318
+ if (typeof window === 'undefined') {
3319
+ return null;
3320
+ }
3321
+ return React.createElement(privyImports.PrivyProvider, {
3322
+ appId: this.privyConfig.appId,
3323
+ config: this.privyConfig.config,
3324
+ children: React.createElement(PrivyComponent)
3325
+ });
3326
+ };
3327
+ this.root = ReactDOM.createRoot(this.containerElement);
3328
+ this.root.render(React.createElement(FinalPrivyComponent));
3329
+ }
3330
+ }
3331
+ async login() {
3332
+ var _a, _b;
3333
+ await this.ensureReady();
3334
+ // Check if we have a valid session that matches an authenticated wallet
3335
+ const session = await WebSessionManager.getSession();
3336
+ if (((_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.authenticated) && ((_b = this.privyMethods.wallets) === null || _b === void 0 ? void 0 : _b.length) > 0 && session) {
3337
+ // Find the wallet matching the session
3338
+ const matchingWallet = this.privyMethods.wallets.find((wallet) => wallet.address === session.address);
3339
+ if (matchingWallet) {
3340
+ // Valid session with matching wallet, return immediately
3341
+ setCurrentUser({ address: matchingWallet.address, provider: this });
3342
+ return {
3343
+ address: matchingWallet.address,
3344
+ provider: this
3345
+ };
3346
+ }
3347
+ // Session exists but doesn't match any connected wallet
3348
+ // This can happen after wallet switching - force fresh login
3349
+ console.log('Session wallet mismatch detected, forcing fresh login flow');
3350
+ }
3351
+ // If no valid session or wallet mismatch, force a fresh login flow
3352
+ // This ensures the user can select the correct wallet, especially after logout
3353
+ if (this.pendingLogin) {
3354
+ return new Promise((resolve, reject) => {
3355
+ this.pendingLogin.resolve = resolve;
3356
+ this.pendingLogin.reject = reject;
3357
+ });
3358
+ }
3359
+ return new Promise((resolve, reject) => {
3360
+ this.pendingLogin = { resolve, reject };
3361
+ // open Privy modal to let user select/verify wallet
3362
+ this.privyMethods.login();
3363
+ // safety timeout
3364
+ setTimeout(() => {
3365
+ if (this.pendingLogin) {
3366
+ this.pendingLogin.reject(new Error("Login timed out"));
3367
+ this.pendingLogin = null;
3368
+ }
3369
+ }, 180000);
3370
+ });
3371
+ }
3372
+ async getNativeMethods() {
3373
+ var _a;
3374
+ await this.ensureReady();
3375
+ return (_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.usePrivy;
3376
+ }
3377
+ async logout() {
3378
+ await this.ensureReady();
3379
+ await this.privyMethods.logout();
3380
+ }
3381
+ async runTransaction(_evmTransactionData, solTransactionData, options) {
3382
+ var _a, _b, _c;
3383
+ await this.ensureReady({ waitForWallets: true });
3384
+ let session = await WebSessionManager.getSession();
3385
+ let sessionAddress = session === null || session === void 0 ? void 0 : session.address;
3386
+ let privyWallets = (_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.wallets;
3387
+ let privyWallet = privyWallets === null || privyWallets === void 0 ? void 0 : privyWallets.find((wallet) => wallet.address === sessionAddress);
3388
+ // If wallet not found yet, it may be an embedded wallet (email login) that hasn't
3389
+ // appeared in the wallets array due to React state timing. Wait for it before
3390
+ // falling back to connectWallet() which shows an unwanted wallet selection modal.
3391
+ if (!privyWallets || privyWallets.length === 0 || !privyWallet) {
3392
+ if (((_b = this.privyMethods) === null || _b === void 0 ? void 0 : _b.authenticated) && sessionAddress) {
3393
+ privyWallet = await this.waitForMatchingWallet(sessionAddress);
3394
+ }
3395
+ }
3396
+ if (!privyWallet) {
3397
+ // If there's already a pending transaction, throw an error to prevent overlapping calls
3398
+ if (this.pendingTransaction) {
3399
+ throw new Error("Oops... something went wrong. Please try again.");
3400
+ }
3401
+ // Create a promise to wait for the transaction result
3402
+ return new Promise((resolve, reject) => {
3403
+ this.pendingTransaction = {
3404
+ resolve,
3405
+ reject,
3406
+ evmTransactionData: _evmTransactionData,
3407
+ solTransactionData,
3408
+ options
3409
+ };
3410
+ this.privyMethods.connectWallet();
3411
+ // Set a timeout to reject the promise if connection takes too long
3412
+ setTimeout(() => {
3413
+ if (this.pendingTransaction) {
3414
+ this.pendingTransaction.reject(new Error("Wallet connection timed out"));
3415
+ this.pendingTransaction = null;
3416
+ }
3417
+ }, 30000); // 30 seconds timeout
3418
+ });
3419
+ }
3420
+ // Proceed with the transaction using privyWallet
3421
+ const wallet = privyWallet;
3422
+ if (solTransactionData == null) {
3423
+ throw new Error("Solana transaction data is required");
3424
+ }
3425
+ const rpcUrl = this.getRpcUrl(solTransactionData.network);
3426
+ const connection = new Connection(rpcUrl, "confirmed");
3427
+ const remainingAccounts = convertRemainingAccounts(solTransactionData.txArgs[0].remainingAccounts);
3428
+ let app_id = solTransactionData.appId;
3429
+ if (typeof window !== 'undefined' && window.CUSTOM_TAROBASE_APP_ID_HEADER) {
3430
+ const customAppId = window.CUSTOM_TAROBASE_APP_ID_HEADER;
3431
+ if (customAppId) {
3432
+ app_id = customAppId;
3433
+ }
3434
+ }
3435
+ if (!app_id) {
3436
+ throw new Error("App ID is required");
3437
+ }
3438
+ const anchorProvider = new anchor.AnchorProvider(connection, wallet.provider, anchor.AnchorProvider.defaultOptions());
3439
+ const finalDeduped = [];
3440
+ for (const acc of remainingAccounts) {
3441
+ const existing = finalDeduped.find((d) => d.pubkey.equals(acc.pubkey));
3442
+ if (existing) {
3443
+ existing.isSigner = existing.isSigner || acc.isSigner;
3444
+ existing.isWritable = existing.isWritable || acc.isWritable;
3445
+ }
3446
+ else {
3447
+ finalDeduped.push(acc);
3448
+ }
3449
+ }
3450
+ let tx;
3451
+ let blockhash;
3452
+ let lastValidBlockHeight;
3453
+ if (solTransactionData.signedTransaction) {
3454
+ // Server already set the blockhash and co-signed — do NOT overwrite
3455
+ // the blockhash or it will invalidate the server's signature.
3456
+ tx = VersionedTransaction.deserialize(Buffer.from(solTransactionData.signedTransaction, 'base64'));
3457
+ // Extract the blockhash that was baked into the signed message
3458
+ blockhash = tx.message.recentBlockhash;
3459
+ const latestBlockhash = await connection.getLatestBlockhash('confirmed');
3460
+ lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;
3461
+ }
3462
+ else {
3463
+ const result = await buildSetDocumentsTransaction(connection, solTransactionData.txArgs[0].idl, anchorProvider, new PublicKey(wallet.address), { app_id, documents: solTransactionData.txArgs[0].setDocumentData, delete_paths: solTransactionData.txArgs[0].deletePaths, txData: solTransactionData.txArgs[0].txData }, finalDeduped, solTransactionData.lutKey, solTransactionData.preInstructions, false, solTransactionData.additionalLutAddresses);
3464
+ tx = result.tx;
3465
+ blockhash = result.blockhash;
3466
+ lastValidBlockHeight = result.lastValidBlockHeight;
3467
+ }
3468
+ // Use duck typing instead of instanceof to handle multiple @solana/web3.js versions
3469
+ const isLegacyTx = 'recentBlockhash' in tx && !('message' in tx && 'staticAccountKeys' in tx.message);
3470
+ if (isLegacyTx) {
3471
+ tx.recentBlockhash = blockhash;
3472
+ tx.lastValidBlockHeight = lastValidBlockHeight;
3473
+ }
3474
+ else {
3475
+ tx.message.recentBlockhash = blockhash;
3476
+ }
3477
+ try {
3478
+ if ((options === null || options === void 0 ? void 0 : options.shouldSubmitTx) === false) {
3479
+ // Just sign, don't submit - return raw signed bytes (same as original runTransaction)
3480
+ const signedTx = await this.signTransactionRaw(tx, privyWallet);
3481
+ return {
3482
+ signedTransaction: signedTx, // Raw Uint8Array from Privy
3483
+ blockNumber: 0,
3484
+ gasUsed: "0",
3485
+ data: ""
3486
+ };
3487
+ }
3488
+ // Sign and submit using shared helper
3489
+ const { signature, txInfo } = await this.signAndSubmitInternal(tx, privyWallet, rpcUrl, connection);
3490
+ return {
3491
+ transactionSignature: signature,
3492
+ blockNumber: (txInfo === null || txInfo === void 0 ? void 0 : txInfo.slot) || 0,
3493
+ gasUsed: ((_c = txInfo === null || txInfo === void 0 ? void 0 : txInfo.meta) === null || _c === void 0 ? void 0 : _c.fee.toString()) || '0',
3494
+ data: txInfo === null || txInfo === void 0 ? void 0 : txInfo.meta,
3495
+ };
3496
+ }
3497
+ catch (err) {
3498
+ console.error(err);
3499
+ throw err;
3500
+ }
3501
+ }
3502
+ /**
3503
+ * Signs a Solana transaction without submitting it.
3504
+ *
3505
+ * This method handles blockhash automatically if not set - you do NOT need to
3506
+ * set recentBlockhash on the transaction before calling this method.
3507
+ * The network/RPC URL is derived from the provider's configuration (set during initialization).
3508
+ *
3509
+ * @param transaction - The transaction to sign (Transaction or VersionedTransaction)
3510
+ * @returns The signed transaction
3511
+ */
3512
+ async signTransaction(transaction) {
3513
+ var _a, _b;
3514
+ await this.ensureReady({ waitForWallets: true });
3515
+ let privyWallets = (_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.wallets;
3516
+ let session = await WebSessionManager.getSession();
3517
+ let sessionAddress = session === null || session === void 0 ? void 0 : session.address;
3518
+ let privyWallet = privyWallets === null || privyWallets === void 0 ? void 0 : privyWallets.find((wallet) => wallet.address === sessionAddress);
3519
+ // If there's already a pending sign transaction, throw an error to prevent overlapping calls
3520
+ if (this.pendingSignTransaction) {
3521
+ throw new Error("Oops... something went wrong. Please try again.");
3522
+ }
3523
+ // If wallet not found yet, it may be an embedded wallet (email login) that hasn't
3524
+ // appeared in the wallets array due to React state timing. Wait for it before
3525
+ // falling back to connectWallet() which shows an unwanted wallet selection modal.
3526
+ if (!privyWallets || privyWallets.length === 0 || !privyWallet) {
3527
+ if (((_b = this.privyMethods) === null || _b === void 0 ? void 0 : _b.authenticated) && sessionAddress) {
3528
+ privyWallet = await this.waitForMatchingWallet(sessionAddress);
3529
+ }
3530
+ }
3531
+ // If still no wallet after waiting, trigger connection and queue the signing
3532
+ if (!privyWallet) {
3533
+ return new Promise((resolve, reject) => {
3534
+ this.pendingSignTransaction = {
3535
+ resolve,
3536
+ reject,
3537
+ transaction
3538
+ };
3539
+ this.privyMethods.connectWallet();
3540
+ // Set a timeout to reject the promise if connection takes too long
3541
+ setTimeout(() => {
3542
+ if (this.pendingSignTransaction) {
3543
+ this.pendingSignTransaction.reject(new Error("Wallet connection timed out"));
3544
+ this.pendingSignTransaction = null;
3545
+ }
3546
+ }, 30000); // 30 seconds timeout
3547
+ });
3548
+ }
3549
+ // Privy requires serialized transaction bytes, which requires a blockhash.
3550
+ // If the transaction doesn't have one, get a fresh blockhash and set it.
3551
+ // Use duck typing instead of instanceof to handle multiple @solana/web3.js versions
3552
+ const isLegacyTransaction = 'recentBlockhash' in transaction && !('message' in transaction && 'staticAccountKeys' in transaction.message);
3553
+ if (isLegacyTransaction) {
3554
+ const legacyTx = transaction;
3555
+ if (!legacyTx.recentBlockhash) {
3556
+ const rpcUrl = this.getRpcUrl();
3557
+ const connection = new Connection(rpcUrl, 'confirmed');
3558
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
3559
+ legacyTx.recentBlockhash = blockhash;
3560
+ legacyTx.lastValidBlockHeight = lastValidBlockHeight;
3561
+ }
3562
+ // Set feePayer if not already set
3563
+ if (!legacyTx.feePayer) {
3564
+ legacyTx.feePayer = new PublicKey(privyWallet.address);
3565
+ }
3566
+ }
3567
+ else {
3568
+ // VersionedTransaction
3569
+ const versionedTx = transaction;
3570
+ if (!versionedTx.message.recentBlockhash) {
3571
+ const rpcUrl = this.getRpcUrl();
3572
+ const connection = new Connection(rpcUrl, 'confirmed');
3573
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
3574
+ versionedTx.message.recentBlockhash = blockhash;
3575
+ }
3576
+ }
3577
+ // Sign using raw method, then deserialize for the public API
3578
+ const signedTxRaw = await this.signTransactionRaw(transaction, privyWallet);
3579
+ return this.deserializeSignedTransaction(signedTxRaw);
3580
+ }
3581
+ /**
3582
+ * Signs and submits a Solana transaction to the network.
3583
+ *
3584
+ * This method handles blockhash and transaction confirmation automatically - you do NOT need to
3585
+ * set recentBlockhash or lastValidBlockHeight on the transaction before calling this method.
3586
+ * The network/RPC URL is derived from the provider's configuration (set during initialization).
3587
+ *
3588
+ * @param transaction - The transaction to sign and submit (Transaction or VersionedTransaction)
3589
+ * @param feePayer - Optional fee payer public key. If not provided and the transaction doesn't
3590
+ * already have a feePayer set, the connected wallet address will be used.
3591
+ * Useful for co-signing scenarios where a different account pays the fees.
3592
+ * @returns The transaction signature
3593
+ */
3594
+ async signAndSubmitTransaction(transaction, feePayer) {
3595
+ var _a, _b;
3596
+ await this.ensureReady({ waitForWallets: true });
3597
+ let privyWallets = (_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.wallets;
3598
+ let session = await WebSessionManager.getSession();
3599
+ let sessionAddress = session === null || session === void 0 ? void 0 : session.address;
3600
+ let privyWallet = privyWallets === null || privyWallets === void 0 ? void 0 : privyWallets.find((wallet) => wallet.address === sessionAddress);
3601
+ // If there's already a pending signAndSubmitTransaction, throw an error to prevent overlapping calls
3602
+ if (this.pendingSignAndSubmitTransaction) {
3603
+ throw new Error("Oops... something went wrong. Please try again.");
3604
+ }
3605
+ // If wallet not found yet, it may be an embedded wallet (email login) that hasn't
3606
+ // appeared in the wallets array due to React state timing. Wait for it before
3607
+ // falling back to connectWallet() which shows an unwanted wallet selection modal.
3608
+ if (!privyWallets || privyWallets.length === 0 || !privyWallet) {
3609
+ if (((_b = this.privyMethods) === null || _b === void 0 ? void 0 : _b.authenticated) && sessionAddress) {
3610
+ privyWallet = await this.waitForMatchingWallet(sessionAddress);
3611
+ }
3612
+ }
3613
+ // If still no wallet after waiting, trigger connection and queue the signing
3614
+ if (!privyWallet) {
3615
+ return new Promise((resolve, reject) => {
3616
+ this.pendingSignAndSubmitTransaction = {
3617
+ resolve,
3618
+ reject,
3619
+ transaction,
3620
+ feePayer
3621
+ };
3622
+ this.privyMethods.connectWallet();
3623
+ // Set a timeout to reject the promise if connection takes too long
3624
+ setTimeout(() => {
3625
+ if (this.pendingSignAndSubmitTransaction) {
3626
+ this.pendingSignAndSubmitTransaction.reject(new Error("Wallet connection timed out"));
3627
+ this.pendingSignAndSubmitTransaction = null;
3628
+ }
3629
+ }, 30000); // 30 seconds timeout
3630
+ });
3631
+ }
3632
+ // Get RPC URL and create connection
3633
+ const rpcUrl = this.getRpcUrl();
3634
+ const connection = new Connection(rpcUrl, 'confirmed');
3635
+ // Get fresh blockhash and set it on the transaction before signing
3636
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
3637
+ // Use duck typing instead of instanceof to handle multiple @solana/web3.js versions
3638
+ const isLegacyTransaction = 'recentBlockhash' in transaction && !('message' in transaction && 'staticAccountKeys' in transaction.message);
3639
+ if (isLegacyTransaction) {
3640
+ const legacyTx = transaction;
3641
+ legacyTx.recentBlockhash = blockhash;
3642
+ legacyTx.lastValidBlockHeight = lastValidBlockHeight;
3643
+ // Set feePayer if not already set
3644
+ if (!legacyTx.feePayer) {
3645
+ legacyTx.feePayer = feePayer !== null && feePayer !== void 0 ? feePayer : new PublicKey(privyWallet.address);
3646
+ }
3647
+ }
3648
+ else {
3649
+ // VersionedTransaction
3650
+ const versionedTx = transaction;
3651
+ versionedTx.message.recentBlockhash = blockhash;
3652
+ // Note: VersionedTransaction feePayer is set in the message at creation time
3653
+ // and cannot be modified after creation
3654
+ }
3655
+ // Use shared sign and submit logic
3656
+ const { signature } = await this.signAndSubmitInternal(transaction, privyWallet, rpcUrl, connection);
3657
+ return signature;
3658
+ }
3659
+ // ============ Private Helpers ============
3660
+ getRpcUrl(network) {
3661
+ if (this.networkUrl) {
3662
+ return this.networkUrl;
3663
+ }
3664
+ if (network === 'solana_devnet') {
3665
+ return SOLANA_DEVNET_RPC_URL;
3666
+ }
3667
+ else if (network === 'solana_mainnet') {
3668
+ return SOLANA_MAINNET_RPC_URL;
3669
+ }
3670
+ else if (network === 'surfnet') {
3671
+ return SURFNET_RPC_URL;
3672
+ }
3673
+ return SOLANA_MAINNET_RPC_URL; // default to mainnet
3674
+ }
3675
+ /**
3676
+ * Internal sign transaction - serializes and signs via Privy
3677
+ * Returns the raw result from Privy (Uint8Array)
3678
+ * This mirrors exactly what runTransaction was doing
3679
+ */
3680
+ async signTransactionRaw(transaction, privyWallet) {
3681
+ var _a;
3682
+ // Serialize the transaction
3683
+ // Use duck typing instead of instanceof to handle multiple @solana/web3.js versions
3684
+ const isLegacyTransaction = 'recentBlockhash' in transaction && !('message' in transaction && 'staticAccountKeys' in transaction.message);
3685
+ let serializedForSign;
3686
+ if (isLegacyTransaction) {
3687
+ serializedForSign = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });
3688
+ }
3689
+ else {
3690
+ serializedForSign = transaction.serialize();
3691
+ }
3692
+ // Sign via Privy - returns { signedTransaction: Uint8Array }
3693
+ const result = await ((_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.signTransaction({
3694
+ transaction: serializedForSign,
3695
+ wallet: privyWallet,
3696
+ chain: this.chainId
3697
+ }));
3698
+ // Privy returns { signedTransaction: Uint8Array }, unwrap it
3699
+ const signedTx = (result === null || result === void 0 ? void 0 : result.signedTransaction) || result;
3700
+ return signedTx;
3701
+ }
3702
+ /**
3703
+ * Deserialize a signed transaction from Uint8Array to Transaction object
3704
+ */
3705
+ deserializeSignedTransaction(signedTxRaw) {
3706
+ // Handle different formats Privy might return
3707
+ let signedTx;
3708
+ if (signedTxRaw instanceof Uint8Array) {
3709
+ signedTx = signedTxRaw;
3710
+ }
3711
+ else if (Array.isArray(signedTxRaw)) {
3712
+ signedTx = new Uint8Array(signedTxRaw);
3713
+ }
3714
+ else if (signedTxRaw && typeof signedTxRaw === 'object' && 'signedTransaction' in signedTxRaw) {
3715
+ // Privy might wrap the result
3716
+ signedTx = signedTxRaw.signedTransaction instanceof Uint8Array
3717
+ ? signedTxRaw.signedTransaction
3718
+ : new Uint8Array(signedTxRaw.signedTransaction);
3719
+ }
3720
+ else if (Buffer.isBuffer(signedTxRaw)) {
3721
+ signedTx = new Uint8Array(signedTxRaw);
3722
+ }
3723
+ else {
3724
+ throw new Error(`Unexpected signed transaction format: ${typeof signedTxRaw}`);
3725
+ }
3726
+ // Try to deserialize as VersionedTransaction first, fall back to legacy Transaction
3727
+ try {
3728
+ return VersionedTransaction.deserialize(signedTx);
3729
+ }
3730
+ catch (_a) {
3731
+ return Transaction.from(signedTx);
3732
+ }
3733
+ }
3734
+ /**
3735
+ * Internal sign and submit - handles Surfnet vs non-Surfnet logic
3736
+ * This is the core submission logic used by both signAndSubmitTransaction and runTransaction
3737
+ *
3738
+ * For Surfnet: sign with signTransactionRaw, then sendRawTransaction
3739
+ * For non-Surfnet: use Privy's signAndSendTransaction (combined operation)
3740
+ */
3741
+ async signAndSubmitInternal(transaction, privyWallet, rpcUrl, connection) {
3742
+ var _a;
3743
+ const isSurfnet = rpcUrl === SURFNET_RPC_URL;
3744
+ let signature;
3745
+ if (isSurfnet) {
3746
+ // For Surfnet: sign with signTransactionRaw, then sendRawTransaction
3747
+ const signedTx = await this.signTransactionRaw(transaction, privyWallet);
3748
+ signature = await connection.sendRawTransaction(signedTx);
3749
+ }
3750
+ else {
3751
+ // For non-Surfnet: use Privy's combined signAndSendTransaction
3752
+ // Serialize the transaction for Privy API
3753
+ // Use duck typing instead of instanceof to handle multiple @solana/web3.js versions
3754
+ const isLegacyTransaction = 'recentBlockhash' in transaction && !('message' in transaction && 'staticAccountKeys' in transaction.message);
3755
+ let serializedTx;
3756
+ if (isLegacyTransaction) {
3757
+ serializedTx = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });
3758
+ }
3759
+ else {
3760
+ serializedTx = transaction.serialize();
3761
+ }
3762
+ const result = await ((_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.useSendTransactionSolana.signAndSendTransaction({
3763
+ transaction: serializedTx,
3764
+ wallet: privyWallet,
3765
+ chain: this.chainId
3766
+ }));
3767
+ // Handle case where signature might be bytes instead of string
3768
+ const rawSig = result.signature;
3769
+ if (rawSig instanceof Uint8Array || Array.isArray(rawSig)) {
3770
+ signature = bs58.encode(rawSig instanceof Uint8Array ? rawSig : new Uint8Array(rawSig));
3771
+ }
3772
+ else {
3773
+ signature = rawSig;
3774
+ }
3775
+ }
3776
+ const txInfo = await confirmAndCheckTransaction(connection, signature);
3777
+ return { signature, txInfo };
3778
+ }
3779
+ async signMessage(message) {
3780
+ var _a, _b, _c;
3781
+ await this.ensureReady({ waitForWallets: true });
3782
+ const session = await WebSessionManager.getSession();
3783
+ let sessionAddress = session === null || session === void 0 ? void 0 : session.address;
3784
+ // If there's already a pending sign message, throw an error to prevent overlapping calls
3785
+ if (this.pendingSignMessage) {
3786
+ throw new Error("Oops... something went wrong. Please try again.");
3787
+ }
3788
+ // If no wallets connected yet, it may be an embedded wallet (email login) that hasn't
3789
+ // appeared in the wallets array due to React state timing. Wait for it before
3790
+ // falling back to connectWallet() which shows an unwanted wallet selection modal.
3791
+ if (!((_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.wallets) || this.privyMethods.wallets.length === 0) {
3792
+ if (((_b = this.privyMethods) === null || _b === void 0 ? void 0 : _b.authenticated) && sessionAddress) {
3793
+ const matchedWallet = await this.waitForMatchingWallet(sessionAddress);
3794
+ if (!matchedWallet) {
3795
+ return new Promise((resolve, reject) => {
3796
+ this.pendingSignMessage = {
3797
+ resolve,
3798
+ reject,
3799
+ message
3800
+ };
3801
+ this.privyMethods.connectWallet();
3802
+ // Set a timeout to reject the promise if connection takes too long
3803
+ setTimeout(() => {
3804
+ if (this.pendingSignMessage) {
3805
+ this.pendingSignMessage.reject(new Error("Wallet connection timed out"));
3806
+ this.pendingSignMessage = null;
3807
+ }
3808
+ }, 30000); // 30 seconds timeout
3809
+ });
3810
+ }
3811
+ }
3812
+ else {
3813
+ return new Promise((resolve, reject) => {
3814
+ this.pendingSignMessage = {
3815
+ resolve,
3816
+ reject,
3817
+ message
3818
+ };
3819
+ this.privyMethods.connectWallet();
3820
+ // Set a timeout to reject the promise if connection takes too long
3821
+ setTimeout(() => {
3822
+ if (this.pendingSignMessage) {
3823
+ this.pendingSignMessage.reject(new Error("Wallet connection timed out"));
3824
+ this.pendingSignMessage = null;
3825
+ }
3826
+ }, 30000); // 30 seconds timeout
3827
+ });
3828
+ }
3829
+ }
3830
+ let privyWallet = this.privyMethods.wallets.find((wallet) => wallet.address === sessionAddress);
3831
+ if (!privyWallet) {
3832
+ // Session address is not a privy wallet, just default to the first wallet
3833
+ const accessToken = await this.privyMethods.getAccessToken();
3834
+ await this.createSession(this.privyMethods.wallets[0].address, accessToken, this.privyMethods.identityToken);
3835
+ setCurrentUser({ address: this.privyMethods.wallets[0].address, provider: this });
3836
+ const session = await WebSessionManager.getSession();
3837
+ sessionAddress = session === null || session === void 0 ? void 0 : session.address;
3838
+ if (!sessionAddress) {
3839
+ throw new Error('No wallet connected or logged in to sign message');
3840
+ }
3841
+ privyWallet = this.privyMethods.wallets[0];
3842
+ }
3843
+ // Use the Privy signMessage hook for Solana wallets
3844
+ // The message needs to be passed as a Uint8Array
3845
+ const messageBytes = getPlatform().textEncode(message);
3846
+ const result = await ((_c = this.privyMethods) === null || _c === void 0 ? void 0 : _c.signMessage({
3847
+ message: messageBytes,
3848
+ wallet: privyWallet,
3849
+ }));
3850
+ // The signature is returned as a Uint8Array, encode it as base58 (standard Solana format)
3851
+ const signatureBytes = (result === null || result === void 0 ? void 0 : result.signature) || result;
3852
+ const bs58 = await import('./index.native-BB7er4-z.esm.js').then(function (n) { return n.a4; });
3853
+ return bs58.default.encode(signatureBytes);
3854
+ }
3855
+ async restoreSession() {
3856
+ const session = await WebSessionManager.getSession();
3857
+ if (session) {
3858
+ return { provider: this, address: session.address };
3859
+ }
3860
+ else {
3861
+ return null;
3862
+ }
3863
+ }
3864
+ async createSession(address, accessToken, idToken) {
3865
+ if (accessToken == null || accessToken == '' || idToken == null || idToken == '') {
3866
+ return;
3867
+ }
3868
+ const createSessionResult = await createSessionWithPrivy(accessToken, address, idToken);
3869
+ await WebSessionManager.storeSession(address, createSessionResult.accessToken, createSessionResult.idToken, createSessionResult.refreshToken);
3870
+ }
3871
+ /**
3872
+ * Waits for a wallet matching the session address to appear in the wallets array.
3873
+ * This handles the timing gap where Privy's embedded wallet (created for email login users)
3874
+ * may not yet be in the useWallets() array when signTransaction is called immediately after login.
3875
+ */
3876
+ async waitForMatchingWallet(sessionAddress, timeoutMs = 10000) {
3877
+ var _a;
3878
+ const startTime = Date.now();
3879
+ while (Date.now() - startTime < timeoutMs) {
3880
+ const wallets = (_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.wallets;
3881
+ if (wallets && wallets.length > 0) {
3882
+ const wallet = wallets.find((w) => w.address === sessionAddress);
3883
+ if (wallet)
3884
+ return wallet;
3885
+ }
3886
+ await new Promise(resolve => setTimeout(resolve, 200));
3887
+ }
3888
+ return null;
3889
+ }
3890
+ async ensureReady({ waitForWallets = false, timeoutMs = 15000 } = {}) {
3891
+ const isReady = () => {
3892
+ var _a, _b;
3893
+ if (!((_a = this.privyMethods) === null || _a === void 0 ? void 0 : _a.ready))
3894
+ return false;
3895
+ if (waitForWallets && !((_b = this.privyMethods) === null || _b === void 0 ? void 0 : _b.walletReady))
3896
+ return false;
3897
+ return true;
3898
+ };
3899
+ if (isReady())
3900
+ return;
3901
+ return new Promise((resolve, reject) => {
3902
+ const startTime = Date.now();
3903
+ const check = () => {
3904
+ if (isReady()) {
3905
+ resolve();
3906
+ }
3907
+ else if (Date.now() - startTime > timeoutMs) {
3908
+ reject(new Error('Login provider failed to initialize. This can happen in incognito mode or when third-party cookies are blocked. Try using a regular browser window.'));
3909
+ }
3910
+ else {
3911
+ setTimeout(check, 100);
3912
+ }
3913
+ };
3914
+ check();
3915
+ });
3916
+ }
3917
+ }
3918
+ PrivyWalletProvider.instance = null;
3919
+
3920
+ export { PrivyWalletProvider };
3921
+ //# sourceMappingURL=privy-wallet-provider-CFuoQYuv.esm.js.map