@xchainjs/xchain-solana 0.0.1

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.
@@ -0,0 +1,502 @@
1
+ import { mplTokenMetadata, fetchAllDigitalAsset, fetchDigitalAsset } from '@metaplex-foundation/mpl-token-metadata';
2
+ import { publicKey } from '@metaplex-foundation/umi';
3
+ import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
4
+ import { isAddress } from '@solana/addresses';
5
+ import { TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, getAccount, createTransferInstruction, TokenAccountNotFoundError, TokenInvalidAccountOwnerError, getOrCreateAssociatedTokenAccount } from '@solana/spl-token';
6
+ import { Connection, clusterApiUrl, Keypair, PublicKey, Transaction, SystemProgram, TransactionInstruction, ComputeBudgetProgram, SendTransactionError } from '@solana/web3.js';
7
+ import { ExplorerProvider, Network, BaseXChainClient, FeeType, FeeOption, TxType } from '@xchainjs/xchain-client';
8
+ import { getSeed } from '@xchainjs/xchain-crypto';
9
+ import { AssetType, baseAmount, assetFromStringEx, eqAsset, getContractAddressFromAsset, assetToBase, assetAmount } from '@xchainjs/xchain-util';
10
+ import bs58 from 'bs58';
11
+ import { HDKey } from 'micro-ed25519-hdkey';
12
+
13
+ /******************************************************************************
14
+ Copyright (c) Microsoft Corporation.
15
+
16
+ Permission to use, copy, modify, and/or distribute this software for any
17
+ purpose with or without fee is hereby granted.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
+ PERFORMANCE OF THIS SOFTWARE.
26
+ ***************************************************************************** */
27
+
28
+ function __awaiter(thisArg, _arguments, P, generator) {
29
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
+ return new (P || (P = Promise))(function (resolve, reject) {
31
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
35
+ });
36
+ }
37
+
38
+ /**
39
+ * Solana chain symbol
40
+ */
41
+ const SOLChain = 'SOL';
42
+ /**
43
+ * Solana native asset decimals
44
+ */
45
+ const SOL_DECIMALS = 9;
46
+ /**
47
+ * Solana native asset
48
+ */
49
+ const SOLAsset = {
50
+ chain: 'SOL',
51
+ ticker: 'SOL',
52
+ symbol: 'SOL',
53
+ type: AssetType.NATIVE,
54
+ };
55
+ const mainnetExplorer = new ExplorerProvider('https://explorer.solana.com/', 'https://explorer.solana.com/address/%%ADDRESS%%', 'https://explorer.solana.com/tx/%%TX_ID%%');
56
+ const defaultSolanaParams = {
57
+ network: Network.Mainnet,
58
+ rootDerivationPaths: {
59
+ [Network.Mainnet]: "m/44'/501'/",
60
+ [Network.Testnet]: "m/44'/501'/",
61
+ [Network.Stagenet]: "m/44'/501'/",
62
+ },
63
+ explorerProviders: {
64
+ [Network.Mainnet]: mainnetExplorer,
65
+ [Network.Testnet]: new ExplorerProvider('https://explorer.solana.com/?cluster=testnet', 'https://explorer.solana.com/address/%%ADDRESS%%?cluster=testnet', 'https://explorer.solana.com/tx/%%TX_ID%%?cluster=testnet'),
66
+ [Network.Stagenet]: mainnetExplorer,
67
+ },
68
+ };
69
+
70
+ const getSolanaNetwork = (network) => {
71
+ const networkMap = {
72
+ [Network.Mainnet]: 'mainnet-beta',
73
+ [Network.Stagenet]: 'mainnet-beta',
74
+ [Network.Testnet]: 'testnet',
75
+ };
76
+ return networkMap[network];
77
+ };
78
+
79
+ class Client extends BaseXChainClient {
80
+ constructor(params = defaultSolanaParams) {
81
+ super(SOLChain, Object.assign(Object.assign({}, defaultSolanaParams), params));
82
+ this.explorerProviders = params.explorerProviders;
83
+ this.connection = new Connection(clusterApiUrl(getSolanaNetwork(this.getNetwork())));
84
+ this.umi = createUmi(this.connection).use(mplTokenMetadata());
85
+ }
86
+ /**
87
+ * Get information about the native asset of the Solana.
88
+ *
89
+ * @returns {AssetInfo} Information about the native asset.
90
+ */
91
+ getAssetInfo() {
92
+ return {
93
+ asset: SOLAsset,
94
+ decimal: SOL_DECIMALS,
95
+ };
96
+ }
97
+ /**
98
+ * Get the explorer URL.
99
+ *
100
+ * @returns {string} The explorer URL.
101
+ */
102
+ getExplorerUrl() {
103
+ return this.explorerProviders[this.getNetwork()].getExplorerUrl();
104
+ }
105
+ /**
106
+ * Get the explorer url for the given address.
107
+ *
108
+ * @param {Address} address
109
+ * @returns {string} The explorer url for the given address.
110
+ */
111
+ getExplorerAddressUrl(address) {
112
+ return this.explorerProviders[this.getNetwork()].getExplorerAddressUrl(address);
113
+ }
114
+ /**
115
+ * Get the explorer url for the given transaction id.
116
+ *
117
+ * @param {string} txID
118
+ * @returns {string} The explorer url for the given transaction id.
119
+ */
120
+ getExplorerTxUrl(txID) {
121
+ return this.explorerProviders[this.getNetwork()].getExplorerTxUrl(txID);
122
+ }
123
+ /**
124
+ * Get the full derivation path based on the wallet index.
125
+ * @param {number} walletIndex The HD wallet index
126
+ * @returns {string} The full derivation path
127
+ */
128
+ getFullDerivationPath(walletIndex) {
129
+ if (!this.rootDerivationPaths) {
130
+ throw Error('Can not generate derivation path due to root derivation path is undefined');
131
+ }
132
+ return `${this.rootDerivationPaths[this.getNetwork()]}${walletIndex}'`;
133
+ }
134
+ /**
135
+ * Get the current address asynchronously.
136
+ *
137
+ * @param {number} index The index of the address. Default 0
138
+ * @returns {Address} The Solana address related to the index provided.
139
+ * @throws {"Phrase must be provided"} Thrown if the phrase has not been set before.
140
+ */
141
+ getAddressAsync(index) {
142
+ return __awaiter(this, void 0, void 0, function* () {
143
+ return this.getPrivateKeyPair(index || 0).publicKey.toBase58();
144
+ });
145
+ }
146
+ /**
147
+ * Get the current address synchronously.
148
+ * @deprecated
149
+ */
150
+ getAddress() {
151
+ throw Error('Sync method not supported');
152
+ }
153
+ /**
154
+ * Validate the given Solana address.
155
+ * @param {string} address Solana address to validate.
156
+ * @returns {boolean} `true` if the address is valid, `false` otherwise.
157
+ */
158
+ validateAddress(address) {
159
+ return isAddress(address);
160
+ }
161
+ /**
162
+ * Retrieves the balance of a given address.
163
+ * @param {Address} address - The address to retrieve the balance for.
164
+ * @param {TokenAsset[]} assets - Assets to retrieve the balance for (optional).
165
+ * @returns {Promise<Balance[]>} An array containing the balance of the address.
166
+ */
167
+ getBalance(address, assets) {
168
+ return __awaiter(this, void 0, void 0, function* () {
169
+ const balances = [];
170
+ const nativeBalance = yield this.connection.getBalance(new PublicKey(address));
171
+ balances.push({
172
+ asset: SOLAsset,
173
+ amount: baseAmount(nativeBalance, SOL_DECIMALS),
174
+ });
175
+ const tokenBalances = yield this.connection.getParsedTokenAccountsByOwner(new PublicKey(address), {
176
+ programId: TOKEN_PROGRAM_ID,
177
+ });
178
+ const tokensToRequest = !assets
179
+ ? tokenBalances.value
180
+ : tokenBalances.value.filter((tokenBalance) => {
181
+ const tokenData = tokenBalance.account.data.parsed;
182
+ return (assets.findIndex((asset) => {
183
+ return asset.symbol.toLowerCase().includes(tokenData.info.mint.toLowerCase());
184
+ }) !== -1);
185
+ });
186
+ const mintPublicKeys = tokensToRequest.map((tokenBalance) => {
187
+ const tokenData = tokenBalance.account.data.parsed;
188
+ return publicKey(tokenData.info.mint);
189
+ });
190
+ const assetsData = yield fetchAllDigitalAsset(this.umi, mintPublicKeys);
191
+ tokenBalances.value.forEach((balance) => {
192
+ const parsedData = balance.account.data.parsed;
193
+ const assetData = assetsData.find((assetData) => assetData.publicKey.toString() === parsedData.info.mint);
194
+ if (assetData) {
195
+ balances.push({
196
+ amount: baseAmount(parsedData.info.tokenAmount.amount, parsedData.info.tokenAmount.decimals),
197
+ asset: assetFromStringEx(`SOL.${assetData.metadata.symbol.trim()}-${parsedData.info.mint}`),
198
+ });
199
+ }
200
+ });
201
+ return balances;
202
+ });
203
+ }
204
+ /**
205
+ * Get transaction fees.
206
+ *
207
+ * @param {TxParams} params - The transaction parameters.
208
+ * @returns {Fees} The average, fast, and fastest fees.
209
+ * @throws {"Params need to be passed"} Thrown if parameters are not provided.
210
+ */
211
+ getFees(params) {
212
+ return __awaiter(this, void 0, void 0, function* () {
213
+ if (!params)
214
+ throw new Error('Params need to be passed');
215
+ const sender = Keypair.generate();
216
+ const toPubkey = new PublicKey(params.recipient);
217
+ const transaction = new Transaction();
218
+ transaction.recentBlockhash = yield this.connection.getLatestBlockhash().then((block) => block.blockhash);
219
+ transaction.feePayer = sender.publicKey;
220
+ let createAccountTxFee = 0;
221
+ if (!params.asset || eqAsset(params.asset, this.getAssetInfo().asset)) {
222
+ // Native transfer
223
+ transaction.add(SystemProgram.transfer({
224
+ fromPubkey: sender.publicKey,
225
+ toPubkey,
226
+ lamports: params.amount.amount().toNumber(),
227
+ }));
228
+ }
229
+ else {
230
+ // Token transfer
231
+ const mintAddress = new PublicKey(getContractAddressFromAsset(params.asset));
232
+ const associatedTokenAddress = getAssociatedTokenAddressSync(mintAddress, toPubkey);
233
+ try {
234
+ yield getAccount(this.connection, associatedTokenAddress, undefined, TOKEN_PROGRAM_ID);
235
+ transaction.add(createTransferInstruction(sender.publicKey, // Should be Token account, but as it new KeyPair for estimation, sender public key
236
+ associatedTokenAddress, sender.publicKey, params.amount.amount().toNumber()));
237
+ }
238
+ catch (error) {
239
+ if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {
240
+ // recipient token account has to be created
241
+ const dataLength = 165; // Normally used for Token accounts
242
+ createAccountTxFee = yield this.connection.getMinimumBalanceForRentExemption(dataLength);
243
+ transaction.add(createTransferInstruction(sender.publicKey, // Should be Token account, but as it new KeyPair for estimation, sender public key
244
+ toPubkey, // Should be Token account, but as recipient token account should be created, recipient public key
245
+ sender.publicKey, params.amount.amount().toNumber()));
246
+ }
247
+ }
248
+ }
249
+ if (params.memo) {
250
+ transaction.add(new TransactionInstruction({
251
+ keys: [{ pubkey: sender.publicKey, isSigner: true, isWritable: true }],
252
+ data: Buffer.from(params.memo, 'utf-8'),
253
+ programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),
254
+ }));
255
+ }
256
+ if (params.priorityFee) {
257
+ transaction.add(ComputeBudgetProgram.setComputeUnitPrice({
258
+ microLamports: params.priorityFee.amount().toNumber() / Math.pow(10, 3),
259
+ }));
260
+ }
261
+ if (params.limit) {
262
+ transaction.add(ComputeBudgetProgram.setComputeUnitLimit({
263
+ units: params.limit,
264
+ }));
265
+ }
266
+ const fee = (yield transaction.getEstimatedFee(this.connection)) || 0;
267
+ return {
268
+ type: FeeType.FlatFee,
269
+ [FeeOption.Average]: baseAmount(fee + createAccountTxFee, SOL_DECIMALS),
270
+ [FeeOption.Fast]: baseAmount(fee + createAccountTxFee, SOL_DECIMALS),
271
+ [FeeOption.Fastest]: baseAmount(fee + createAccountTxFee, SOL_DECIMALS),
272
+ };
273
+ });
274
+ }
275
+ /**
276
+ * Get the transaction details of a given transaction ID.
277
+ *
278
+ * @param {string} txId The transaction ID.
279
+ * @returns {Tx} The transaction details.
280
+ */
281
+ getTransactionData(txId) {
282
+ return __awaiter(this, void 0, void 0, function* () {
283
+ const transaction = yield this.connection.getParsedTransaction(txId);
284
+ if (!transaction)
285
+ throw Error('Can not find transaction');
286
+ return this.parseTransaction(transaction);
287
+ });
288
+ }
289
+ getTransactions(params) {
290
+ return __awaiter(this, void 0, void 0, function* () {
291
+ const signatures = yield this.connection.getSignaturesForAddress(new PublicKey((params === null || params === void 0 ? void 0 : params.address) || (yield this.getAddressAsync())));
292
+ const transactions = yield this.connection.getParsedTransactions(signatures.map(({ signature }) => signature));
293
+ const results = yield Promise.allSettled(transactions
294
+ .filter((transaction) => !!transaction)
295
+ .map((transaction) => this.parseTransaction(transaction)));
296
+ const txs = [];
297
+ results.forEach((result) => {
298
+ if (result.status === 'fulfilled') {
299
+ txs.push(result.value);
300
+ }
301
+ });
302
+ return {
303
+ txs,
304
+ total: txs.length,
305
+ };
306
+ });
307
+ }
308
+ /**
309
+ * Transfers SOL or Solana token
310
+ *
311
+ * @param {TxParams} params The transfer options.
312
+ * @returns {TxHash} The transaction hash.
313
+ */
314
+ transfer({ walletIndex, recipient, asset, amount, memo, limit, priorityFee, }) {
315
+ return __awaiter(this, void 0, void 0, function* () {
316
+ const senderKeyPair = this.getPrivateKeyPair(walletIndex || 0);
317
+ if (asset && !eqAsset(asset, this.getAssetInfo().asset)) {
318
+ // Check if receipt token account is created, otherwise, create it
319
+ const mintAddress = new PublicKey(getContractAddressFromAsset(asset));
320
+ yield getOrCreateAssociatedTokenAccount(this.connection, senderKeyPair, mintAddress, new PublicKey(recipient));
321
+ }
322
+ const { rawUnsignedTx } = yield this.prepareTx({
323
+ sender: senderKeyPair.publicKey.toBase58(),
324
+ recipient,
325
+ asset,
326
+ amount,
327
+ memo,
328
+ limit,
329
+ priorityFee,
330
+ });
331
+ const transaction = Transaction.from(bs58.decode(rawUnsignedTx));
332
+ transaction.sign(senderKeyPair);
333
+ return this.broadcastTx(bs58.encode(transaction.serialize()));
334
+ });
335
+ }
336
+ /**
337
+ * Broadcast a transaction to the network
338
+ * @param {string} txHex Raw transaction to broadcast
339
+ * @returns {TxHash} The hash of the transaction broadcasted
340
+ */
341
+ broadcastTx(txHex) {
342
+ return __awaiter(this, void 0, void 0, function* () {
343
+ try {
344
+ const transaction = Transaction.from(bs58.decode(txHex));
345
+ return yield this.connection.sendRawTransaction(transaction.serialize());
346
+ }
347
+ catch (e) {
348
+ if (e instanceof SendTransactionError) {
349
+ console.log(yield e.getLogs(this.connection));
350
+ }
351
+ throw Error('Can not broadcast transaction. Unknown error');
352
+ }
353
+ });
354
+ }
355
+ /**
356
+ * Prepares a transaction for transfer.
357
+ *
358
+ * @param {TxParams&Address} params - The transfer options.
359
+ * @returns {Promise<PreparedTx>} The raw unsigned transaction.
360
+ */
361
+ prepareTx({ sender, recipient, asset, amount, memo, limit, priorityFee, }) {
362
+ return __awaiter(this, void 0, void 0, function* () {
363
+ const transaction = new Transaction();
364
+ const fromPubkey = new PublicKey(sender);
365
+ const toPubkey = new PublicKey(recipient);
366
+ transaction.recentBlockhash = yield this.connection.getLatestBlockhash().then((block) => block.blockhash);
367
+ transaction.feePayer = new PublicKey(sender);
368
+ if (!asset || eqAsset(asset, this.getAssetInfo().asset)) {
369
+ // Native transfer
370
+ transaction.add(SystemProgram.transfer({
371
+ fromPubkey,
372
+ toPubkey,
373
+ lamports: amount.amount().toNumber(),
374
+ }));
375
+ }
376
+ else {
377
+ // Token transfer
378
+ const mintAddress = new PublicKey(getContractAddressFromAsset(asset));
379
+ const fromAssociatedAccount = getAssociatedTokenAddressSync(mintAddress, fromPubkey);
380
+ let fromTokenAccount;
381
+ try {
382
+ fromTokenAccount = yield getAccount(this.connection, fromAssociatedAccount);
383
+ }
384
+ catch (error) {
385
+ if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {
386
+ throw Error('Can not find sender Token account');
387
+ }
388
+ throw error;
389
+ }
390
+ const toAssociatedAccount = getAssociatedTokenAddressSync(mintAddress, toPubkey);
391
+ let toTokenAccount;
392
+ try {
393
+ toTokenAccount = yield getAccount(this.connection, toAssociatedAccount);
394
+ }
395
+ catch (error) {
396
+ if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {
397
+ throw Error('Can not find recipient Token account. Create it first');
398
+ }
399
+ throw error;
400
+ }
401
+ transaction.add(createTransferInstruction(fromTokenAccount.address, toTokenAccount.address, fromPubkey, amount.amount().toNumber()));
402
+ }
403
+ if (memo) {
404
+ transaction.add(new TransactionInstruction({
405
+ keys: [{ pubkey: fromPubkey, isSigner: true, isWritable: true }],
406
+ data: Buffer.from(memo, 'utf-8'),
407
+ programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),
408
+ }));
409
+ }
410
+ if (priorityFee) {
411
+ transaction.add(ComputeBudgetProgram.setComputeUnitPrice({
412
+ microLamports: priorityFee.amount().toNumber() / Math.pow(10, 3),
413
+ }));
414
+ }
415
+ if (limit) {
416
+ transaction.add(ComputeBudgetProgram.setComputeUnitLimit({
417
+ units: limit,
418
+ }));
419
+ }
420
+ return { rawUnsignedTx: bs58.encode(transaction.serialize({ verifySignatures: false })) };
421
+ });
422
+ }
423
+ getPrivateKeyPair(index) {
424
+ if (!this.phrase)
425
+ throw new Error('Phrase must be provided');
426
+ const seed = getSeed(this.phrase);
427
+ const hd = HDKey.fromMasterSeed(seed.toString('hex'));
428
+ return Keypair.fromSeed(hd.derive(this.getFullDerivationPath(index)).privateKey);
429
+ }
430
+ parseTransaction(tx) {
431
+ var _a, _b, _c;
432
+ return __awaiter(this, void 0, void 0, function* () {
433
+ const from = [];
434
+ const to = [];
435
+ tx.transaction.message.accountKeys.forEach((accountKey, index) => {
436
+ var _a, _b;
437
+ if (accountKey.writable) {
438
+ const preBalance = (_a = tx.meta) === null || _a === void 0 ? void 0 : _a.preBalances[index];
439
+ const postBalance = (_b = tx.meta) === null || _b === void 0 ? void 0 : _b.postBalances[index];
440
+ if (preBalance !== undefined && postBalance !== undefined) {
441
+ if (postBalance > preBalance) {
442
+ to.push({
443
+ amount: baseAmount(postBalance - preBalance, this.getAssetInfo().decimal),
444
+ asset: this.getAssetInfo().asset,
445
+ to: accountKey.pubkey.toBase58(),
446
+ });
447
+ }
448
+ else if (preBalance > postBalance) {
449
+ from.push({
450
+ amount: baseAmount(preBalance - postBalance, this.getAssetInfo().decimal),
451
+ asset: this.getAssetInfo().asset,
452
+ from: accountKey.pubkey.toBase58(),
453
+ });
454
+ }
455
+ }
456
+ }
457
+ });
458
+ // Tokens transfer
459
+ if (((_a = tx.meta) === null || _a === void 0 ? void 0 : _a.preTokenBalances) && ((_b = tx.meta) === null || _b === void 0 ? void 0 : _b.postTokenBalances)) {
460
+ for (let i = 0; i < ((_c = tx.meta) === null || _c === void 0 ? void 0 : _c.postTokenBalances.length); i++) {
461
+ const postBalance = tx.meta.postTokenBalances[i];
462
+ const preBalance = tx.meta.preTokenBalances.find((preTokenBalance) => preTokenBalance.accountIndex === postBalance.accountIndex);
463
+ const postBalanceAmount = postBalance.uiTokenAmount.uiAmount || 0;
464
+ const preBalanceAmount = (preBalance === null || preBalance === void 0 ? void 0 : preBalance.uiTokenAmount.uiAmount) || 0;
465
+ if (preBalance !== null && postBalance !== null) {
466
+ const assetDecimals = tx.meta.postTokenBalances[i].uiTokenAmount.decimals;
467
+ const mintAddress = tx.meta.postTokenBalances[i].mint;
468
+ const owner = tx.meta.postTokenBalances[i].owner;
469
+ const tokenMetadata = yield fetchDigitalAsset(this.umi, publicKey(mintAddress));
470
+ if (owner) {
471
+ if (postBalanceAmount > preBalanceAmount) {
472
+ to.push({
473
+ amount: assetToBase(assetAmount(postBalanceAmount - preBalanceAmount, assetDecimals)),
474
+ asset: assetFromStringEx(`SOL.${tokenMetadata.metadata.symbol.trim()}-${mintAddress}`),
475
+ to: owner,
476
+ });
477
+ }
478
+ else if (preBalanceAmount > postBalanceAmount) {
479
+ from.push({
480
+ amount: assetToBase(assetAmount(preBalanceAmount - postBalanceAmount, assetDecimals)),
481
+ asset: assetFromStringEx(`SOL.${tokenMetadata.metadata.symbol.trim()}-${mintAddress}`),
482
+ from: owner,
483
+ });
484
+ }
485
+ }
486
+ }
487
+ }
488
+ }
489
+ return {
490
+ asset: this.getAssetInfo().asset,
491
+ date: new Date((tx.blockTime || 0) * 1000),
492
+ type: TxType.Transfer,
493
+ hash: tx.transaction.signatures[0],
494
+ from,
495
+ to,
496
+ };
497
+ });
498
+ }
499
+ }
500
+
501
+ export { Client, SOLAsset, SOLChain, SOL_DECIMALS, defaultSolanaParams };
502
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":["../src/const.ts","../src/utils.ts","../src/client.ts"],"sourcesContent":["import { ExplorerProvider, Network } from '@xchainjs/xchain-client'\nimport { Asset, AssetType } from '@xchainjs/xchain-util'\n\nimport { SOLClientParams } from './types'\n\n/**\n * Solana chain symbol\n */\nexport const SOLChain = 'SOL' as const\n\n/**\n * Solana native asset decimals\n */\nexport const SOL_DECIMALS = 9\n\n/**\n * Solana native asset\n */\nexport const SOLAsset: Asset = {\n chain: 'SOL',\n ticker: 'SOL',\n symbol: 'SOL',\n type: AssetType.NATIVE,\n}\n\nconst mainnetExplorer = new ExplorerProvider(\n 'https://explorer.solana.com/',\n 'https://explorer.solana.com/address/%%ADDRESS%%',\n 'https://explorer.solana.com/tx/%%TX_ID%%',\n)\n\nexport const defaultSolanaParams: SOLClientParams = {\n network: Network.Mainnet,\n rootDerivationPaths: {\n [Network.Mainnet]: \"m/44'/501'/\",\n [Network.Testnet]: \"m/44'/501'/\",\n [Network.Stagenet]: \"m/44'/501'/\",\n },\n explorerProviders: {\n [Network.Mainnet]: mainnetExplorer,\n [Network.Testnet]: new ExplorerProvider(\n 'https://explorer.solana.com/?cluster=testnet',\n 'https://explorer.solana.com/address/%%ADDRESS%%?cluster=testnet',\n 'https://explorer.solana.com/tx/%%TX_ID%%?cluster=testnet',\n ),\n [Network.Stagenet]: mainnetExplorer,\n },\n}\n","import { Cluster } from '@solana/web3.js'\nimport { Network } from '@xchainjs/xchain-client'\n\nexport const getSolanaNetwork = (network: Network): Cluster => {\n const networkMap: { [key in Network]: Cluster } = {\n [Network.Mainnet]: 'mainnet-beta',\n [Network.Stagenet]: 'mainnet-beta',\n [Network.Testnet]: 'testnet',\n }\n return networkMap[network]\n}\n","import { fetchAllDigitalAsset, fetchDigitalAsset, mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata'\nimport { PublicKey as UmiPubliKey, Umi, publicKey } from '@metaplex-foundation/umi'\nimport { createUmi } from '@metaplex-foundation/umi-bundle-defaults'\nimport { isAddress } from '@solana/addresses'\nimport {\n Account,\n TOKEN_PROGRAM_ID,\n TokenAccountNotFoundError,\n TokenInvalidAccountOwnerError,\n createTransferInstruction,\n getAccount,\n getAssociatedTokenAddressSync,\n getOrCreateAssociatedTokenAccount,\n} from '@solana/spl-token'\nimport {\n ComputeBudgetProgram,\n Connection,\n Keypair,\n ParsedTransactionWithMeta,\n PublicKey,\n SendTransactionError,\n SystemProgram,\n Transaction,\n TransactionInstruction,\n clusterApiUrl,\n} from '@solana/web3.js'\nimport {\n AssetInfo,\n BaseXChainClient,\n ExplorerProviders,\n FeeOption,\n FeeType,\n Fees,\n PreparedTx,\n TxHash,\n TxHistoryParams,\n TxType,\n} from '@xchainjs/xchain-client'\nimport { getSeed } from '@xchainjs/xchain-crypto'\nimport {\n Address,\n TokenAsset,\n assetAmount,\n assetFromStringEx,\n assetToBase,\n baseAmount,\n eqAsset,\n getContractAddressFromAsset,\n} from '@xchainjs/xchain-util'\nimport bs58 from 'bs58'\nimport { HDKey } from 'micro-ed25519-hdkey'\n\nimport { SOLAsset, SOLChain, SOL_DECIMALS, defaultSolanaParams } from './const'\nimport { TokenAssetData } from './solana-types'\nimport { Balance, SOLClientParams, Tx, TxFrom, TxParams, TxTo, TxsPage } from './types'\nimport { getSolanaNetwork } from './utils'\n\nexport class Client extends BaseXChainClient {\n private explorerProviders: ExplorerProviders\n private connection: Connection\n private umi: Umi\n\n constructor(params: SOLClientParams = defaultSolanaParams) {\n super(SOLChain, {\n ...defaultSolanaParams,\n ...params,\n })\n this.explorerProviders = params.explorerProviders\n this.connection = new Connection(clusterApiUrl(getSolanaNetwork(this.getNetwork())))\n this.umi = createUmi(this.connection).use(mplTokenMetadata())\n }\n\n /**\n * Get information about the native asset of the Solana.\n *\n * @returns {AssetInfo} Information about the native asset.\n */\n public getAssetInfo(): AssetInfo {\n return {\n asset: SOLAsset,\n decimal: SOL_DECIMALS,\n }\n }\n\n /**\n * Get the explorer URL.\n *\n * @returns {string} The explorer URL.\n */\n public getExplorerUrl(): string {\n return this.explorerProviders[this.getNetwork()].getExplorerUrl()\n }\n\n /**\n * Get the explorer url for the given address.\n *\n * @param {Address} address\n * @returns {string} The explorer url for the given address.\n */\n public getExplorerAddressUrl(address: Address): string {\n return this.explorerProviders[this.getNetwork()].getExplorerAddressUrl(address)\n }\n\n /**\n * Get the explorer url for the given transaction id.\n *\n * @param {string} txID\n * @returns {string} The explorer url for the given transaction id.\n */\n public getExplorerTxUrl(txID: TxHash): string {\n return this.explorerProviders[this.getNetwork()].getExplorerTxUrl(txID)\n }\n\n /**\n * Get the full derivation path based on the wallet index.\n * @param {number} walletIndex The HD wallet index\n * @returns {string} The full derivation path\n */\n public getFullDerivationPath(walletIndex: number): string {\n if (!this.rootDerivationPaths) {\n throw Error('Can not generate derivation path due to root derivation path is undefined')\n }\n return `${this.rootDerivationPaths[this.getNetwork()]}${walletIndex}'`\n }\n\n /**\n * Get the current address asynchronously.\n *\n * @param {number} index The index of the address. Default 0\n * @returns {Address} The Solana address related to the index provided.\n * @throws {\"Phrase must be provided\"} Thrown if the phrase has not been set before.\n */\n public async getAddressAsync(index?: number): Promise<string> {\n return this.getPrivateKeyPair(index || 0).publicKey.toBase58()\n }\n\n /**\n * Get the current address synchronously.\n * @deprecated\n */\n public getAddress(): string {\n throw Error('Sync method not supported')\n }\n\n /**\n * Validate the given Solana address.\n * @param {string} address Solana address to validate.\n * @returns {boolean} `true` if the address is valid, `false` otherwise.\n */\n public validateAddress(address: Address): boolean {\n return isAddress(address)\n }\n\n /**\n * Retrieves the balance of a given address.\n * @param {Address} address - The address to retrieve the balance for.\n * @param {TokenAsset[]} assets - Assets to retrieve the balance for (optional).\n * @returns {Promise<Balance[]>} An array containing the balance of the address.\n */\n public async getBalance(address: Address, assets?: TokenAsset[]): Promise<Balance[]> {\n const balances: Balance[] = []\n\n const nativeBalance = await this.connection.getBalance(new PublicKey(address))\n\n balances.push({\n asset: SOLAsset,\n amount: baseAmount(nativeBalance, SOL_DECIMALS),\n })\n\n const tokenBalances = await this.connection.getParsedTokenAccountsByOwner(new PublicKey(address), {\n programId: TOKEN_PROGRAM_ID,\n })\n\n const tokensToRequest = !assets\n ? tokenBalances.value\n : tokenBalances.value.filter((tokenBalance) => {\n const tokenData = tokenBalance.account.data.parsed as TokenAssetData\n return (\n assets.findIndex((asset) => {\n return asset.symbol.toLowerCase().includes(tokenData.info.mint.toLowerCase())\n }) !== -1\n )\n })\n\n const mintPublicKeys: UmiPubliKey[] = tokensToRequest.map((tokenBalance) => {\n const tokenData = tokenBalance.account.data.parsed as TokenAssetData\n return publicKey(tokenData.info.mint)\n })\n\n const assetsData = await fetchAllDigitalAsset(this.umi, mintPublicKeys)\n\n tokenBalances.value.forEach((balance) => {\n const parsedData = balance.account.data.parsed as TokenAssetData\n const assetData = assetsData.find((assetData) => assetData.publicKey.toString() === parsedData.info.mint)\n\n if (assetData) {\n balances.push({\n amount: baseAmount(parsedData.info.tokenAmount.amount, parsedData.info.tokenAmount.decimals),\n asset: assetFromStringEx(`SOL.${assetData.metadata.symbol.trim()}-${parsedData.info.mint}`) as TokenAsset,\n })\n }\n })\n\n return balances\n }\n\n /**\n * Get transaction fees.\n *\n * @param {TxParams} params - The transaction parameters.\n * @returns {Fees} The average, fast, and fastest fees.\n * @throws {\"Params need to be passed\"} Thrown if parameters are not provided.\n */\n public async getFees(params?: TxParams): Promise<Fees> {\n if (!params) throw new Error('Params need to be passed')\n\n const sender = Keypair.generate()\n const toPubkey = new PublicKey(params.recipient)\n\n const transaction = new Transaction()\n\n transaction.recentBlockhash = await this.connection.getLatestBlockhash().then((block) => block.blockhash)\n transaction.feePayer = sender.publicKey\n\n let createAccountTxFee = 0\n if (!params.asset || eqAsset(params.asset, this.getAssetInfo().asset)) {\n // Native transfer\n transaction.add(\n SystemProgram.transfer({\n fromPubkey: sender.publicKey,\n toPubkey,\n lamports: params.amount.amount().toNumber(),\n }),\n )\n } else {\n // Token transfer\n const mintAddress = new PublicKey(getContractAddressFromAsset(params.asset as TokenAsset))\n const associatedTokenAddress = getAssociatedTokenAddressSync(mintAddress, toPubkey)\n\n try {\n await getAccount(this.connection, associatedTokenAddress, undefined, TOKEN_PROGRAM_ID)\n transaction.add(\n createTransferInstruction(\n sender.publicKey, // Should be Token account, but as it new KeyPair for estimation, sender public key\n associatedTokenAddress,\n sender.publicKey,\n params.amount.amount().toNumber(),\n ),\n )\n } catch (error: unknown) {\n if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {\n // recipient token account has to be created\n\n const dataLength = 165 // Normally used for Token accounts\n createAccountTxFee = await this.connection.getMinimumBalanceForRentExemption(dataLength)\n\n transaction.add(\n createTransferInstruction(\n sender.publicKey, // Should be Token account, but as it new KeyPair for estimation, sender public key\n toPubkey, // Should be Token account, but as recipient token account should be created, recipient public key\n sender.publicKey,\n params.amount.amount().toNumber(),\n ),\n )\n }\n }\n }\n\n if (params.memo) {\n transaction.add(\n new TransactionInstruction({\n keys: [{ pubkey: sender.publicKey, isSigner: true, isWritable: true }],\n data: Buffer.from(params.memo, 'utf-8'),\n programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n }),\n )\n }\n\n if (params.priorityFee) {\n transaction.add(\n ComputeBudgetProgram.setComputeUnitPrice({\n microLamports: params.priorityFee.amount().toNumber() / 10 ** 3,\n }),\n )\n }\n\n if (params.limit) {\n transaction.add(\n ComputeBudgetProgram.setComputeUnitLimit({\n units: params.limit,\n }),\n )\n }\n\n const fee = (await transaction.getEstimatedFee(this.connection)) || 0\n\n return {\n type: FeeType.FlatFee,\n [FeeOption.Average]: baseAmount(fee + createAccountTxFee, SOL_DECIMALS),\n [FeeOption.Fast]: baseAmount(fee + createAccountTxFee, SOL_DECIMALS),\n [FeeOption.Fastest]: baseAmount(fee + createAccountTxFee, SOL_DECIMALS),\n }\n }\n\n /**\n * Get the transaction details of a given transaction ID.\n *\n * @param {string} txId The transaction ID.\n * @returns {Tx} The transaction details.\n */\n public async getTransactionData(txId: string): Promise<Tx> {\n const transaction = await this.connection.getParsedTransaction(txId)\n if (!transaction) throw Error('Can not find transaction')\n\n return this.parseTransaction(transaction)\n }\n\n public async getTransactions(params?: TxHistoryParams): Promise<TxsPage> {\n const signatures = await this.connection.getSignaturesForAddress(\n new PublicKey(params?.address || (await this.getAddressAsync())),\n )\n\n const transactions = await this.connection.getParsedTransactions(signatures.map(({ signature }) => signature))\n\n const results = await Promise.allSettled(\n transactions\n .filter((transaction) => !!transaction)\n .map((transaction) => this.parseTransaction(transaction as ParsedTransactionWithMeta)),\n )\n\n const txs: Tx[] = []\n\n results.forEach((result) => {\n if (result.status === 'fulfilled') {\n txs.push(result.value)\n }\n })\n\n return {\n txs,\n total: txs.length,\n }\n }\n\n /**\n * Transfers SOL or Solana token\n *\n * @param {TxParams} params The transfer options.\n * @returns {TxHash} The transaction hash.\n */\n public async transfer({\n walletIndex,\n recipient,\n asset,\n amount,\n memo,\n limit,\n priorityFee,\n }: TxParams): Promise<string> {\n const senderKeyPair = this.getPrivateKeyPair(walletIndex || 0)\n\n if (asset && !eqAsset(asset, this.getAssetInfo().asset)) {\n // Check if receipt token account is created, otherwise, create it\n const mintAddress = new PublicKey(getContractAddressFromAsset(asset as TokenAsset))\n await getOrCreateAssociatedTokenAccount(this.connection, senderKeyPair, mintAddress, new PublicKey(recipient))\n }\n\n const { rawUnsignedTx } = await this.prepareTx({\n sender: senderKeyPair.publicKey.toBase58(),\n recipient,\n asset,\n amount,\n memo,\n limit,\n priorityFee,\n })\n\n const transaction = Transaction.from(bs58.decode(rawUnsignedTx))\n\n transaction.sign(senderKeyPair)\n\n return this.broadcastTx(bs58.encode(transaction.serialize()))\n }\n\n /**\n * Broadcast a transaction to the network\n * @param {string} txHex Raw transaction to broadcast\n * @returns {TxHash} The hash of the transaction broadcasted\n */\n public async broadcastTx(txHex: string): Promise<TxHash> {\n try {\n const transaction = Transaction.from(bs58.decode(txHex))\n return await this.connection.sendRawTransaction(transaction.serialize())\n } catch (e: unknown) {\n if (e instanceof SendTransactionError) {\n console.log(await e.getLogs(this.connection))\n }\n throw Error('Can not broadcast transaction. Unknown error')\n }\n }\n\n /**\n * Prepares a transaction for transfer.\n *\n * @param {TxParams&Address} params - The transfer options.\n * @returns {Promise<PreparedTx>} The raw unsigned transaction.\n */\n public async prepareTx({\n sender,\n recipient,\n asset,\n amount,\n memo,\n limit,\n priorityFee,\n }: TxParams & { sender: Address }): Promise<PreparedTx> {\n const transaction = new Transaction()\n\n const fromPubkey = new PublicKey(sender)\n const toPubkey = new PublicKey(recipient)\n\n transaction.recentBlockhash = await this.connection.getLatestBlockhash().then((block) => block.blockhash)\n transaction.feePayer = new PublicKey(sender)\n\n if (!asset || eqAsset(asset, this.getAssetInfo().asset)) {\n // Native transfer\n transaction.add(\n SystemProgram.transfer({\n fromPubkey,\n toPubkey,\n lamports: amount.amount().toNumber(),\n }),\n )\n } else {\n // Token transfer\n const mintAddress = new PublicKey(getContractAddressFromAsset(asset as TokenAsset))\n\n const fromAssociatedAccount = getAssociatedTokenAddressSync(mintAddress, fromPubkey)\n let fromTokenAccount: Account\n try {\n fromTokenAccount = await getAccount(this.connection, fromAssociatedAccount)\n } catch (error) {\n if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {\n throw Error('Can not find sender Token account')\n }\n throw error\n }\n\n const toAssociatedAccount = getAssociatedTokenAddressSync(mintAddress, toPubkey)\n let toTokenAccount: Account\n try {\n toTokenAccount = await getAccount(this.connection, toAssociatedAccount)\n } catch (error) {\n if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {\n throw Error('Can not find recipient Token account. Create it first')\n }\n throw error\n }\n\n transaction.add(\n createTransferInstruction(\n fromTokenAccount.address,\n toTokenAccount.address,\n fromPubkey,\n amount.amount().toNumber(),\n ),\n )\n }\n\n if (memo) {\n transaction.add(\n new TransactionInstruction({\n keys: [{ pubkey: fromPubkey, isSigner: true, isWritable: true }],\n data: Buffer.from(memo, 'utf-8'),\n programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),\n }),\n )\n }\n\n if (priorityFee) {\n transaction.add(\n ComputeBudgetProgram.setComputeUnitPrice({\n microLamports: priorityFee.amount().toNumber() / 10 ** 3,\n }),\n )\n }\n\n if (limit) {\n transaction.add(\n ComputeBudgetProgram.setComputeUnitLimit({\n units: limit,\n }),\n )\n }\n\n return { rawUnsignedTx: bs58.encode(transaction.serialize({ verifySignatures: false })) }\n }\n\n private getPrivateKeyPair(index: number): Keypair {\n if (!this.phrase) throw new Error('Phrase must be provided')\n\n const seed = getSeed(this.phrase)\n const hd = HDKey.fromMasterSeed(seed.toString('hex'))\n\n return Keypair.fromSeed(hd.derive(this.getFullDerivationPath(index)).privateKey)\n }\n\n private async parseTransaction(tx: ParsedTransactionWithMeta): Promise<Tx> {\n const from: TxFrom[] = []\n const to: TxTo[] = []\n\n tx.transaction.message.accountKeys.forEach((accountKey, index) => {\n if (accountKey.writable) {\n const preBalance = tx.meta?.preBalances[index]\n const postBalance = tx.meta?.postBalances[index]\n\n if (preBalance !== undefined && postBalance !== undefined) {\n if (postBalance > preBalance) {\n to.push({\n amount: baseAmount(postBalance - preBalance, this.getAssetInfo().decimal),\n asset: this.getAssetInfo().asset,\n to: accountKey.pubkey.toBase58(),\n })\n } else if (preBalance > postBalance) {\n from.push({\n amount: baseAmount(preBalance - postBalance, this.getAssetInfo().decimal),\n asset: this.getAssetInfo().asset,\n from: accountKey.pubkey.toBase58(),\n })\n }\n }\n }\n })\n\n // Tokens transfer\n if (tx.meta?.preTokenBalances && tx.meta?.postTokenBalances) {\n for (let i = 0; i < tx.meta?.postTokenBalances.length; i++) {\n const postBalance = tx.meta.postTokenBalances[i]\n\n const preBalance = tx.meta.preTokenBalances.find(\n (preTokenBalance) => preTokenBalance.accountIndex === postBalance.accountIndex,\n )\n\n const postBalanceAmount = postBalance.uiTokenAmount.uiAmount || 0\n const preBalanceAmount = preBalance?.uiTokenAmount.uiAmount || 0\n\n if (preBalance !== null && postBalance !== null) {\n const assetDecimals = tx.meta.postTokenBalances[i].uiTokenAmount.decimals\n const mintAddress = tx.meta.postTokenBalances[i].mint\n const owner = tx.meta.postTokenBalances[i].owner\n\n const tokenMetadata = await fetchDigitalAsset(this.umi, publicKey(mintAddress))\n\n if (owner) {\n if (postBalanceAmount > preBalanceAmount) {\n to.push({\n amount: assetToBase(assetAmount(postBalanceAmount - preBalanceAmount, assetDecimals)),\n asset: assetFromStringEx(`SOL.${tokenMetadata.metadata.symbol.trim()}-${mintAddress}`) as TokenAsset,\n to: owner,\n })\n } else if (preBalanceAmount > postBalanceAmount) {\n from.push({\n amount: assetToBase(assetAmount(preBalanceAmount - postBalanceAmount, assetDecimals)),\n asset: assetFromStringEx(`SOL.${tokenMetadata.metadata.symbol.trim()}-${mintAddress}`) as TokenAsset,\n from: owner,\n })\n }\n }\n }\n }\n }\n\n return {\n asset: this.getAssetInfo().asset,\n date: new Date((tx.blockTime || 0) * 1000),\n type: TxType.Transfer,\n hash: tx.transaction.signatures[0],\n from,\n to,\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA;;AAEG;AACI,MAAM,QAAQ,GAAG,MAAc;AAEtC;;AAEG;AACI,MAAM,YAAY,GAAG,EAAC;AAE7B;;AAEG;AACU,MAAA,QAAQ,GAAU;AAC7B,IAAA,KAAK,EAAE,KAAK;AACZ,IAAA,MAAM,EAAE,KAAK;AACb,IAAA,MAAM,EAAE,KAAK;IACb,IAAI,EAAE,SAAS,CAAC,MAAM;EACvB;AAED,MAAM,eAAe,GAAG,IA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