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