@n1xyz/nord-ts 0.0.1 → 0.0.4

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 (237) hide show
  1. package/.eslintrc.js +11 -0
  2. package/README.md +148 -65
  3. package/dist/bridge/NordUser.d.ts +78 -0
  4. package/dist/bridge/NordUser.js +196 -0
  5. package/dist/bridge/client.d.ts +150 -0
  6. package/dist/bridge/client.js +394 -0
  7. package/dist/bridge/const.d.ts +23 -0
  8. package/dist/bridge/const.js +47 -0
  9. package/dist/bridge/index.d.ts +5 -0
  10. package/dist/bridge/index.js +23 -0
  11. package/dist/bridge/types.d.ts +118 -0
  12. package/dist/bridge/types.js +16 -0
  13. package/dist/bridge/utils.d.ts +64 -0
  14. package/dist/bridge/utils.js +131 -0
  15. package/dist/client.d.ts +70 -0
  16. package/dist/client.js +129 -0
  17. package/dist/const.d.ts +2 -5
  18. package/dist/const.js +18 -22
  19. package/dist/constants/endpoints.d.ts +65 -0
  20. package/dist/constants/endpoints.js +68 -0
  21. package/dist/gen/common.d.ts +6 -1
  22. package/dist/gen/common.js +19 -9
  23. package/dist/gen/nord.d.ts +75 -17
  24. package/dist/gen/nord.js +987 -423
  25. package/dist/idl/bridge.d.ts +2 -0
  26. package/dist/idl/bridge.js +703 -0
  27. package/dist/index.d.ts +8 -5
  28. package/dist/index.js +18 -2
  29. package/dist/models/account.d.ts +58 -0
  30. package/dist/models/account.js +6 -0
  31. package/dist/models/index.d.ts +8 -0
  32. package/dist/models/index.js +28 -0
  33. package/dist/models/market.d.ts +137 -0
  34. package/dist/models/market.js +6 -0
  35. package/dist/models/order.d.ts +211 -0
  36. package/dist/models/order.js +6 -0
  37. package/dist/models/token.d.ts +50 -0
  38. package/dist/models/token.js +6 -0
  39. package/dist/nord/Nord.d.ts +222 -49
  40. package/dist/nord/Nord.js +290 -278
  41. package/dist/nord/NordError.d.ts +23 -0
  42. package/dist/nord/NordError.js +48 -0
  43. package/dist/nord/NordImpl.d.ts +6 -2
  44. package/dist/nord/NordImpl.js +21 -1
  45. package/dist/nord/NordUser.d.ts +208 -42
  46. package/dist/nord/NordUser.js +389 -157
  47. package/dist/nord/Subscriber.d.ts +37 -0
  48. package/dist/nord/Subscriber.js +29 -0
  49. package/dist/nord/api/actions.d.ts +101 -0
  50. package/dist/nord/api/actions.js +250 -0
  51. package/dist/nord/api/core.d.ts +49 -0
  52. package/dist/nord/api/core.js +121 -0
  53. package/dist/nord/api/index.d.ts +1 -0
  54. package/dist/nord/api/index.js +17 -0
  55. package/dist/nord/api/market.d.ts +36 -0
  56. package/dist/nord/api/market.js +98 -0
  57. package/dist/nord/api/metrics.d.ts +67 -0
  58. package/dist/nord/api/metrics.js +132 -0
  59. package/dist/nord/api/orderFunctions.d.ts +168 -0
  60. package/dist/nord/api/orderFunctions.js +133 -0
  61. package/dist/nord/api/queries.d.ts +81 -0
  62. package/dist/nord/api/queries.js +187 -0
  63. package/dist/nord/client/Nord.d.ts +335 -0
  64. package/dist/nord/client/Nord.js +532 -0
  65. package/dist/nord/client/NordUser.d.ts +320 -0
  66. package/dist/nord/client/NordUser.js +701 -0
  67. package/dist/nord/core.d.ts +48 -0
  68. package/dist/nord/core.js +97 -0
  69. package/dist/nord/index.d.ts +9 -2
  70. package/dist/nord/index.js +30 -6
  71. package/dist/nord/market.d.ts +36 -0
  72. package/dist/nord/market.js +90 -0
  73. package/dist/nord/metrics.d.ts +67 -0
  74. package/dist/nord/metrics.js +124 -0
  75. package/dist/nord/models/Subscriber.d.ts +37 -0
  76. package/dist/nord/models/Subscriber.js +29 -0
  77. package/dist/nord/queries.d.ts +81 -0
  78. package/dist/nord/queries.js +181 -0
  79. package/dist/nord/types.d.ts +88 -0
  80. package/dist/nord/types.js +2 -0
  81. package/dist/nord/utils/NordError.d.ts +35 -0
  82. package/dist/nord/utils/NordError.js +46 -0
  83. package/dist/nord/websocket.d.ts +49 -0
  84. package/dist/nord/websocket.js +107 -0
  85. package/dist/operations/account.d.ts +58 -0
  86. package/dist/operations/account.js +112 -0
  87. package/dist/operations/market.d.ts +65 -0
  88. package/dist/operations/market.js +131 -0
  89. package/dist/operations/orders.d.ts +57 -0
  90. package/dist/operations/orders.js +129 -0
  91. package/dist/solana/NordUser.d.ts +78 -0
  92. package/dist/solana/NordUser.js +196 -0
  93. package/dist/solana/client.d.ts +139 -0
  94. package/dist/solana/client.js +360 -0
  95. package/dist/solana/const.d.ts +23 -0
  96. package/dist/solana/const.js +47 -0
  97. package/dist/solana/index.d.ts +5 -0
  98. package/dist/solana/index.js +23 -0
  99. package/dist/solana/types.d.ts +118 -0
  100. package/dist/solana/types.js +16 -0
  101. package/dist/solana/utils.d.ts +64 -0
  102. package/dist/solana/utils.js +131 -0
  103. package/dist/types/api.d.ts +152 -0
  104. package/dist/types/api.js +6 -0
  105. package/dist/types/config.d.ts +34 -0
  106. package/dist/types/config.js +6 -0
  107. package/dist/types.d.ts +144 -87
  108. package/dist/types.js +13 -2
  109. package/dist/utils/errors.d.ts +96 -0
  110. package/dist/utils/errors.js +132 -0
  111. package/dist/utils/http.d.ts +35 -0
  112. package/dist/utils/http.js +105 -0
  113. package/dist/utils.d.ts +14 -5
  114. package/dist/utils.js +26 -7
  115. package/dist/websocket/NordWebSocketClient.d.ts +71 -0
  116. package/dist/websocket/NordWebSocketClient.js +343 -0
  117. package/dist/websocket/client.d.ts +93 -0
  118. package/dist/websocket/client.js +222 -0
  119. package/dist/websocket/events.d.ts +19 -0
  120. package/dist/websocket/events.js +2 -0
  121. package/dist/websocket/index.d.ts +2 -0
  122. package/dist/websocket/index.js +5 -0
  123. package/dist/websocket.d.ts +55 -0
  124. package/dist/websocket.js +211 -0
  125. package/docs/assets/navigation.js +1 -1
  126. package/docs/assets/search.js +1 -1
  127. package/docs/classes/Nord.html +2 -15
  128. package/docs/classes/NordUser.html +4 -4
  129. package/docs/enums/FillMode.html +2 -2
  130. package/docs/enums/KeyType.html +2 -2
  131. package/docs/enums/PeakTpsPeriodUnit.html +2 -2
  132. package/docs/enums/Side.html +2 -2
  133. package/docs/functions/assert.html +1 -1
  134. package/docs/functions/bigIntToProtoU128.html +1 -1
  135. package/docs/functions/checkPubKeyLength.html +1 -1
  136. package/docs/functions/checkedFetch.html +1 -1
  137. package/docs/functions/decodeLengthDelimited.html +1 -1
  138. package/docs/functions/encodeLengthDelimited.html +1 -1
  139. package/docs/functions/fillModeToProtoFillMode.html +1 -1
  140. package/docs/functions/findMarket.html +1 -1
  141. package/docs/functions/findToken.html +1 -1
  142. package/docs/functions/makeWalletSignFn.html +1 -1
  143. package/docs/functions/optExpect.html +1 -1
  144. package/docs/functions/optMap.html +1 -1
  145. package/docs/functions/optUnwrap.html +1 -1
  146. package/docs/functions/panic.html +1 -1
  147. package/docs/functions/signAction.html +1 -1
  148. package/docs/functions/toScaledU128.html +1 -1
  149. package/docs/functions/toScaledU64.html +1 -1
  150. package/docs/interfaces/Account.html +2 -2
  151. package/docs/interfaces/ActionInfo.html +2 -2
  152. package/docs/interfaces/ActionQuery.html +2 -2
  153. package/docs/interfaces/ActionResponse.html +2 -2
  154. package/docs/interfaces/ActionsExtendedInfo.html +2 -2
  155. package/docs/interfaces/ActionsQuery.html +2 -2
  156. package/docs/interfaces/ActionsResponse.html +2 -2
  157. package/docs/interfaces/AggregateMetrics.html +2 -2
  158. package/docs/interfaces/BlockQuery.html +2 -2
  159. package/docs/interfaces/BlockResponse.html +2 -2
  160. package/docs/interfaces/BlockSummary.html +2 -2
  161. package/docs/interfaces/BlockSummaryResponse.html +2 -2
  162. package/docs/interfaces/DeltaEvent.html +2 -2
  163. package/docs/interfaces/ERC20TokenInfo.html +2 -2
  164. package/docs/interfaces/Info.html +2 -2
  165. package/docs/interfaces/Market.html +2 -2
  166. package/docs/interfaces/MarketStats.html +2 -2
  167. package/docs/interfaces/MarketsStatsResponse.html +2 -2
  168. package/docs/interfaces/NordConfig.html +2 -2
  169. package/docs/interfaces/Order.html +2 -2
  170. package/docs/interfaces/OrderInfo.html +2 -2
  171. package/docs/interfaces/PerpMarketStats.html +2 -2
  172. package/docs/interfaces/RollmanActionExtendedInfo.html +2 -2
  173. package/docs/interfaces/RollmanActionInfo.html +2 -2
  174. package/docs/interfaces/RollmanActionResponse.html +2 -2
  175. package/docs/interfaces/RollmanActionsResponse.html +2 -2
  176. package/docs/interfaces/RollmanBlockResponse.html +2 -2
  177. package/docs/interfaces/SubscriberConfig.html +2 -2
  178. package/docs/interfaces/Token.html +2 -2
  179. package/docs/interfaces/Trade.html +2 -2
  180. package/docs/interfaces/Trades.html +2 -2
  181. package/docs/modules.html +0 -7
  182. package/docs/types/BigIntValue.html +1 -1
  183. package/docs/variables/DEBUG_KEYS.html +1 -1
  184. package/docs/variables/DEFAULT_FUNDING_AMOUNTS.html +1 -1
  185. package/docs/variables/DEV_CONTRACT_ADDRESS.html +1 -1
  186. package/docs/variables/DEV_TOKEN_INFOS.html +1 -1
  187. package/docs/variables/DEV_URL.html +1 -1
  188. package/docs/variables/ERC20_ABI.html +1 -1
  189. package/docs/variables/EVM_DEV_URL.html +1 -1
  190. package/docs/variables/FAUCET_PRIVATE_ADDRESS.html +1 -1
  191. package/docs/variables/MAX_BUFFER_LEN.html +1 -1
  192. package/docs/variables/NORD_GETTERS_FACET_ABI.html +1 -1
  193. package/docs/variables/NORD_RAMP_FACET_ABI.html +1 -1
  194. package/docs/variables/SESSION_TTL.html +1 -1
  195. package/docs/variables/WEBSERVER_DEV_URL.html +1 -1
  196. package/docs/variables/ZERO_DECIMAL.html +1 -1
  197. package/package.json +10 -12
  198. package/src/bridge/client.ts +487 -0
  199. package/src/bridge/const.ts +53 -0
  200. package/src/bridge/index.ts +7 -0
  201. package/src/bridge/types.ts +127 -0
  202. package/src/bridge/utils.ts +140 -0
  203. package/src/const.ts +20 -25
  204. package/src/gen/common.ts +27 -10
  205. package/src/gen/nord.ts +1044 -483
  206. package/src/idl/bridge.ts +702 -0
  207. package/src/index.ts +24 -5
  208. package/src/nord/{actions.ts → api/actions.ts} +33 -37
  209. package/src/nord/api/core.ts +130 -0
  210. package/src/nord/api/market.ts +125 -0
  211. package/src/nord/api/metrics.ts +154 -0
  212. package/src/nord/api/queries.ts +236 -0
  213. package/src/nord/client/Nord.ts +652 -0
  214. package/src/nord/client/NordUser.ts +1105 -0
  215. package/src/nord/index.ts +16 -2
  216. package/src/nord/models/Subscriber.ts +57 -0
  217. package/src/nord/utils/NordError.ts +72 -0
  218. package/src/types.ts +170 -99
  219. package/src/utils.ts +40 -19
  220. package/src/websocket/NordWebSocketClient.ts +432 -0
  221. package/src/websocket/events.ts +31 -0
  222. package/src/websocket/index.ts +2 -0
  223. package/tests/utils.spec.ts +24 -24
  224. package/docs/classes/Subscriber.html +0 -6
  225. package/docs/functions/createWebSocketSubscription.html +0 -12
  226. package/docs/interfaces/OrderbookOrder.html +0 -6
  227. package/docs/interfaces/OrderbookResponse.html +0 -10
  228. package/docs/interfaces/TradeInfo.html +0 -20
  229. package/docs/interfaces/TradesQueryParams.html +0 -10
  230. package/docs/interfaces/TradesResponse.html +0 -12
  231. package/src/abis/ERC20_ABI.ts +0 -310
  232. package/src/abis/NORD_GETTERS_FACET_ABI.ts +0 -192
  233. package/src/abis/NORD_RAMP_FACET_ABI.ts +0 -141
  234. package/src/abis/index.ts +0 -3
  235. package/src/nord/Nord.ts +0 -504
  236. package/src/nord/NordImpl.ts +0 -8
  237. package/src/nord/NordUser.ts +0 -469
@@ -0,0 +1,487 @@
1
+ import * as anchor from '@coral-xyz/anchor';
2
+ import { AnchorProvider, Idl } from '@coral-xyz/anchor';
3
+ import {
4
+ createAssociatedTokenAccountInstruction,
5
+ getAssociatedTokenAddress,
6
+ TOKEN_2022_PROGRAM_ID,
7
+ } from '@solana/spl-token';
8
+ import {
9
+ Connection,
10
+ Keypair,
11
+ PublicKey,
12
+ SystemProgram,
13
+ Transaction,
14
+ } from '@solana/web3.js';
15
+ import {
16
+ BlockFacts,
17
+ DepositSplParams,
18
+ PdaSeedType,
19
+ SolanaBridgeConfig,
20
+ WithdrawalParams,
21
+ } from './types';
22
+
23
+ // Import the BRIDGE_IDL
24
+ import { BRIDGE_IDL } from '../idl/bridge';
25
+
26
+ /**
27
+ * Solana Bridge Client for interacting with the bridge program
28
+ */
29
+ export class SolanaBridgeClient {
30
+ /** Anchor program instance */
31
+ program: any;
32
+ /** Solana connection */
33
+ connection: Connection;
34
+ /** Program ID */
35
+ programId: PublicKey;
36
+ /** Configuration */
37
+ config: SolanaBridgeConfig;
38
+ /** Anchor provider */
39
+ provider: AnchorProvider;
40
+
41
+ /**
42
+ * Create a new Solana Bridge Client
43
+ *
44
+ * @param config Bridge configuration
45
+ * @param wallet Anchor wallet for signing transactions
46
+ */
47
+ constructor(config: SolanaBridgeConfig, wallet: anchor.Wallet) {
48
+ this.config = config;
49
+ this.connection = new Connection(config.rpcUrl, {
50
+ commitment: config.commitment,
51
+ });
52
+ this.programId = new PublicKey(config.programId);
53
+
54
+ // Create the provider
55
+ const provider = new AnchorProvider(this.connection, wallet, {
56
+ commitment: config.commitment,
57
+ skipPreflight: true, // Skip simulation
58
+ });
59
+
60
+ // Set the provider globally
61
+ anchor.setProvider(provider);
62
+
63
+ // Store the provider
64
+ this.provider = provider;
65
+
66
+ this.program = new anchor.Program(
67
+ { ...(BRIDGE_IDL as Idl), address: config.programId },
68
+ provider,
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Derive a PDA (Program Derived Address) for the given seeds
74
+ *
75
+ * @param type PDA seed type
76
+ * @param seeds Additional seeds
77
+ * @returns [PDA, bump]
78
+ */
79
+ async findPda(
80
+ type: PdaSeedType,
81
+ ...seeds: (Buffer | PublicKey | string | number)[]
82
+ ): Promise<[PublicKey, number]> {
83
+ const seedBuffers = [
84
+ Buffer.from(type),
85
+ ...seeds.map((seed) => {
86
+ if (seed instanceof PublicKey) {
87
+ return seed.toBuffer();
88
+ } else if (typeof seed === 'string') {
89
+ return Buffer.from(seed);
90
+ } else if (typeof seed === 'number') {
91
+ // Convert number to little-endian byte array (8 bytes for u64)
92
+ const buffer = Buffer.alloc(8);
93
+ buffer.writeBigUInt64LE(BigInt(seed), 0);
94
+ return buffer;
95
+ }
96
+ return seed;
97
+ }),
98
+ ];
99
+
100
+ return PublicKey.findProgramAddressSync(seedBuffers, this.programId);
101
+ }
102
+
103
+ /**
104
+ * Find the contract storage PDA
105
+ *
106
+ * @returns [PDA, bump]
107
+ */
108
+ async findContractStoragePda(): Promise<[PublicKey, number]> {
109
+ return this.findPda(PdaSeedType.ContractStorage);
110
+ }
111
+
112
+ /**
113
+ * Find the asset whitelisted PDA for a token mint
114
+ *
115
+ * @param mint Token mint address
116
+ * @returns [PDA, bump]
117
+ */
118
+ async findAssetWhitelistedPda(mint: PublicKey): Promise<[PublicKey, number]> {
119
+ return this.findPda(PdaSeedType.AssetWhitelisted, mint);
120
+ }
121
+
122
+ /**
123
+ * Find the deposit storage PDA for a deposit index
124
+ *
125
+ * @param depositIndex Deposit index
126
+ * @returns [PDA, bump]
127
+ */
128
+ async findDepositStoragePda(
129
+ depositIndex: number,
130
+ ): Promise<[PublicKey, number]> {
131
+ return this.findPda(PdaSeedType.DepositStorage, depositIndex);
132
+ }
133
+
134
+ /**
135
+ * Find the block storage PDA for a block ID
136
+ *
137
+ * @param blockId Block ID
138
+ * @returns [PDA, bump]
139
+ */
140
+ async findBlockStoragePda(blockId: number): Promise<[PublicKey, number]> {
141
+ return this.findPda(PdaSeedType.BlockStorage, blockId);
142
+ }
143
+
144
+ /**
145
+ * Find the withdrawal nullifier PDA
146
+ *
147
+ * @param blockId Block ID
148
+ * @param leafIndex Leaf index
149
+ * @returns [PDA, bump]
150
+ */
151
+ async findWithdrawalNullifierPda(
152
+ blockId: number,
153
+ leafIndex: number,
154
+ ): Promise<[PublicKey, number]> {
155
+ return this.findPda(PdaSeedType.WithdrawalNullifier, blockId, leafIndex);
156
+ }
157
+
158
+ /**
159
+ * Find the authority PDA
160
+ *
161
+ * @returns [PDA, bump]
162
+ */
163
+ async findAuthorityPda(): Promise<[PublicKey, number]> {
164
+ return this.findPda(PdaSeedType.Authority);
165
+ }
166
+
167
+ /**
168
+ * Helper method to sign and send a transaction
169
+ *
170
+ * @param transaction Transaction to sign and send
171
+ * @param signers Additional signers (beyond the provider's wallet)
172
+ * @returns Transaction signature
173
+ */
174
+ private async signAndSendTransaction(
175
+ transaction: Transaction,
176
+ signers: Keypair[] = [],
177
+ ): Promise<string> {
178
+ // Use the provider to sign and send the transaction with skipPreflight
179
+ const txSignature = await this.provider.sendAndConfirm(
180
+ transaction,
181
+ signers,
182
+ {
183
+ skipPreflight: true,
184
+ },
185
+ );
186
+ return txSignature;
187
+ }
188
+
189
+ /**
190
+ * Deposit SPL tokens to the bridge
191
+ *
192
+ * @param params Deposit parameters
193
+ * @param signer Signer keypair
194
+ * @returns Transaction signature
195
+ */
196
+ async depositSpl(params: DepositSplParams): Promise<string> {
197
+ const [contractStorage] = await this.findContractStoragePda();
198
+ const [assetWhitelisted] = await this.findAssetWhitelistedPda(params.mint);
199
+
200
+ // Get the last deposit index from contract storage
201
+ const contractStorageAccount =
202
+ await this.program.account.contractStorage.fetch(contractStorage);
203
+ const lastDepositIndex = contractStorageAccount.lastDepositIndex.toNumber();
204
+
205
+ // Find the deposit PDA for this deposit
206
+ const [deposit] = await this.findDepositStoragePda(lastDepositIndex + 1);
207
+
208
+ // Find the previous deposit PDA if it exists
209
+ let prevDeposit: PublicKey | undefined = undefined;
210
+ if (lastDepositIndex > 0) {
211
+ const [prevDepositPda] =
212
+ await this.findDepositStoragePda(lastDepositIndex);
213
+ prevDeposit = prevDepositPda;
214
+ }
215
+
216
+ // Build the transaction
217
+ const accounts: any = {
218
+ depositor: this.provider.wallet.publicKey,
219
+ deposit,
220
+ assetWhitelisted,
221
+ contractStorage,
222
+ fromAccount: params.fromAccount,
223
+ toAccount: params.toAccount,
224
+ tokenProgram: TOKEN_2022_PROGRAM_ID,
225
+ systemProgram: SystemProgram.programId,
226
+ };
227
+
228
+ // Create the transaction
229
+ const tx = await this.program.methods
230
+ .depositSpl(params.amount)
231
+ .accounts({ ...accounts, prevDeposit: prevDeposit })
232
+ .transaction();
233
+
234
+ // Check if toAccount is initialized and add preinstruction if needed
235
+ try {
236
+ await this.connection.getTokenAccountBalance(params.toAccount);
237
+ } catch (error) {
238
+ // Account doesn't exist, add instruction to create it
239
+ // Get the authority PDA which is the owner of the toAccount
240
+ const [authority] = await this.findAuthorityPda();
241
+
242
+ const createTokenAccountIx = createAssociatedTokenAccountInstruction(
243
+ this.provider.wallet.publicKey, // payer
244
+ params.toAccount, // associated token account address
245
+ authority, // owner of the token account
246
+ params.mint, // token mint
247
+ TOKEN_2022_PROGRAM_ID,
248
+ );
249
+
250
+ // Add the instruction to the beginning of the transaction
251
+ tx.instructions.unshift(createTokenAccountIx);
252
+ }
253
+
254
+ // Sign and send the transaction using our helper method
255
+ return await this.signAndSendTransaction(tx);
256
+ }
257
+
258
+ /**
259
+ * Withdraw tokens from the bridge
260
+ *
261
+ * @param params Withdrawal parameters
262
+ * @param signer Signer keypair
263
+ * @returns Transaction signature
264
+ */
265
+ async withdraw(params: WithdrawalParams, signer: Keypair): Promise<string> {
266
+ const [stateUpdate] = await this.findBlockStoragePda(
267
+ params.claim.blockId.toNumber(),
268
+ );
269
+ const [withdrawalNullifier] = await this.findWithdrawalNullifierPda(
270
+ params.claim.blockId.toNumber(),
271
+ params.claim.leafIndex.toNumber(),
272
+ );
273
+ const [authority] = await this.findAuthorityPda();
274
+
275
+ // Build the transaction
276
+ const tx = await this.program.methods
277
+ .withdraw(params.claim)
278
+ .accounts({
279
+ payer: signer.publicKey,
280
+ stateUpdate,
281
+ withdrawalNullifier,
282
+ fromAccount: params.fromAccount,
283
+ toAccount: params.toAccount,
284
+ authority,
285
+ tokenProgram: TOKEN_2022_PROGRAM_ID,
286
+ systemProgram: SystemProgram.programId,
287
+ })
288
+ .transaction();
289
+
290
+ // Sign and send the transaction using our helper method
291
+ return await this.signAndSendTransaction(tx, [signer]);
292
+ }
293
+
294
+ /**
295
+ * Whitelist an asset (token) for use with the bridge
296
+ *
297
+ * @param mint Token mint address
298
+ * @param signer Operator keypair
299
+ * @returns Transaction signature
300
+ */
301
+ async whitelistAsset(mint: PublicKey, signer: Keypair): Promise<string> {
302
+ const [contractStorage] = await this.findContractStoragePda();
303
+ const [assetWhitelisted] = await this.findAssetWhitelistedPda(mint);
304
+
305
+ // Build the transaction
306
+ const tx = await this.program.methods
307
+ .whitelistAsset(mint)
308
+ .accounts({
309
+ operator: signer.publicKey,
310
+ contractStorage,
311
+ assetWhitelisted,
312
+ systemProgram: SystemProgram.programId,
313
+ })
314
+ .transaction();
315
+
316
+ // Sign and send the transaction using our helper method
317
+ return await this.signAndSendTransaction(tx, [signer]);
318
+ }
319
+
320
+ /**
321
+ * Propose a new block
322
+ *
323
+ * @param facts Block facts
324
+ * @param signer Operator keypair
325
+ * @returns Transaction signature
326
+ */
327
+ async proposeBlock(facts: BlockFacts, signer: Keypair): Promise<string> {
328
+ const [contractStorage] = await this.findContractStoragePda();
329
+
330
+ // Get the last block ID from contract storage
331
+ const contractStorageAccount =
332
+ await this.program.account.contractStorage.fetch(contractStorage);
333
+ const [block] = await this.findBlockStoragePda(
334
+ contractStorageAccount.lastBlockId.toNumber() + 1,
335
+ );
336
+
337
+ // Find the last deposit PDA
338
+ const [lastDeposit] = await this.findDepositStoragePda(
339
+ facts.nextStateFacts.lastDepositIndex.toNumber(),
340
+ );
341
+
342
+ // Find the DA fact state
343
+ const daFactState = PublicKey.findProgramAddressSync(
344
+ [Buffer.from(PdaSeedType.DaFactStorage), facts.daCommitment],
345
+ this.programId,
346
+ )[0];
347
+
348
+ // Build the transaction
349
+ const tx = await this.program.methods
350
+ .proposeBlock(facts)
351
+ .accounts({
352
+ operator: signer.publicKey,
353
+ block,
354
+ lastDeposit,
355
+ daFactState,
356
+ contractStorage,
357
+ systemProgram: SystemProgram.programId,
358
+ })
359
+ .transaction();
360
+
361
+ // Sign and send the transaction using our helper method
362
+ return await this.signAndSendTransaction(tx, [signer]);
363
+ }
364
+
365
+ /**
366
+ * Finalize a block
367
+ *
368
+ * @param blockId Block ID
369
+ * @param stateUpdateId State update ID
370
+ * @param signer Payer keypair
371
+ * @returns Transaction signature
372
+ */
373
+ async finalizeBlock(
374
+ blockId: number,
375
+ stateUpdateId: number,
376
+ signer: Keypair,
377
+ ): Promise<string> {
378
+ const [contractStorage] = await this.findContractStoragePda();
379
+ const [block] = await this.findBlockStoragePda(blockId);
380
+
381
+ // Build the transaction
382
+ const tx = await this.program.methods
383
+ .finalizeBlock(new anchor.BN(stateUpdateId))
384
+ .accounts({
385
+ payer: signer.publicKey,
386
+ block,
387
+ contractStorage,
388
+ systemProgram: SystemProgram.programId,
389
+ })
390
+ .transaction();
391
+
392
+ // Sign and send the transaction using our helper method
393
+ return await this.signAndSendTransaction(tx, [signer]);
394
+ }
395
+
396
+ /**
397
+ * Finalize a DA fact
398
+ *
399
+ * @param fact DA fact (32-byte array)
400
+ * @param signer Payer keypair
401
+ * @returns Transaction signature
402
+ */
403
+ async finalizeDaFact(fact: Buffer, signer: Keypair): Promise<string> {
404
+ const factStateStorage = PublicKey.findProgramAddressSync(
405
+ [Buffer.from(PdaSeedType.DaFactStorage), fact],
406
+ this.programId,
407
+ )[0];
408
+
409
+ // Build the transaction
410
+ const tx = await this.program.methods
411
+ .finalizeDaFact(Array.from(fact))
412
+ .accounts({
413
+ payer: signer.publicKey,
414
+ factStateStorage,
415
+ systemProgram: SystemProgram.programId,
416
+ })
417
+ .transaction();
418
+
419
+ // Sign and send the transaction using our helper method
420
+ return await this.signAndSendTransaction(tx, [signer]);
421
+ }
422
+
423
+ /**
424
+ * Initialize the bridge contract
425
+ *
426
+ * @param operator Operator public key
427
+ * @param initialAppStateCommitment Initial app state commitment (32-byte array)
428
+ * @param signer Payer keypair
429
+ * @returns Transaction signature
430
+ */
431
+ async initialize(
432
+ operator: PublicKey,
433
+ initialAppStateCommitment: Buffer,
434
+ signer: Keypair,
435
+ ): Promise<string> {
436
+ const [contractStorage] = await this.findContractStoragePda();
437
+
438
+ // Build the transaction
439
+ const tx = await this.program.methods
440
+ .initialize(operator, Array.from(initialAppStateCommitment))
441
+ .accounts({
442
+ payer: signer.publicKey,
443
+ program: this.programId,
444
+ contractStorage,
445
+ systemProgram: SystemProgram.programId,
446
+ })
447
+ .transaction();
448
+
449
+ // Sign and send the transaction using our helper method
450
+ return await this.signAndSendTransaction(tx, [signer]);
451
+ }
452
+
453
+ /**
454
+ * Create an associated token account if it doesn't exist
455
+ *
456
+ * @param mint Token mint
457
+ * @param owner Account owner
458
+ * @param payer Transaction payer
459
+ * @returns Associated token account address
460
+ */
461
+ async createTokenAccountIfNeeded(
462
+ mint: PublicKey,
463
+ owner: PublicKey,
464
+ payer: Keypair,
465
+ ): Promise<PublicKey> {
466
+ const associatedTokenAddress = await getAssociatedTokenAddress(mint, owner);
467
+
468
+ try {
469
+ await this.connection.getTokenAccountBalance(associatedTokenAddress);
470
+ } catch (error) {
471
+ // Account doesn't exist, create it
472
+ const transaction = new Transaction().add(
473
+ createAssociatedTokenAccountInstruction(
474
+ payer.publicKey,
475
+ associatedTokenAddress,
476
+ owner,
477
+ mint,
478
+ ),
479
+ );
480
+
481
+ // Sign and send the transaction using our helper method
482
+ await this.signAndSendTransaction(transaction, [payer]);
483
+ }
484
+
485
+ return associatedTokenAddress;
486
+ }
487
+ }
@@ -0,0 +1,53 @@
1
+ import { SPLTokenInfo } from './types';
2
+ import { Commitment } from '@solana/web3.js';
3
+
4
+ // Solana RPC endpoints
5
+ export const SOLANA_MAINNET_URL = 'https://api.mainnet-beta.solana.com';
6
+ export const SOLANA_DEVNET_URL = 'https://api.devnet.solana.com';
7
+ export const SOLANA_TESTNET_URL = 'https://api.testnet.solana.com';
8
+ export const SOLANA_LOCALNET_URL = 'http://localhost:8899';
9
+
10
+ // Default commitment level
11
+ export const DEFAULT_COMMITMENT: Commitment = 'confirmed';
12
+
13
+ // Webserver configuration
14
+ const WEBSERVER_PORT = '80';
15
+ export const DEV_URL = 'http://localhost';
16
+ export const WEBSERVER_DEV_URL = DEV_URL + ':' + WEBSERVER_PORT;
17
+
18
+ // Program ID (will be supplied externally)
19
+ export const SOLANA_PROGRAM_ID = 'CVDFLCAjXhVWiPXH9nTCTpCgVzmDVoiPzNJYuccr1dqB';
20
+
21
+ // Sample token information for development
22
+ export const DEV_TOKEN_INFOS: SPLTokenInfo[] = [
23
+ {
24
+ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC on devnet
25
+ precision: 6,
26
+ tokenId: 0,
27
+ name: 'usdc',
28
+ },
29
+ {
30
+ mint: 'So11111111111111111111111111111111111111112', // Wrapped SOL
31
+ precision: 9,
32
+ tokenId: 1,
33
+ name: 'sol',
34
+ },
35
+ ];
36
+
37
+ // Default funding amounts for development
38
+ export const DEFAULT_FUNDING_AMOUNTS: { [key: string]: [string, number] } = {
39
+ SOL: ['0.2', 9],
40
+ // USDC mint address
41
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: ['10000', 6],
42
+ };
43
+
44
+ // PDA seed constants
45
+ export const PDA_SEEDS = {
46
+ CONTRACT_STORAGE: 'contract_storage',
47
+ ASSET_WHITELISTED: 'asset_whitelisted',
48
+ DEPOSIT_STORAGE: 'deposit_storage',
49
+ BLOCK_STORAGE: 'block_storage',
50
+ WITHDRAWAL_NULLIFIER: 'withdrawal_nullifier',
51
+ AUTHORITY: 'authority',
52
+ DA_FACT_STORAGE: 'da_fact_storage',
53
+ };
@@ -0,0 +1,7 @@
1
+ export * from './client';
2
+ export * from './types';
3
+ export * from './utils';
4
+
5
+ // Re-export the IDL for convenience
6
+ import { BRIDGE_IDL } from '../idl/bridge';
7
+ export { BRIDGE_IDL };
@@ -0,0 +1,127 @@
1
+ import { PublicKey } from '@solana/web3.js';
2
+ import { BN } from '@coral-xyz/anchor';
3
+
4
+ /**
5
+ * Configuration for Solana bridge
6
+ */
7
+ export interface SolanaBridgeConfig {
8
+ /** Solana RPC URL */
9
+ rpcUrl: string;
10
+ /** Program ID for the bridge program */
11
+ programId: string;
12
+ /** Commitment level for transactions */
13
+ commitment: 'processed' | 'confirmed' | 'finalized';
14
+ /** Token information for supported SPL tokens */
15
+ tokenInfos: SPLTokenInfo[];
16
+ }
17
+
18
+ /**
19
+ * Information about an SPL token
20
+ */
21
+ export interface SPLTokenInfo {
22
+ /** Token mint address */
23
+ mint: string;
24
+ /** Token decimals */
25
+ precision: number;
26
+ /** Token ID in the Layer-N system */
27
+ tokenId: number;
28
+ /** Token name */
29
+ name: string;
30
+ }
31
+
32
+ /**
33
+ * Parameters for depositing SPL tokens
34
+ */
35
+ export interface DepositSplParams {
36
+ /** Amount to deposit (in token's smallest unit) */
37
+ amount: BN;
38
+ /** Mint address of the token to deposit */
39
+ mint: PublicKey;
40
+ /** User's token account to deposit from */
41
+ fromAccount: PublicKey;
42
+ /** Bridge's token account to deposit to */
43
+ toAccount: PublicKey;
44
+ }
45
+
46
+ /**
47
+ * Parameters for withdrawing tokens
48
+ */
49
+ export interface WithdrawalParams {
50
+ /** Withdrawal claim data */
51
+ claim: WithdrawalClaim;
52
+ /** User's token account to receive tokens */
53
+ toAccount: PublicKey;
54
+ /** Bridge's token account to withdraw from */
55
+ fromAccount: PublicKey;
56
+ }
57
+
58
+ /**
59
+ * Withdrawal claim data
60
+ */
61
+ export interface WithdrawalClaim {
62
+ /** Block ID containing the withdrawal */
63
+ blockId: BN;
64
+ /** Leaf index in the Merkle tree */
65
+ leafIndex: BN;
66
+ /** Amount to withdraw */
67
+ amount: BN;
68
+ /** Recipient address */
69
+ recipient: PublicKey;
70
+ /** Token mint address */
71
+ mint: PublicKey;
72
+ /** Merkle proof for the withdrawal */
73
+ proof: Buffer[];
74
+ }
75
+
76
+ /**
77
+ * Block facts data structure
78
+ */
79
+ export interface BlockFacts {
80
+ /** Previous state facts */
81
+ prevStateFacts: StateFacts;
82
+ /** Next state facts */
83
+ nextStateFacts: StateFacts;
84
+ /** Data availability commitment */
85
+ daCommitment: Buffer;
86
+ /** Withdrawal Merkle root */
87
+ withdrawalRoot: Buffer;
88
+ }
89
+
90
+ /**
91
+ * State facts data structure
92
+ */
93
+ export interface StateFacts {
94
+ /** Application state commitment */
95
+ appStateCommitment: Buffer;
96
+ /** Deposit root */
97
+ depositRoot: Buffer;
98
+ /** Last deposit index */
99
+ lastDepositIndex: BN;
100
+ /** Last action ID */
101
+ lastActionId: BN;
102
+ }
103
+
104
+ /**
105
+ * Transfer parameters
106
+ */
107
+ export interface TransferParams {
108
+ /** User public key */
109
+ user: PublicKey;
110
+ /** Token mint */
111
+ mint: PublicKey;
112
+ /** Amount to transfer */
113
+ amount: BN;
114
+ }
115
+
116
+ /**
117
+ * PDA seed types
118
+ */
119
+ export enum PdaSeedType {
120
+ ContractStorage = 'contract_storage',
121
+ AssetWhitelisted = 'asset_whitelisted',
122
+ DepositStorage = 'deposit_storage',
123
+ BlockStorage = 'block_storage',
124
+ WithdrawalNullifier = 'withdrawal_nullifier',
125
+ Authority = 'authority',
126
+ DaFactStorage = 'da_fact_storage',
127
+ }