@streamflow/common 6.5.0 → 7.0.0-alpha.10
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/dist/{index.js → cjs/index.js} +2 -2
- package/dist/{solana → cjs/solana}/index.js +3 -3
- package/dist/cjs/solana/instructions.js +22 -0
- package/dist/cjs/solana/types.js +11 -0
- package/dist/cjs/solana/utils.js +443 -0
- package/dist/cjs/types.js +40 -0
- package/dist/cjs/utils.js +57 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/solana/index.d.ts +3 -0
- package/dist/esm/solana/index.js +3 -0
- package/dist/{solana → esm/solana}/instructions.d.ts +2 -2
- package/dist/esm/solana/instructions.js +18 -0
- package/dist/esm/solana/types.js +7 -0
- package/dist/{solana → esm/solana}/utils.d.ts +1 -1
- package/dist/esm/solana/utils.js +416 -0
- package/dist/{types.d.ts → esm/types.d.ts} +1 -2
- package/dist/esm/types.js +38 -0
- package/dist/{utils.d.ts → esm/utils.d.ts} +9 -9
- package/dist/esm/utils.js +47 -0
- package/package.json +20 -20
- package/dist/index.d.ts +0 -2
- package/dist/solana/index.d.ts +0 -3
- package/dist/solana/instructions.js +0 -92
- package/dist/solana/types.js +0 -29
- package/dist/solana/utils.js +0 -754
- package/dist/types.js +0 -58
- package/dist/utils.js +0 -107
- /package/dist/{solana → esm/solana}/types.d.ts +0 -0
|
@@ -14,5 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./types"), exports);
|
|
18
|
-
__exportStar(require("./utils"), exports);
|
|
17
|
+
__exportStar(require("./types.js"), exports);
|
|
18
|
+
__exportStar(require("./utils.js"), exports);
|
|
@@ -14,6 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./instructions"), exports);
|
|
18
|
-
__exportStar(require("./types"), exports);
|
|
19
|
-
__exportStar(require("./utils"), exports);
|
|
17
|
+
__exportStar(require("./instructions.js"), exports);
|
|
18
|
+
__exportStar(require("./types.js"), exports);
|
|
19
|
+
__exportStar(require("./utils.js"), exports);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.prepareWrappedAccount = void 0;
|
|
4
|
+
const spl_token_1 = require("@solana/spl-token");
|
|
5
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
6
|
+
const prepareWrappedAccount = async (connection, senderAddress, amount) => {
|
|
7
|
+
const tokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, senderAddress, true);
|
|
8
|
+
const accInfo = await connection.getParsedAccountInfo(tokenAccount);
|
|
9
|
+
const instructions = (accInfo.value?.lamports ?? 0) > 0
|
|
10
|
+
? []
|
|
11
|
+
: [(0, spl_token_1.createAssociatedTokenAccountInstruction)(senderAddress, tokenAccount, senderAddress, spl_token_1.NATIVE_MINT)];
|
|
12
|
+
return [
|
|
13
|
+
...instructions,
|
|
14
|
+
web3_js_1.SystemProgram.transfer({
|
|
15
|
+
fromPubkey: senderAddress,
|
|
16
|
+
toPubkey: tokenAccount,
|
|
17
|
+
lamports: amount.toNumber(),
|
|
18
|
+
}),
|
|
19
|
+
(0, spl_token_1.createSyncNativeInstruction)(tokenAccount),
|
|
20
|
+
];
|
|
21
|
+
};
|
|
22
|
+
exports.prepareWrappedAccount = prepareWrappedAccount;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TransactionFailedError = void 0;
|
|
4
|
+
class TransactionFailedError extends Error {
|
|
5
|
+
constructor(m) {
|
|
6
|
+
super(m);
|
|
7
|
+
Object.setPrototypeOf(this, TransactionFailedError.prototype);
|
|
8
|
+
this.name = "TransactionFailedError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
exports.TransactionFailedError = TransactionFailedError;
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.getMintAndProgram = exports.prepareBaseInstructions = exports.checkOrCreateAtaBatch = exports.createAtaBatch = exports.generateCreateAtaBatchTx = exports.enrichAtaParams = exports.ataBatchExist = exports.ata = exports.confirmAndEnsureTransaction = exports.simulateTransaction = exports.sendAndConfirmTransaction = exports.executeMultipleTransactions = exports.executeTransaction = exports.signAndExecuteTransaction = exports.signTransaction = exports.prepareTransaction = exports.isTransactionVersioned = exports.isSignerKeypair = exports.isSignerWallet = exports.getProgramAccounts = exports.buildSendThrottler = void 0;
|
|
7
|
+
const spl_token_1 = require("@solana/spl-token");
|
|
8
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
9
|
+
const bs58_1 = __importDefault(require("bs58"));
|
|
10
|
+
const p_queue_1 = __importDefault(require("p-queue"));
|
|
11
|
+
const types_js_1 = require("./types.js");
|
|
12
|
+
const utils_js_1 = require("../utils.js");
|
|
13
|
+
const SIMULATE_TRIES = 3;
|
|
14
|
+
const buildSendThrottler = (sendRate) => {
|
|
15
|
+
return new p_queue_1.default({ concurrency: sendRate, intervalCap: 1, interval: 1000 });
|
|
16
|
+
};
|
|
17
|
+
exports.buildSendThrottler = buildSendThrottler;
|
|
18
|
+
/**
|
|
19
|
+
* Wrapper function for Solana web3 getProgramAccounts with slightly better call interface
|
|
20
|
+
* @param {Connection} connection - Solana web3 connection object.
|
|
21
|
+
* @param {PublicKey} wallet - PublicKey to compare against.
|
|
22
|
+
* @param {number} offset - Offset of bits of the PublicKey in the account binary.
|
|
23
|
+
* @param {PublicKey} programId - Solana program ID.
|
|
24
|
+
* @return {Promise<Account[]>} - Array of resulting accounts.
|
|
25
|
+
*/
|
|
26
|
+
async function getProgramAccounts(connection, wallet, offset, programId) {
|
|
27
|
+
const programAccounts = await connection?.getProgramAccounts(programId, {
|
|
28
|
+
filters: [
|
|
29
|
+
{
|
|
30
|
+
memcmp: {
|
|
31
|
+
offset,
|
|
32
|
+
bytes: wallet.toBase58(),
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
});
|
|
37
|
+
return [...programAccounts];
|
|
38
|
+
}
|
|
39
|
+
exports.getProgramAccounts = getProgramAccounts;
|
|
40
|
+
/**
|
|
41
|
+
* Utility function to check if the transaction initiator is a Wallet object
|
|
42
|
+
* @param {Keypair | SignerWalletAdapter} walletOrKeypair - Wallet or Keypair in question
|
|
43
|
+
* @return {boolean} - Returns true if parameter is a Wallet.
|
|
44
|
+
*/
|
|
45
|
+
function isSignerWallet(walletOrKeypair) {
|
|
46
|
+
return walletOrKeypair.signTransaction !== undefined;
|
|
47
|
+
}
|
|
48
|
+
exports.isSignerWallet = isSignerWallet;
|
|
49
|
+
/**
|
|
50
|
+
* Utility function to check if the transaction initiator a Keypair object, tries to mitigate version mismatch issues
|
|
51
|
+
* @param walletOrKeypair {Keypair | SignerWalletAdapter} walletOrKeypair - Wallet or Keypair in question
|
|
52
|
+
* @returns {boolean} - Returns true if parameter is a Keypair.
|
|
53
|
+
*/
|
|
54
|
+
function isSignerKeypair(walletOrKeypair) {
|
|
55
|
+
return (walletOrKeypair instanceof web3_js_1.Keypair ||
|
|
56
|
+
walletOrKeypair.constructor === web3_js_1.Keypair ||
|
|
57
|
+
walletOrKeypair.constructor.name === web3_js_1.Keypair.prototype.constructor.name);
|
|
58
|
+
}
|
|
59
|
+
exports.isSignerKeypair = isSignerKeypair;
|
|
60
|
+
/**
|
|
61
|
+
* Utility function to check whether given transaction is Versioned
|
|
62
|
+
* @param tx {Transaction | VersionedTransaction} - Transaction to check
|
|
63
|
+
* @returns {boolean} - Returns true if transaction is Versioned.
|
|
64
|
+
*/
|
|
65
|
+
function isTransactionVersioned(tx) {
|
|
66
|
+
return "message" in tx;
|
|
67
|
+
}
|
|
68
|
+
exports.isTransactionVersioned = isTransactionVersioned;
|
|
69
|
+
/**
|
|
70
|
+
* Creates a Transaction with given instructions and optionally signs it.
|
|
71
|
+
* @param connection - Solana client connection
|
|
72
|
+
* @param ixs - Instructions to add to the Transaction
|
|
73
|
+
* @param payer - PublicKey of payer
|
|
74
|
+
* @param commitment - optional Commitment that will be used to fetch latest blockhash
|
|
75
|
+
* @param partialSigners - optional signers that will be used to partially sign a Transaction
|
|
76
|
+
* @returns Transaction and Blockhash
|
|
77
|
+
*/
|
|
78
|
+
async function prepareTransaction(connection, ixs, payer, commitment, ...partialSigners) {
|
|
79
|
+
if (!payer) {
|
|
80
|
+
throw new Error("Payer public key is not provided!");
|
|
81
|
+
}
|
|
82
|
+
const { value: hash, context } = await connection.getLatestBlockhashAndContext(commitment);
|
|
83
|
+
const messageV0 = new web3_js_1.TransactionMessage({
|
|
84
|
+
payerKey: payer,
|
|
85
|
+
recentBlockhash: hash.blockhash,
|
|
86
|
+
instructions: ixs,
|
|
87
|
+
}).compileToV0Message();
|
|
88
|
+
const tx = new web3_js_1.VersionedTransaction(messageV0);
|
|
89
|
+
const signers = partialSigners.filter((item) => !!item);
|
|
90
|
+
tx.sign(signers);
|
|
91
|
+
return { tx, context, hash };
|
|
92
|
+
}
|
|
93
|
+
exports.prepareTransaction = prepareTransaction;
|
|
94
|
+
async function signTransaction(invoker, tx) {
|
|
95
|
+
let signedTx;
|
|
96
|
+
if (isSignerWallet(invoker)) {
|
|
97
|
+
signedTx = await invoker.signTransaction(tx);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
if (isTransactionVersioned(tx)) {
|
|
101
|
+
tx.sign([invoker]);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
tx.partialSign(invoker);
|
|
105
|
+
}
|
|
106
|
+
signedTx = tx;
|
|
107
|
+
}
|
|
108
|
+
return signedTx;
|
|
109
|
+
}
|
|
110
|
+
exports.signTransaction = signTransaction;
|
|
111
|
+
/**
|
|
112
|
+
* Signs, sends and confirms Transaction
|
|
113
|
+
* @param connection - Solana client connection
|
|
114
|
+
* @param invoker - Keypair used as signer
|
|
115
|
+
* @param tx - Transaction instance
|
|
116
|
+
* @param confirmationParams - Confirmation Params that will be used for execution
|
|
117
|
+
* @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
|
|
118
|
+
* @returns Transaction signature
|
|
119
|
+
*/
|
|
120
|
+
async function signAndExecuteTransaction(connection, invoker, tx, confirmationParams, throttleParams) {
|
|
121
|
+
const signedTx = await signTransaction(invoker, tx);
|
|
122
|
+
return executeTransaction(connection, signedTx, confirmationParams, throttleParams);
|
|
123
|
+
}
|
|
124
|
+
exports.signAndExecuteTransaction = signAndExecuteTransaction;
|
|
125
|
+
/**
|
|
126
|
+
* Sends and confirms Transaction
|
|
127
|
+
* Uses custom confirmation logic that:
|
|
128
|
+
* - simulates tx before sending separately
|
|
129
|
+
* - sends transaction without preFlight checks but with some valuable flags https://twitter.com/jordaaash/status/1774892862049800524?s=46&t=bhZ10V0r7IX5Lk5kKzxfGw
|
|
130
|
+
* - rebroadcasts a tx every 500 ms
|
|
131
|
+
* - after broadcasting check whether tx has executed once
|
|
132
|
+
* - catch errors for every actionable item, throw only the ones that signal that tx has failed
|
|
133
|
+
* - otherwise there is a chance of marking a landed tx as failed if it was broadcasted at least once
|
|
134
|
+
* @param connection - Solana client connection
|
|
135
|
+
* @param tx - Transaction instance
|
|
136
|
+
* @param confirmationParams - Confirmation Params that will be used for execution
|
|
137
|
+
* @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
|
|
138
|
+
* @returns Transaction signature
|
|
139
|
+
*/
|
|
140
|
+
async function executeTransaction(connection, tx, confirmationParams, throttleParams) {
|
|
141
|
+
if (tx.signatures.length === 0) {
|
|
142
|
+
throw Error("Error with transaction parameters.");
|
|
143
|
+
}
|
|
144
|
+
await simulateTransaction(connection, tx);
|
|
145
|
+
return sendAndConfirmTransaction(connection, tx, confirmationParams, throttleParams);
|
|
146
|
+
}
|
|
147
|
+
exports.executeTransaction = executeTransaction;
|
|
148
|
+
/**
|
|
149
|
+
* Launches a PromisePool with all transaction being executed at the same time, allows to throttle all TXs through one Queue
|
|
150
|
+
* @param connection - Solana client connection
|
|
151
|
+
* @param txs - Transactions
|
|
152
|
+
* @param confirmationParams - Confirmation Params that will be used for execution
|
|
153
|
+
* @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
|
|
154
|
+
* @param throttleParams.sendRate - rate
|
|
155
|
+
* @param throttleParams.sendThrottler - throttler instance
|
|
156
|
+
* @returns Raw Promise Results - should be handled by the consumer and unwrapped accordingly
|
|
157
|
+
*/
|
|
158
|
+
async function executeMultipleTransactions(connection, txs, confirmationParams, { sendRate = 1, sendThrottler }) {
|
|
159
|
+
if (!sendThrottler) {
|
|
160
|
+
sendThrottler = (0, exports.buildSendThrottler)(sendRate);
|
|
161
|
+
}
|
|
162
|
+
return Promise.allSettled(txs.map((tx) => executeTransaction(connection, tx, confirmationParams, { sendRate: sendRate, sendThrottler: sendThrottler })));
|
|
163
|
+
}
|
|
164
|
+
exports.executeMultipleTransactions = executeMultipleTransactions;
|
|
165
|
+
/**
|
|
166
|
+
* Sends and confirm transaction in a loop, constantly re-broadcsting the tx until Blockheight expires.
|
|
167
|
+
* - we add additional 30 bocks to account for validators in an PRC pool divergence
|
|
168
|
+
* @param connection - Solana client connection
|
|
169
|
+
* @param tx - Transaction instance
|
|
170
|
+
* @param confirmationParams - Confirmation Params that will be used for execution
|
|
171
|
+
* @param confirmationParams.hash - blockhash information, the same hash should be used in the Transaction
|
|
172
|
+
* @param confirmationParams.context - context at which blockhash has been retrieve
|
|
173
|
+
* @param confirmationParams.commitment - optional commitment that will be used for simulation and confirmation
|
|
174
|
+
* @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
|
|
175
|
+
* @param throttleParams.sendRate - rate
|
|
176
|
+
* @param throttleParams.sendThrottler - throttler instance
|
|
177
|
+
*/
|
|
178
|
+
async function sendAndConfirmTransaction(connection, tx, { hash, context, commitment }, { sendRate = 1, sendThrottler }) {
|
|
179
|
+
const isVersioned = isTransactionVersioned(tx);
|
|
180
|
+
let signature;
|
|
181
|
+
if (isVersioned) {
|
|
182
|
+
signature = bs58_1.default.encode(tx.signatures[0]);
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
signature = bs58_1.default.encode(tx.signature);
|
|
186
|
+
}
|
|
187
|
+
if (!sendThrottler) {
|
|
188
|
+
sendThrottler = (0, exports.buildSendThrottler)(sendRate);
|
|
189
|
+
}
|
|
190
|
+
let blockheight = await connection.getBlockHeight(commitment);
|
|
191
|
+
let transactionSent = false;
|
|
192
|
+
const rawTransaction = tx.serialize();
|
|
193
|
+
while (blockheight < hash.lastValidBlockHeight + 15) {
|
|
194
|
+
try {
|
|
195
|
+
if (blockheight < hash.lastValidBlockHeight || !transactionSent) {
|
|
196
|
+
await sendThrottler.add(async () => connection.sendRawTransaction(rawTransaction, {
|
|
197
|
+
maxRetries: 0,
|
|
198
|
+
minContextSlot: context.slot,
|
|
199
|
+
preflightCommitment: commitment,
|
|
200
|
+
skipPreflight: true,
|
|
201
|
+
}));
|
|
202
|
+
transactionSent = true;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
catch (e) {
|
|
206
|
+
if (transactionSent ||
|
|
207
|
+
(e instanceof web3_js_1.SendTransactionError && e.message.includes("Minimum context slot has not been reached"))) {
|
|
208
|
+
await (0, utils_js_1.sleep)(500);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
throw e;
|
|
212
|
+
}
|
|
213
|
+
await (0, utils_js_1.sleep)(500);
|
|
214
|
+
try {
|
|
215
|
+
const value = await confirmAndEnsureTransaction(connection, signature);
|
|
216
|
+
if (value) {
|
|
217
|
+
return signature;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch (e) {
|
|
221
|
+
if (e instanceof types_js_1.TransactionFailedError) {
|
|
222
|
+
throw e;
|
|
223
|
+
}
|
|
224
|
+
await (0, utils_js_1.sleep)(500);
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
blockheight = await connection.getBlockHeight(commitment);
|
|
228
|
+
}
|
|
229
|
+
catch (_e) {
|
|
230
|
+
await (0, utils_js_1.sleep)(500);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
throw new Error(`Transaction ${signature} expired.`);
|
|
234
|
+
}
|
|
235
|
+
exports.sendAndConfirmTransaction = sendAndConfirmTransaction;
|
|
236
|
+
async function simulateTransaction(connection, tx) {
|
|
237
|
+
let res;
|
|
238
|
+
for (let i = 0; i < SIMULATE_TRIES; i++) {
|
|
239
|
+
if (isTransactionVersioned(tx)) {
|
|
240
|
+
res = await connection.simulateTransaction(tx);
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
res = await connection.simulateTransaction(tx);
|
|
244
|
+
}
|
|
245
|
+
if (res.value.err) {
|
|
246
|
+
const errMessage = JSON.stringify(res.value.err);
|
|
247
|
+
if (!errMessage.includes("BlockhashNotFound") || i === SIMULATE_TRIES - 1) {
|
|
248
|
+
throw new web3_js_1.SendTransactionError("failed to simulate transaction: " + errMessage, res.value.logs || undefined);
|
|
249
|
+
}
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
return res;
|
|
253
|
+
}
|
|
254
|
+
throw new web3_js_1.SendTransactionError("failed to simulate transaction");
|
|
255
|
+
}
|
|
256
|
+
exports.simulateTransaction = simulateTransaction;
|
|
257
|
+
/**
|
|
258
|
+
* Confirms and validates transaction success once
|
|
259
|
+
* @param connection - Solana client connection
|
|
260
|
+
* @param signature - Transaction signature
|
|
261
|
+
* @param ignoreError - return status even if tx failed
|
|
262
|
+
* @returns Transaction Status
|
|
263
|
+
*/
|
|
264
|
+
async function confirmAndEnsureTransaction(connection, signature, ignoreError) {
|
|
265
|
+
const response = await connection.getSignatureStatuses([signature]);
|
|
266
|
+
if (!response || response.value.length === 0 || response.value[0] === null) {
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
const value = response.value[0];
|
|
270
|
+
if (!value) {
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
if (!ignoreError && value.err) {
|
|
274
|
+
// That's how solana-web3js does it, `err` here is an object that won't really be handled
|
|
275
|
+
throw new types_js_1.TransactionFailedError(`Raw transaction ${signature} failed (${JSON.stringify({ err: value.err })})`);
|
|
276
|
+
}
|
|
277
|
+
switch (connection.commitment) {
|
|
278
|
+
case "confirmed":
|
|
279
|
+
case "single":
|
|
280
|
+
case "singleGossip": {
|
|
281
|
+
if (value.confirmationStatus === "processed") {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
case "finalized":
|
|
287
|
+
case "max":
|
|
288
|
+
case "root": {
|
|
289
|
+
if (value.confirmationStatus === "processed" || value.confirmationStatus === "confirmed") {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
break;
|
|
293
|
+
}
|
|
294
|
+
// exhaust enums to ensure full coverage
|
|
295
|
+
case "processed":
|
|
296
|
+
case "recent":
|
|
297
|
+
}
|
|
298
|
+
return value;
|
|
299
|
+
}
|
|
300
|
+
exports.confirmAndEnsureTransaction = confirmAndEnsureTransaction;
|
|
301
|
+
/**
|
|
302
|
+
* Shorthand call signature for getAssociatedTokenAddress, with allowance for address to be offCurve
|
|
303
|
+
* @param {PublicKey} mint - SPL token Mint address.
|
|
304
|
+
* @param {PublicKey} owner - Owner of the Associated Token Address
|
|
305
|
+
* @param {PublicKey} programId - Program ID of the mint
|
|
306
|
+
* @return {Promise<PublicKey>} - Associated Token Address
|
|
307
|
+
*/
|
|
308
|
+
function ata(mint, owner, programId) {
|
|
309
|
+
return (0, spl_token_1.getAssociatedTokenAddress)(mint, owner, true, programId);
|
|
310
|
+
}
|
|
311
|
+
exports.ata = ata;
|
|
312
|
+
/**
|
|
313
|
+
* Function that checks whether ATA exists for each provided owner
|
|
314
|
+
* @param connection - Solana client connection
|
|
315
|
+
* @param paramsBatch - Array of Params for each ATA account: {mint, owner}
|
|
316
|
+
* @returns Array of boolean where each member corresponds to an owner
|
|
317
|
+
*/
|
|
318
|
+
async function ataBatchExist(connection, paramsBatch) {
|
|
319
|
+
const tokenAccounts = await Promise.all(paramsBatch.map(async ({ mint, owner, programId }) => {
|
|
320
|
+
return ata(mint, owner, programId);
|
|
321
|
+
}));
|
|
322
|
+
const response = await connection.getMultipleAccountsInfo(tokenAccounts);
|
|
323
|
+
return response.map((accInfo) => !!accInfo);
|
|
324
|
+
}
|
|
325
|
+
exports.ataBatchExist = ataBatchExist;
|
|
326
|
+
async function enrichAtaParams(connection, paramsBatch) {
|
|
327
|
+
const programIdByMint = {};
|
|
328
|
+
return Promise.all(paramsBatch.map(async (params) => {
|
|
329
|
+
if (params.programId) {
|
|
330
|
+
return params;
|
|
331
|
+
}
|
|
332
|
+
const mintStr = params.mint.toString();
|
|
333
|
+
if (!(mintStr in programIdByMint)) {
|
|
334
|
+
const { tokenProgramId } = await getMintAndProgram(connection, params.mint);
|
|
335
|
+
programIdByMint[mintStr] = tokenProgramId;
|
|
336
|
+
}
|
|
337
|
+
params.programId = programIdByMint[mintStr];
|
|
338
|
+
return params;
|
|
339
|
+
}));
|
|
340
|
+
}
|
|
341
|
+
exports.enrichAtaParams = enrichAtaParams;
|
|
342
|
+
/**
|
|
343
|
+
* Generates a Transaction to create ATA for an array of owners
|
|
344
|
+
* @param connection - Solana client connection
|
|
345
|
+
* @param payer - Transaction invoker, should be a signer
|
|
346
|
+
* @param paramsBatch - Array of Params for an each ATA account: {mint, owner}
|
|
347
|
+
* @param commitment - optional commitment that will be used to fetch Blockhash
|
|
348
|
+
* @returns Unsigned Transaction with create ATA instructions
|
|
349
|
+
*/
|
|
350
|
+
async function generateCreateAtaBatchTx(connection, payer, paramsBatch, commitment) {
|
|
351
|
+
paramsBatch = await enrichAtaParams(connection, paramsBatch);
|
|
352
|
+
const ixs = await Promise.all(paramsBatch.map(async ({ mint, owner, programId }) => {
|
|
353
|
+
return (0, spl_token_1.createAssociatedTokenAccountInstruction)(payer, await ata(mint, owner), owner, mint, programId);
|
|
354
|
+
}));
|
|
355
|
+
const { value: hash, context } = await connection.getLatestBlockhashAndContext({ commitment });
|
|
356
|
+
const messageV0 = new web3_js_1.TransactionMessage({
|
|
357
|
+
payerKey: payer,
|
|
358
|
+
recentBlockhash: hash.blockhash,
|
|
359
|
+
instructions: ixs,
|
|
360
|
+
}).compileToV0Message();
|
|
361
|
+
const tx = new web3_js_1.VersionedTransaction(messageV0);
|
|
362
|
+
return { tx, hash, context };
|
|
363
|
+
}
|
|
364
|
+
exports.generateCreateAtaBatchTx = generateCreateAtaBatchTx;
|
|
365
|
+
/**
|
|
366
|
+
* Creates ATA for an array of owners
|
|
367
|
+
* @param connection - Solana client connection
|
|
368
|
+
* @param invoker - Transaction invoker and payer
|
|
369
|
+
* @param paramsBatch - Array of Params for an each ATA account: {mint, owner}
|
|
370
|
+
* @param commitment - optional commitment that will be used to fetch Blockhash
|
|
371
|
+
* @param rate - throttle rate for tx sending
|
|
372
|
+
* @returns Transaction signature
|
|
373
|
+
*/
|
|
374
|
+
async function createAtaBatch(connection, invoker, paramsBatch, commitment, rate) {
|
|
375
|
+
const { tx, hash, context } = await generateCreateAtaBatchTx(connection, invoker.publicKey, await enrichAtaParams(connection, paramsBatch), commitment);
|
|
376
|
+
return signAndExecuteTransaction(connection, invoker, tx, { hash, context, commitment }, { sendRate: rate });
|
|
377
|
+
}
|
|
378
|
+
exports.createAtaBatch = createAtaBatch;
|
|
379
|
+
/**
|
|
380
|
+
* Utility function that checks whether associated token accounts exist and return instructions to populate them if not
|
|
381
|
+
* @param connection - Solana client connection
|
|
382
|
+
* @param owners - Array of ATA owners
|
|
383
|
+
* @param mint - Mint for which ATA will be checked
|
|
384
|
+
* @param invoker - Transaction invoker and payer
|
|
385
|
+
* @param programId - Program ID of the Mint
|
|
386
|
+
* @returns Array of Transaction Instructions that should be added to a transaction
|
|
387
|
+
*/
|
|
388
|
+
async function checkOrCreateAtaBatch(connection, owners, mint, invoker, programId) {
|
|
389
|
+
const ixs = [];
|
|
390
|
+
if (!programId) {
|
|
391
|
+
programId = (await getMintAndProgram(connection, mint)).tokenProgramId;
|
|
392
|
+
}
|
|
393
|
+
// TODO: optimize fetching and maps/arrays
|
|
394
|
+
const atas = [];
|
|
395
|
+
for (const owner of owners) {
|
|
396
|
+
atas.push(await ata(mint, owner, programId));
|
|
397
|
+
}
|
|
398
|
+
const response = await connection.getMultipleAccountsInfo(atas);
|
|
399
|
+
for (let i = 0; i < response.length; i++) {
|
|
400
|
+
if (!response[i]) {
|
|
401
|
+
ixs.push((0, spl_token_1.createAssociatedTokenAccountInstruction)(invoker.publicKey, atas[i], owners[i], mint, programId));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return ixs;
|
|
405
|
+
}
|
|
406
|
+
exports.checkOrCreateAtaBatch = checkOrCreateAtaBatch;
|
|
407
|
+
/**
|
|
408
|
+
* Create Base instructions for Solana
|
|
409
|
+
* - sets compute price if `computePrice` is provided
|
|
410
|
+
* - sets compute limit if `computeLimit` is provided
|
|
411
|
+
*/
|
|
412
|
+
function prepareBaseInstructions(connection, { computePrice, computeLimit }) {
|
|
413
|
+
const ixs = [];
|
|
414
|
+
if (computePrice) {
|
|
415
|
+
ixs.push(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: computePrice }));
|
|
416
|
+
}
|
|
417
|
+
if (computeLimit) {
|
|
418
|
+
ixs.push(web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({ units: computeLimit }));
|
|
419
|
+
}
|
|
420
|
+
return ixs;
|
|
421
|
+
}
|
|
422
|
+
exports.prepareBaseInstructions = prepareBaseInstructions;
|
|
423
|
+
/**
|
|
424
|
+
* Retrieve information about a mint and its program ID, support all Token Programs.
|
|
425
|
+
*
|
|
426
|
+
* @param connection Connection to use
|
|
427
|
+
* @param address Mint account
|
|
428
|
+
* @param commitment Desired level of commitment for querying the state
|
|
429
|
+
*
|
|
430
|
+
* @return Mint information
|
|
431
|
+
*/
|
|
432
|
+
async function getMintAndProgram(connection, address, commitment) {
|
|
433
|
+
const accountInfo = await connection.getAccountInfo(address, commitment);
|
|
434
|
+
let programId = accountInfo?.owner;
|
|
435
|
+
if (!programId?.equals(spl_token_1.TOKEN_PROGRAM_ID) && !programId?.equals(spl_token_1.TOKEN_2022_PROGRAM_ID)) {
|
|
436
|
+
programId = spl_token_1.TOKEN_PROGRAM_ID;
|
|
437
|
+
}
|
|
438
|
+
return {
|
|
439
|
+
mint: (0, spl_token_1.unpackMint)(address, accountInfo, programId),
|
|
440
|
+
tokenProgramId: programId,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
exports.getMintAndProgram = getMintAndProgram;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ContractError = exports.IChain = exports.ICluster = void 0;
|
|
4
|
+
// Utility types
|
|
5
|
+
var ICluster;
|
|
6
|
+
(function (ICluster) {
|
|
7
|
+
ICluster["Mainnet"] = "mainnet";
|
|
8
|
+
ICluster["Devnet"] = "devnet";
|
|
9
|
+
ICluster["Testnet"] = "testnet";
|
|
10
|
+
ICluster["Local"] = "local";
|
|
11
|
+
})(ICluster = exports.ICluster || (exports.ICluster = {}));
|
|
12
|
+
var IChain;
|
|
13
|
+
(function (IChain) {
|
|
14
|
+
IChain["Solana"] = "Solana";
|
|
15
|
+
IChain["Aptos"] = "Aptos";
|
|
16
|
+
IChain["Ethereum"] = "Ethereum";
|
|
17
|
+
IChain["BNB"] = "BNB";
|
|
18
|
+
IChain["Polygon"] = "Polygon";
|
|
19
|
+
IChain["Sui"] = "Sui";
|
|
20
|
+
})(IChain = exports.IChain || (exports.IChain = {}));
|
|
21
|
+
/**
|
|
22
|
+
* Error wrapper for calls made to the contract on chain
|
|
23
|
+
*/
|
|
24
|
+
class ContractError extends Error {
|
|
25
|
+
/**
|
|
26
|
+
* Constructs the Error Wrapper
|
|
27
|
+
* @param error Original error raised probably by the chain SDK
|
|
28
|
+
* @param code extracted code from the error if managed to parse it
|
|
29
|
+
*/
|
|
30
|
+
constructor(error, code, description) {
|
|
31
|
+
super(error.message); // Call the base class constructor with the error message
|
|
32
|
+
this.contractErrorCode = code ?? null;
|
|
33
|
+
this.description = description ?? null;
|
|
34
|
+
// Copy properties from the original error
|
|
35
|
+
Object.setPrototypeOf(this, ContractError.prototype);
|
|
36
|
+
this.name = "ContractError"; // Set the name property
|
|
37
|
+
this.stack = error.stack;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
exports.ContractError = ContractError;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.sleep = exports.handleContractError = exports.getScaledBigNumber = exports.getNumberFromBigNumber = void 0;
|
|
7
|
+
const bignumber_js_1 = __importDefault(require("bignumber.js"));
|
|
8
|
+
const types_js_1 = require("./types.js");
|
|
9
|
+
/**
|
|
10
|
+
* Used for token amounts conversion from their Big Number representation to number.
|
|
11
|
+
* Get value in the highest units from BigNumber representation of the same value in the smallest units.
|
|
12
|
+
* @param {BigNumber} value - Big Number representation of value in the smallest units.
|
|
13
|
+
* @param {number} decimals - Number of decimals the token has.
|
|
14
|
+
*/
|
|
15
|
+
const getNumberFromBigNumber = (bigNum, decimals) => {
|
|
16
|
+
return bigNum.div((0, bignumber_js_1.default)(10).pow(decimals)).toNumber();
|
|
17
|
+
};
|
|
18
|
+
exports.getNumberFromBigNumber = getNumberFromBigNumber;
|
|
19
|
+
/**
|
|
20
|
+
* Used for conversion of token amounts to their Big Number representation.
|
|
21
|
+
* Get Big Number representation in the smallest units from the same value in the highest units.
|
|
22
|
+
* @param {number} value - Number of tokens you want to convert to its BigNumber representation.
|
|
23
|
+
* @param {number} decimals - Number of decimals the token has.
|
|
24
|
+
*/
|
|
25
|
+
const getScaledBigNumber = (value, decimals) => {
|
|
26
|
+
return new bignumber_js_1.default(value).times(new bignumber_js_1.default(10).pow(decimals));
|
|
27
|
+
};
|
|
28
|
+
exports.getScaledBigNumber = getScaledBigNumber;
|
|
29
|
+
/**
|
|
30
|
+
* Used to make on chain calls to the contract and wrap raised errors if any
|
|
31
|
+
* @param func function that interacts with the contract
|
|
32
|
+
* @param callback callback that may be used to extract error code
|
|
33
|
+
* @returns {T}
|
|
34
|
+
*/
|
|
35
|
+
async function handleContractError(func, callback) {
|
|
36
|
+
try {
|
|
37
|
+
return await func();
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
if (err instanceof Error) {
|
|
41
|
+
if (callback) {
|
|
42
|
+
throw new types_js_1.ContractError(err, callback(err));
|
|
43
|
+
}
|
|
44
|
+
throw new types_js_1.ContractError(err);
|
|
45
|
+
}
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
exports.handleContractError = handleContractError;
|
|
50
|
+
/**
|
|
51
|
+
* Pause async function execution for given amount of milliseconds
|
|
52
|
+
* @param ms millisecond to sleep for
|
|
53
|
+
*/
|
|
54
|
+
function sleep(ms) {
|
|
55
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
56
|
+
}
|
|
57
|
+
exports.sleep = sleep;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { Connection, PublicKey, TransactionInstruction } from "@solana/web3.js";
|
|
2
|
-
import
|
|
3
|
-
export declare const prepareWrappedAccount: (connection: Connection, senderAddress: PublicKey, amount:
|
|
2
|
+
import BigNumber from "bignumber.js";
|
|
3
|
+
export declare const prepareWrappedAccount: (connection: Connection, senderAddress: PublicKey, amount: BigNumber) => Promise<TransactionInstruction[]>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { getAssociatedTokenAddress, NATIVE_MINT, createAssociatedTokenAccountInstruction, createSyncNativeInstruction, } from "@solana/spl-token";
|
|
2
|
+
import { SystemProgram } from "@solana/web3.js";
|
|
3
|
+
export const prepareWrappedAccount = async (connection, senderAddress, amount) => {
|
|
4
|
+
const tokenAccount = await getAssociatedTokenAddress(NATIVE_MINT, senderAddress, true);
|
|
5
|
+
const accInfo = await connection.getParsedAccountInfo(tokenAccount);
|
|
6
|
+
const instructions = (accInfo.value?.lamports ?? 0) > 0
|
|
7
|
+
? []
|
|
8
|
+
: [createAssociatedTokenAccountInstruction(senderAddress, tokenAccount, senderAddress, NATIVE_MINT)];
|
|
9
|
+
return [
|
|
10
|
+
...instructions,
|
|
11
|
+
SystemProgram.transfer({
|
|
12
|
+
fromPubkey: senderAddress,
|
|
13
|
+
toPubkey: tokenAccount,
|
|
14
|
+
lamports: amount.toNumber(),
|
|
15
|
+
}),
|
|
16
|
+
createSyncNativeInstruction(tokenAccount),
|
|
17
|
+
];
|
|
18
|
+
};
|
|
@@ -2,7 +2,7 @@ import { Mint } from "@solana/spl-token";
|
|
|
2
2
|
import { SignerWalletAdapter } from "@solana/wallet-adapter-base";
|
|
3
3
|
import { BlockhashWithExpiryBlockHeight, Commitment, Connection, Keypair, PublicKey, Transaction, TransactionInstruction, SignatureStatus, VersionedTransaction, Context, RpcResponseAndContext, SimulatedTransactionResponse } from "@solana/web3.js";
|
|
4
4
|
import PQueue from "p-queue";
|
|
5
|
-
import { Account, AtaParams, ConfirmationParams, ITransactionSolanaExt, ThrottleParams } from "./types";
|
|
5
|
+
import { Account, AtaParams, ConfirmationParams, ITransactionSolanaExt, ThrottleParams } from "./types.js";
|
|
6
6
|
export declare const buildSendThrottler: (sendRate: number) => PQueue;
|
|
7
7
|
/**
|
|
8
8
|
* Wrapper function for Solana web3 getProgramAccounts with slightly better call interface
|