@0dotxyz/p0-ts-sdk 1.1.0-alpha.1 → 1.1.0-alpha.11
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.cjs +15899 -4579
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +204 -129
- package/dist/index.d.ts +204 -129
- package/dist/index.js +15897 -4579
- package/dist/index.js.map +1 -1
- package/dist/{rewards.types-CaEoVXqe.d.cts → rewards.types-C0f0ZwWk.d.cts} +3 -1
- package/dist/{rewards.types-CaEoVXqe.d.ts → rewards.types-C0f0ZwWk.d.ts} +3 -1
- package/dist/vendor.cjs +100 -2626
- package/dist/vendor.cjs.map +1 -1
- package/dist/vendor.d.cts +48 -20
- package/dist/vendor.d.ts +48 -20
- package/dist/vendor.js +86 -2613
- package/dist/vendor.js.map +1 -1
- package/package.json +1 -1
package/dist/vendor.cjs
CHANGED
|
@@ -35,2504 +35,6 @@ var BN2__default = /*#__PURE__*/_interopDefault(BN2);
|
|
|
35
35
|
var borsh__namespace = /*#__PURE__*/_interopNamespace(borsh);
|
|
36
36
|
var Decimal3__default = /*#__PURE__*/_interopDefault(Decimal3);
|
|
37
37
|
|
|
38
|
-
var __create = Object.create;
|
|
39
|
-
var __defProp = Object.defineProperty;
|
|
40
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
41
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
42
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
43
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
44
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
45
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
46
|
-
}) : x)(function(x) {
|
|
47
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
48
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
49
|
-
});
|
|
50
|
-
var __commonJS = (cb, mod) => function __require2() {
|
|
51
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
52
|
-
};
|
|
53
|
-
var __copyProps = (to, from, except, desc) => {
|
|
54
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
55
|
-
for (let key of __getOwnPropNames(from))
|
|
56
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
57
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
58
|
-
}
|
|
59
|
-
return to;
|
|
60
|
-
};
|
|
61
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
62
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
63
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
64
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
65
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
66
|
-
__defProp(target, "default", { value: mod, enumerable: true }) ,
|
|
67
|
-
mod
|
|
68
|
-
));
|
|
69
|
-
|
|
70
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/nodeWallet.js
|
|
71
|
-
var require_nodeWallet = __commonJS({
|
|
72
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/nodeWallet.js"(exports$1) {
|
|
73
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
74
|
-
exports$1.NodeWallet = void 0;
|
|
75
|
-
var web3_js_1 = __require("@solana/web3.js");
|
|
76
|
-
var NodeWallet = class _NodeWallet {
|
|
77
|
-
/**
|
|
78
|
-
* @param payer Keypair of the associated payer
|
|
79
|
-
*/
|
|
80
|
-
constructor(payer) {
|
|
81
|
-
this.payer = payer;
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Factory for the local wallet.
|
|
85
|
-
* Makes use of the `MARGINFI_WALLET` env var, with fallback to `$HOME/.config/solana/id.json`.
|
|
86
|
-
*/
|
|
87
|
-
static local() {
|
|
88
|
-
const process = __require("process");
|
|
89
|
-
const payer = web3_js_1.Keypair.fromSecretKey(Buffer.from(JSON.parse(__require("fs").readFileSync(process.env.MARGINFI_WALLET || __require("path").join(__require("os").homedir(), ".config/solana/id.json"), {
|
|
90
|
-
encoding: "utf-8"
|
|
91
|
-
}))));
|
|
92
|
-
return new _NodeWallet(payer);
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Factory for the Anchor local wallet.
|
|
96
|
-
*/
|
|
97
|
-
static anchor() {
|
|
98
|
-
const process = __require("process");
|
|
99
|
-
if (!process.env.ANCHOR_WALLET || process.env.ANCHOR_WALLET === "") {
|
|
100
|
-
throw new Error("expected environment variable `ANCHOR_WALLET` is not set.");
|
|
101
|
-
}
|
|
102
|
-
const payer = web3_js_1.Keypair.fromSecretKey(Buffer.from(JSON.parse(__require("fs").readFileSync(process.env.ANCHOR_WALLET, {
|
|
103
|
-
encoding: "utf-8"
|
|
104
|
-
}))));
|
|
105
|
-
return new _NodeWallet(payer);
|
|
106
|
-
}
|
|
107
|
-
async signTransaction(tx) {
|
|
108
|
-
if ("version" in tx) {
|
|
109
|
-
tx.sign([this.payer]);
|
|
110
|
-
} else {
|
|
111
|
-
tx.partialSign(this.payer);
|
|
112
|
-
}
|
|
113
|
-
return tx;
|
|
114
|
-
}
|
|
115
|
-
async signAllTransactions(txs) {
|
|
116
|
-
return txs.map((tx) => {
|
|
117
|
-
if ("version" in tx) {
|
|
118
|
-
tx.sign([this.payer]);
|
|
119
|
-
return tx;
|
|
120
|
-
} else {
|
|
121
|
-
tx.partialSign(this.payer);
|
|
122
|
-
return tx;
|
|
123
|
-
}
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
get publicKey() {
|
|
127
|
-
return this.payer.publicKey;
|
|
128
|
-
}
|
|
129
|
-
};
|
|
130
|
-
exports$1.NodeWallet = NodeWallet;
|
|
131
|
-
}
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/cache.js
|
|
135
|
-
var require_cache = __commonJS({
|
|
136
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/cache.js"(exports$1) {
|
|
137
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
138
|
-
exports$1.loadTokenMetadatas = loadTokenMetadatas;
|
|
139
|
-
exports$1.loadBankMetadatas = loadBankMetadatas;
|
|
140
|
-
exports$1.loadStakedBankMetadatas = loadStakedBankMetadatas;
|
|
141
|
-
var superstruct_1 = __require("superstruct");
|
|
142
|
-
var TokenMetadataRaw = (0, superstruct_1.object)({
|
|
143
|
-
address: (0, superstruct_1.string)(),
|
|
144
|
-
chainId: (0, superstruct_1.number)(),
|
|
145
|
-
decimals: (0, superstruct_1.number)(),
|
|
146
|
-
name: (0, superstruct_1.string)(),
|
|
147
|
-
symbol: (0, superstruct_1.string)(),
|
|
148
|
-
logoURI: (0, superstruct_1.string)(),
|
|
149
|
-
extensions: (0, superstruct_1.object)()
|
|
150
|
-
});
|
|
151
|
-
(0, superstruct_1.array)(TokenMetadataRaw);
|
|
152
|
-
function parseTokenMetadata(tokenMetadataRaw) {
|
|
153
|
-
return {
|
|
154
|
-
address: tokenMetadataRaw.address,
|
|
155
|
-
icon: tokenMetadataRaw.logoURI,
|
|
156
|
-
name: tokenMetadataRaw.name,
|
|
157
|
-
symbol: tokenMetadataRaw.symbol,
|
|
158
|
-
decimals: tokenMetadataRaw.decimals
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
function parseTokenMetadatas(tokenMetadataListRaw) {
|
|
162
|
-
return tokenMetadataListRaw.reduce((config, current, _) => ({
|
|
163
|
-
[current.symbol]: parseTokenMetadata(current),
|
|
164
|
-
...config
|
|
165
|
-
}), {});
|
|
166
|
-
}
|
|
167
|
-
async function loadTokenMetadatas(cacheUrl = "https://storage.googleapis.com/mrgn-public/mrgn-token-metadata-cache.json") {
|
|
168
|
-
const response = await fetch(cacheUrl, {
|
|
169
|
-
headers: {
|
|
170
|
-
Accept: "application/json"
|
|
171
|
-
},
|
|
172
|
-
method: "GET"
|
|
173
|
-
});
|
|
174
|
-
if (response.status === 200) {
|
|
175
|
-
const responseData = await response.json();
|
|
176
|
-
return parseTokenMetadatas(responseData);
|
|
177
|
-
} else {
|
|
178
|
-
throw new Error("Failed to fetch token metadata cache");
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
var BankMetadataRaw = (0, superstruct_1.object)({
|
|
182
|
-
groupAddress: (0, superstruct_1.optional)((0, superstruct_1.string)()),
|
|
183
|
-
// optional as only present on arena cache not mrgnlend
|
|
184
|
-
validatorVoteAccount: (0, superstruct_1.optional)((0, superstruct_1.string)()),
|
|
185
|
-
// optional as only present on staked asset banks
|
|
186
|
-
bankAddress: (0, superstruct_1.string)(),
|
|
187
|
-
tokenAddress: (0, superstruct_1.string)(),
|
|
188
|
-
tokenName: (0, superstruct_1.string)(),
|
|
189
|
-
tokenSymbol: (0, superstruct_1.string)()
|
|
190
|
-
});
|
|
191
|
-
var BankMetadataList = (0, superstruct_1.array)(BankMetadataRaw);
|
|
192
|
-
function parseBankMetadata(bankMetadataRaw) {
|
|
193
|
-
return {
|
|
194
|
-
tokenAddress: bankMetadataRaw.tokenAddress,
|
|
195
|
-
tokenName: bankMetadataRaw.tokenName,
|
|
196
|
-
tokenSymbol: bankMetadataRaw.tokenSymbol,
|
|
197
|
-
validatorVoteAccount: bankMetadataRaw.validatorVoteAccount ?? void 0
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
function parseBankMetadatas(bankMetadataListRaw) {
|
|
201
|
-
return bankMetadataListRaw.reduce((config, current, _) => ({
|
|
202
|
-
[current.bankAddress]: parseBankMetadata(current),
|
|
203
|
-
...config
|
|
204
|
-
}), {});
|
|
205
|
-
}
|
|
206
|
-
async function loadStakedBankMetadatas(cacheUrl = "https://storage.googleapis.com/mrgn-public/mrgn-staked-bank-metadata-cache.json") {
|
|
207
|
-
return loadBankMetadatas(cacheUrl);
|
|
208
|
-
}
|
|
209
|
-
async function loadBankMetadatas(cacheUrl = "https://storage.googleapis.com/mrgn-public/mrgn-bank-metadata-cache.json") {
|
|
210
|
-
const response = await fetch(cacheUrl, {
|
|
211
|
-
headers: {
|
|
212
|
-
Accept: "application/json"
|
|
213
|
-
},
|
|
214
|
-
method: "GET"
|
|
215
|
-
});
|
|
216
|
-
if (response.status === 200) {
|
|
217
|
-
const responseData = await response.json();
|
|
218
|
-
(0, superstruct_1.assert)(responseData, BankMetadataList);
|
|
219
|
-
return parseBankMetadatas(responseData);
|
|
220
|
-
} else {
|
|
221
|
-
throw new Error("Failed to fetch bank metadata cache");
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
});
|
|
226
|
-
|
|
227
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/types.js
|
|
228
|
-
var require_types = __commonJS({
|
|
229
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/types.js"(exports$1) {
|
|
230
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
231
|
-
}
|
|
232
|
-
});
|
|
233
|
-
|
|
234
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/misc.js
|
|
235
|
-
var require_misc = __commonJS({
|
|
236
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/misc.js"(exports$1) {
|
|
237
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
238
|
-
exports$1.loadKeypair = loadKeypair;
|
|
239
|
-
exports$1.getValueInsensitive = getValueInsensitive;
|
|
240
|
-
exports$1.sleep = sleep;
|
|
241
|
-
exports$1.chunks = chunks;
|
|
242
|
-
exports$1.setTimeoutPromise = setTimeoutPromise;
|
|
243
|
-
exports$1.chunkedGetRawMultipleAccountInfos = chunkedGetRawMultipleAccountInfos;
|
|
244
|
-
exports$1.chunkedGetRawMultipleAccountInfoOrderedWithNulls = chunkedGetRawMultipleAccountInfoOrderedWithNulls;
|
|
245
|
-
exports$1.chunkedGetRawMultipleAccountInfoOrdered = chunkedGetRawMultipleAccountInfoOrdered;
|
|
246
|
-
var web3_js_1 = __require("@solana/web3.js");
|
|
247
|
-
function loadKeypair(keypairPath) {
|
|
248
|
-
const path = __require("path");
|
|
249
|
-
if (!keypairPath || keypairPath == "") {
|
|
250
|
-
throw new Error("Keypair is required!");
|
|
251
|
-
}
|
|
252
|
-
if (keypairPath[0] === "~") {
|
|
253
|
-
keypairPath = path.join(__require("os").homedir(), keypairPath.slice(1));
|
|
254
|
-
}
|
|
255
|
-
const keyPath = path.normalize(keypairPath);
|
|
256
|
-
return web3_js_1.Keypair.fromSecretKey(new Uint8Array(JSON.parse(__require("fs").readFileSync(keyPath).toString())));
|
|
257
|
-
}
|
|
258
|
-
function getValueInsensitive(map, key) {
|
|
259
|
-
const lowerCaseLabel = key.toLowerCase();
|
|
260
|
-
for (let key2 in map) {
|
|
261
|
-
if (key2.toLowerCase() === lowerCaseLabel) {
|
|
262
|
-
return map[key2];
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
throw new Error(`Token metadata not found for ${key}`);
|
|
266
|
-
}
|
|
267
|
-
function sleep(ms) {
|
|
268
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
269
|
-
}
|
|
270
|
-
function chunks(array3, size) {
|
|
271
|
-
return Array.apply(0, new Array(Math.ceil(array3.length / size))).map((_, index) => array3.slice(index * size, (index + 1) * size));
|
|
272
|
-
}
|
|
273
|
-
function setTimeoutPromise(duration, message) {
|
|
274
|
-
return new Promise((_, reject) => setTimeout(() => reject(new Error(message)), duration));
|
|
275
|
-
}
|
|
276
|
-
async function chunkedGetRawMultipleAccountInfos(connection, pks, batchChunkSize = 1e3, maxAccountsChunkSize = 100) {
|
|
277
|
-
const accountInfoMap = /* @__PURE__ */ new Map();
|
|
278
|
-
let contextSlot = 0;
|
|
279
|
-
const batches = chunkArray(pks, batchChunkSize);
|
|
280
|
-
for (let i = 0; i < batches.length; i++) {
|
|
281
|
-
const batch = batches[i];
|
|
282
|
-
const batchRequest = chunkArray(batch, maxAccountsChunkSize).map((pubkeys) => ({
|
|
283
|
-
methodName: "getMultipleAccounts",
|
|
284
|
-
args: connection._buildArgs([pubkeys], "confirmed", "base64")
|
|
285
|
-
}));
|
|
286
|
-
let accountInfos = [];
|
|
287
|
-
let retries = 0;
|
|
288
|
-
const maxRetries = 3;
|
|
289
|
-
while (retries < maxRetries && accountInfos.length === 0) {
|
|
290
|
-
try {
|
|
291
|
-
accountInfos = await connection._rpcBatchRequest(batchRequest).then((batchResults) => {
|
|
292
|
-
contextSlot = Math.max(...batchResults.map((res) => res.result.context.slot));
|
|
293
|
-
const accounts = batchResults.reduce((acc, res) => {
|
|
294
|
-
acc.push(...res.result.value);
|
|
295
|
-
return acc;
|
|
296
|
-
}, []);
|
|
297
|
-
return accounts;
|
|
298
|
-
});
|
|
299
|
-
} catch (error) {
|
|
300
|
-
retries++;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
if (accountInfos.length === 0) {
|
|
304
|
-
throw new Error(`Failed to fetch account infos after ${maxRetries} retries`);
|
|
305
|
-
}
|
|
306
|
-
accountInfos.forEach((item, index) => {
|
|
307
|
-
const publicKey6 = batch[index];
|
|
308
|
-
if (item) {
|
|
309
|
-
accountInfoMap.set(publicKey6, {
|
|
310
|
-
...item,
|
|
311
|
-
owner: new web3_js_1.PublicKey(item.owner),
|
|
312
|
-
data: Buffer.from(item.data[0], "base64")
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
return [contextSlot, accountInfoMap];
|
|
318
|
-
}
|
|
319
|
-
async function chunkedGetRawMultipleAccountInfoOrderedWithNulls(connection, pks, batchChunkSize = 1e3, maxAccountsChunkSize = 100) {
|
|
320
|
-
const allAccountInfos = [];
|
|
321
|
-
const batches = chunkArray(pks, batchChunkSize);
|
|
322
|
-
for (let i = 0; i < batches.length; i++) {
|
|
323
|
-
const batch = batches[i];
|
|
324
|
-
const batchRequest = chunkArray(batch, maxAccountsChunkSize).map((pubkeys) => ({
|
|
325
|
-
methodName: "getMultipleAccounts",
|
|
326
|
-
args: connection._buildArgs([pubkeys], "confirmed", "base64")
|
|
327
|
-
}));
|
|
328
|
-
let accountInfos = [];
|
|
329
|
-
let retries = 0;
|
|
330
|
-
const maxRetries = 3;
|
|
331
|
-
while (retries < maxRetries && accountInfos.length === 0) {
|
|
332
|
-
try {
|
|
333
|
-
accountInfos = await connection._rpcBatchRequest(batchRequest).then((batchResults) => {
|
|
334
|
-
const accounts = batchResults.reduce((acc, res) => {
|
|
335
|
-
acc.push(...res.result.value);
|
|
336
|
-
return acc;
|
|
337
|
-
}, []);
|
|
338
|
-
return accounts;
|
|
339
|
-
});
|
|
340
|
-
} catch (error) {
|
|
341
|
-
retries++;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
if (accountInfos.length === 0) {
|
|
345
|
-
throw new Error(`Failed to fetch account infos after ${maxRetries} retries`);
|
|
346
|
-
}
|
|
347
|
-
accountInfos.forEach((item) => {
|
|
348
|
-
if (item) {
|
|
349
|
-
allAccountInfos.push({
|
|
350
|
-
...item,
|
|
351
|
-
owner: new web3_js_1.PublicKey(item.owner),
|
|
352
|
-
data: Buffer.from(item.data[0], "base64")
|
|
353
|
-
});
|
|
354
|
-
} else {
|
|
355
|
-
allAccountInfos.push(null);
|
|
356
|
-
}
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
return allAccountInfos;
|
|
360
|
-
}
|
|
361
|
-
async function chunkedGetRawMultipleAccountInfoOrdered(connection, pks, batchChunkSize = 1e3, maxAccountsChunkSize = 100) {
|
|
362
|
-
const allAccountInfos = [];
|
|
363
|
-
const batches = chunkArray(pks, batchChunkSize);
|
|
364
|
-
for (let i = 0; i < batches.length; i++) {
|
|
365
|
-
const batch = batches[i];
|
|
366
|
-
const batchRequest = chunkArray(batch, maxAccountsChunkSize).map((pubkeys) => ({
|
|
367
|
-
methodName: "getMultipleAccounts",
|
|
368
|
-
args: connection._buildArgs([pubkeys], "confirmed", "base64")
|
|
369
|
-
}));
|
|
370
|
-
let accountInfos = [];
|
|
371
|
-
let retries = 0;
|
|
372
|
-
const maxRetries = 3;
|
|
373
|
-
while (retries < maxRetries && accountInfos.length === 0) {
|
|
374
|
-
try {
|
|
375
|
-
accountInfos = await connection._rpcBatchRequest(batchRequest).then((batchResults) => {
|
|
376
|
-
const accounts = batchResults.reduce((acc, res) => {
|
|
377
|
-
acc.push(...res.result.value);
|
|
378
|
-
return acc;
|
|
379
|
-
}, []);
|
|
380
|
-
return accounts;
|
|
381
|
-
});
|
|
382
|
-
} catch (error) {
|
|
383
|
-
retries++;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
if (accountInfos.length === 0) {
|
|
387
|
-
throw new Error(`Failed to fetch account infos after ${maxRetries} retries`);
|
|
388
|
-
}
|
|
389
|
-
accountInfos.forEach((item) => {
|
|
390
|
-
if (item) {
|
|
391
|
-
allAccountInfos.push({
|
|
392
|
-
...item,
|
|
393
|
-
owner: new web3_js_1.PublicKey(item.owner),
|
|
394
|
-
data: Buffer.from(item.data[0], "base64")
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
return allAccountInfos;
|
|
400
|
-
}
|
|
401
|
-
function chunkArray(array3, chunkSize) {
|
|
402
|
-
const chunks2 = [];
|
|
403
|
-
for (let i = 0; i < array3.length; i += chunkSize) {
|
|
404
|
-
chunks2.push(array3.slice(i, i + chunkSize));
|
|
405
|
-
}
|
|
406
|
-
return chunks2;
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
});
|
|
410
|
-
|
|
411
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/math.js
|
|
412
|
-
var require_math = __commonJS({
|
|
413
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/math.js"(exports$1) {
|
|
414
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
415
|
-
exports$1.ceil = ceil;
|
|
416
|
-
exports$1.floor = floor;
|
|
417
|
-
exports$1.median = median;
|
|
418
|
-
function floor(value, decimals) {
|
|
419
|
-
return Math.floor(value * 10 ** decimals) / 10 ** decimals;
|
|
420
|
-
}
|
|
421
|
-
function ceil(value, decimals) {
|
|
422
|
-
return Math.ceil(value * 10 ** decimals) / 10 ** decimals;
|
|
423
|
-
}
|
|
424
|
-
function median(values) {
|
|
425
|
-
if (values.length === 0) {
|
|
426
|
-
throw new Error("Input array is empty");
|
|
427
|
-
}
|
|
428
|
-
values = [...values].sort((a, b) => a - b);
|
|
429
|
-
const half = Math.floor(values.length / 2);
|
|
430
|
-
return values.length % 2 ? values[half] : (values[half - 1] + values[half]) / 2;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
});
|
|
434
|
-
|
|
435
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/misc.consts.js
|
|
436
|
-
var require_misc_consts = __commonJS({
|
|
437
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/misc.consts.js"(exports$1) {
|
|
438
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
439
|
-
exports$1.MAX_U64 = exports$1.HOURS_PER_YEAR = void 0;
|
|
440
|
-
exports$1.HOURS_PER_YEAR = 365.25 * 24;
|
|
441
|
-
exports$1.MAX_U64 = BigInt("18446744073709551615").toString();
|
|
442
|
-
}
|
|
443
|
-
});
|
|
444
|
-
|
|
445
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/program.consts.js
|
|
446
|
-
var require_program_consts = __commonJS({
|
|
447
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/program.consts.js"(exports$1) {
|
|
448
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
449
|
-
exports$1.STAKE_CONFIG_ID = exports$1.SYSVAR_STAKE_HISTORY_ID = exports$1.SYSVAR_CLOCK_ID = exports$1.SYSVAR_RENT_ID = exports$1.SYSTEM_PROGRAM_ID = exports$1.MPL_METADATA_PROGRAM_ID = exports$1.STAKE_PROGRAM_ID = exports$1.SINGLE_POOL_PROGRAM_ID = exports$1.MARGINFI_PROGRAM = exports$1.JUPITER_V6_PROGRAM = exports$1.LUT_PROGRAM_AUTHORITY_INDEX = void 0;
|
|
450
|
-
var web3_js_1 = __require("@solana/web3.js");
|
|
451
|
-
exports$1.LUT_PROGRAM_AUTHORITY_INDEX = 5;
|
|
452
|
-
exports$1.JUPITER_V6_PROGRAM = new web3_js_1.PublicKey("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");
|
|
453
|
-
exports$1.MARGINFI_PROGRAM = new web3_js_1.PublicKey("MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA");
|
|
454
|
-
exports$1.SINGLE_POOL_PROGRAM_ID = new web3_js_1.PublicKey("SVSPxpvHdN29nkVg9rPapPNDddN5DipNLRUFhyjFThE");
|
|
455
|
-
exports$1.STAKE_PROGRAM_ID = new web3_js_1.PublicKey("Stake11111111111111111111111111111111111111");
|
|
456
|
-
exports$1.MPL_METADATA_PROGRAM_ID = new web3_js_1.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
|
|
457
|
-
exports$1.SYSTEM_PROGRAM_ID = new web3_js_1.PublicKey("11111111111111111111111111111111");
|
|
458
|
-
exports$1.SYSVAR_RENT_ID = new web3_js_1.PublicKey("SysvarRent111111111111111111111111111111111");
|
|
459
|
-
exports$1.SYSVAR_CLOCK_ID = new web3_js_1.PublicKey("SysvarC1ock11111111111111111111111111111111");
|
|
460
|
-
exports$1.SYSVAR_STAKE_HISTORY_ID = new web3_js_1.PublicKey("SysvarStakeHistory1111111111111111111111111");
|
|
461
|
-
exports$1.STAKE_CONFIG_ID = new web3_js_1.PublicKey("StakeConfig11111111111111111111111111111111");
|
|
462
|
-
}
|
|
463
|
-
});
|
|
464
|
-
|
|
465
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/token.consts.js
|
|
466
|
-
var require_token_consts = __commonJS({
|
|
467
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/token.consts.js"(exports$1) {
|
|
468
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
469
|
-
exports$1.USDC_DECIMALS = exports$1.USDC_MINT = exports$1.LST_MINT = exports$1.WSOL_MINT = void 0;
|
|
470
|
-
var web3_js_1 = __require("@solana/web3.js");
|
|
471
|
-
exports$1.WSOL_MINT = new web3_js_1.PublicKey("So11111111111111111111111111111111111111112");
|
|
472
|
-
exports$1.LST_MINT = new web3_js_1.PublicKey("LSTxxxnJzKDFSLr4dUkPcmCf5VyryEqzPLz5j4bpxFp");
|
|
473
|
-
exports$1.USDC_MINT = new web3_js_1.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
|
474
|
-
exports$1.USDC_DECIMALS = 6;
|
|
475
|
-
}
|
|
476
|
-
});
|
|
477
|
-
|
|
478
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/transaction.consts.js
|
|
479
|
-
var require_transaction_consts = __commonJS({
|
|
480
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/transaction.consts.js"(exports$1) {
|
|
481
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
482
|
-
exports$1.SKIP_SIMULATION = exports$1.PRIORITY_TX_SIZE = exports$1.BUNDLE_TX_SIZE = exports$1.MAX_TX_SIZE = exports$1.DEFAULT_CONFIRM_OPTS = exports$1.DEFAULT_SEND_OPTS = exports$1.DEFAULT_COMMITMENT = void 0;
|
|
483
|
-
exports$1.DEFAULT_COMMITMENT = "processed";
|
|
484
|
-
exports$1.DEFAULT_SEND_OPTS = {
|
|
485
|
-
skipPreflight: false,
|
|
486
|
-
preflightCommitment: exports$1.DEFAULT_COMMITMENT
|
|
487
|
-
};
|
|
488
|
-
exports$1.DEFAULT_CONFIRM_OPTS = {
|
|
489
|
-
commitment: exports$1.DEFAULT_COMMITMENT,
|
|
490
|
-
...exports$1.DEFAULT_SEND_OPTS
|
|
491
|
-
};
|
|
492
|
-
exports$1.MAX_TX_SIZE = 1232;
|
|
493
|
-
exports$1.BUNDLE_TX_SIZE = 81;
|
|
494
|
-
exports$1.PRIORITY_TX_SIZE = 44;
|
|
495
|
-
exports$1.SKIP_SIMULATION = false;
|
|
496
|
-
}
|
|
497
|
-
});
|
|
498
|
-
|
|
499
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/index.js
|
|
500
|
-
var require_constants = __commonJS({
|
|
501
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/constants/index.js"(exports$1) {
|
|
502
|
-
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
503
|
-
if (k2 === void 0) k2 = k;
|
|
504
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
505
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
506
|
-
desc = { enumerable: true, get: function() {
|
|
507
|
-
return m[k];
|
|
508
|
-
} };
|
|
509
|
-
}
|
|
510
|
-
Object.defineProperty(o, k2, desc);
|
|
511
|
-
}) : (function(o, m, k, k2) {
|
|
512
|
-
if (k2 === void 0) k2 = k;
|
|
513
|
-
o[k2] = m[k];
|
|
514
|
-
}));
|
|
515
|
-
var __exportStar = exports$1 && exports$1.__exportStar || function(m, exports2) {
|
|
516
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
|
|
517
|
-
};
|
|
518
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
519
|
-
__exportStar(require_misc_consts(), exports$1);
|
|
520
|
-
__exportStar(require_program_consts(), exports$1);
|
|
521
|
-
__exportStar(require_token_consts(), exports$1);
|
|
522
|
-
__exportStar(require_transaction_consts(), exports$1);
|
|
523
|
-
}
|
|
524
|
-
});
|
|
525
|
-
|
|
526
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/accounting.utils.js
|
|
527
|
-
var require_accounting_utils = __commonJS({
|
|
528
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/accounting.utils.js"(exports$1) {
|
|
529
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
530
|
-
exports$1.aprToApy = exports$1.apyToApr = void 0;
|
|
531
|
-
exports$1.calculateInterestFromApy = calculateInterestFromApy;
|
|
532
|
-
exports$1.calculateApyFromInterest = calculateApyFromInterest;
|
|
533
|
-
var constants_1 = require_constants();
|
|
534
|
-
var apyToApr = (apy, compoundingFrequency = constants_1.HOURS_PER_YEAR) => ((1 + apy) ** (1 / compoundingFrequency) - 1) * compoundingFrequency;
|
|
535
|
-
exports$1.apyToApr = apyToApr;
|
|
536
|
-
var aprToApy2 = (apr, compoundingFrequency = constants_1.HOURS_PER_YEAR, apyCap = 3) => Math.min((1 + apr / compoundingFrequency) ** compoundingFrequency - 1, apyCap);
|
|
537
|
-
exports$1.aprToApy = aprToApy2;
|
|
538
|
-
function calculateInterestFromApy(principal, durationInYears, apy) {
|
|
539
|
-
return principal * apy * durationInYears;
|
|
540
|
-
}
|
|
541
|
-
function calculateApyFromInterest(principal, durationInYears, interest) {
|
|
542
|
-
return interest / (principal * durationInYears);
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
});
|
|
546
|
-
|
|
547
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/conversion.utils.js
|
|
548
|
-
var require_conversion_utils = __commonJS({
|
|
549
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/conversion.utils.js"(exports$1) {
|
|
550
|
-
var __importDefault = exports$1 && exports$1.__importDefault || function(mod) {
|
|
551
|
-
return mod && mod.__esModule ? mod : { "default": mod };
|
|
552
|
-
};
|
|
553
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
554
|
-
exports$1.composeRemainingAccounts = void 0;
|
|
555
|
-
exports$1.wrappedI80F48toBigNumber = wrappedI80F48toBigNumber;
|
|
556
|
-
exports$1.bigNumberToWrappedI80F48 = bigNumberToWrappedI80F48;
|
|
557
|
-
exports$1.toNumber = toNumber;
|
|
558
|
-
exports$1.toBigNumber = toBigNumber;
|
|
559
|
-
exports$1.uiToNative = uiToNative;
|
|
560
|
-
exports$1.uiToNativeBigNumber = uiToNativeBigNumber;
|
|
561
|
-
exports$1.nativeToUi = nativeToUi;
|
|
562
|
-
exports$1.shortenAddress = shortenAddress;
|
|
563
|
-
exports$1.bpsToPercentile = bpsToPercentile;
|
|
564
|
-
var anchor_1 = __require("@coral-xyz/anchor");
|
|
565
|
-
var bignumber_js_1 = __importDefault(__require("bignumber.js"));
|
|
566
|
-
var decimal_js_1 = __require("decimal.js");
|
|
567
|
-
var I80F48_FRACTIONAL_BYTES = 6;
|
|
568
|
-
var I80F48_TOTAL_BYTES = 16;
|
|
569
|
-
var I80F48_DIVISOR = new decimal_js_1.Decimal(2).pow(8 * I80F48_FRACTIONAL_BYTES);
|
|
570
|
-
function wrappedI80F48toBigNumber(wrapped) {
|
|
571
|
-
let bytesLE = wrapped.value;
|
|
572
|
-
if (bytesLE.length !== I80F48_TOTAL_BYTES) {
|
|
573
|
-
throw new Error(`Expected a ${I80F48_TOTAL_BYTES}-byte buffer`);
|
|
574
|
-
}
|
|
575
|
-
let bytesBE = bytesLE.slice();
|
|
576
|
-
bytesBE.reverse();
|
|
577
|
-
let signChar = "";
|
|
578
|
-
const msb = bytesBE[0];
|
|
579
|
-
if (msb & 128) {
|
|
580
|
-
signChar = "-";
|
|
581
|
-
bytesBE = bytesBE.map((v) => ~v & 255);
|
|
582
|
-
}
|
|
583
|
-
let hex = signChar + "0x" + bytesBE.map((v) => v.toString(16).padStart(2, "0")).join("");
|
|
584
|
-
let decoded = new decimal_js_1.Decimal(hex).dividedBy(I80F48_DIVISOR);
|
|
585
|
-
return new bignumber_js_1.default(decoded.toString());
|
|
586
|
-
}
|
|
587
|
-
function bigNumberToWrappedI80F48(value) {
|
|
588
|
-
let decimalValue = new decimal_js_1.Decimal(value.toString());
|
|
589
|
-
const isNegative = decimalValue.isNegative();
|
|
590
|
-
decimalValue = decimalValue.times(I80F48_DIVISOR);
|
|
591
|
-
let wrappedValue = new anchor_1.BN(decimalValue.round().toFixed()).toArray();
|
|
592
|
-
if (wrappedValue.length < I80F48_TOTAL_BYTES) {
|
|
593
|
-
const padding = Array(I80F48_TOTAL_BYTES - wrappedValue.length).fill(0);
|
|
594
|
-
wrappedValue.unshift(...padding);
|
|
595
|
-
}
|
|
596
|
-
if (isNegative) {
|
|
597
|
-
wrappedValue[wrappedValue.length - 1] |= 128;
|
|
598
|
-
wrappedValue = wrappedValue.map((v) => ~v & 255);
|
|
599
|
-
}
|
|
600
|
-
wrappedValue.reverse();
|
|
601
|
-
return { value: wrappedValue };
|
|
602
|
-
}
|
|
603
|
-
function toNumber(amount) {
|
|
604
|
-
let amt;
|
|
605
|
-
if (typeof amount === "number") {
|
|
606
|
-
amt = amount;
|
|
607
|
-
} else if (typeof amount === "string") {
|
|
608
|
-
amt = Number(amount);
|
|
609
|
-
} else {
|
|
610
|
-
amt = amount.toNumber();
|
|
611
|
-
}
|
|
612
|
-
return amt;
|
|
613
|
-
}
|
|
614
|
-
function toBigNumber(amount) {
|
|
615
|
-
let amt;
|
|
616
|
-
if (amount instanceof bignumber_js_1.default) {
|
|
617
|
-
amt = amount;
|
|
618
|
-
} else {
|
|
619
|
-
amt = new bignumber_js_1.default(amount.toString());
|
|
620
|
-
}
|
|
621
|
-
return amt;
|
|
622
|
-
}
|
|
623
|
-
function uiToNative(amount, decimals) {
|
|
624
|
-
let amt = toBigNumber(amount);
|
|
625
|
-
return new anchor_1.BN(amt.times(10 ** decimals).toFixed(0, bignumber_js_1.default.ROUND_FLOOR));
|
|
626
|
-
}
|
|
627
|
-
function uiToNativeBigNumber(amount, decimals) {
|
|
628
|
-
let amt = toBigNumber(amount);
|
|
629
|
-
return amt.times(10 ** decimals);
|
|
630
|
-
}
|
|
631
|
-
function nativeToUi(amount, decimals) {
|
|
632
|
-
let amt = toBigNumber(amount);
|
|
633
|
-
return amt.div(10 ** decimals).toNumber();
|
|
634
|
-
}
|
|
635
|
-
function shortenAddress(pubkey, chars = 4) {
|
|
636
|
-
const pubkeyStr = pubkey.toString();
|
|
637
|
-
return `${pubkeyStr.slice(0, chars)}...${pubkeyStr.slice(-chars)}`;
|
|
638
|
-
}
|
|
639
|
-
function bpsToPercentile(bps) {
|
|
640
|
-
return bps / 1e4;
|
|
641
|
-
}
|
|
642
|
-
var composeRemainingAccounts = (banksAndOracles) => {
|
|
643
|
-
banksAndOracles.sort((a, b) => {
|
|
644
|
-
const A = a[0].toBytes();
|
|
645
|
-
const B = b[0].toBytes();
|
|
646
|
-
for (let i = 0; i < 32; i++) {
|
|
647
|
-
if (A[i] !== B[i]) {
|
|
648
|
-
return B[i] - A[i];
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
return 0;
|
|
652
|
-
});
|
|
653
|
-
return banksAndOracles.flat();
|
|
654
|
-
};
|
|
655
|
-
exports$1.composeRemainingAccounts = composeRemainingAccounts;
|
|
656
|
-
}
|
|
657
|
-
});
|
|
658
|
-
|
|
659
|
-
// node_modules/.pnpm/numeral@2.0.6/node_modules/numeral/numeral.js
|
|
660
|
-
var require_numeral = __commonJS({
|
|
661
|
-
"node_modules/.pnpm/numeral@2.0.6/node_modules/numeral/numeral.js"(exports$1, module) {
|
|
662
|
-
(function(global, factory) {
|
|
663
|
-
if (typeof define === "function" && define.amd) {
|
|
664
|
-
define(factory);
|
|
665
|
-
} else if (typeof module === "object" && module.exports) {
|
|
666
|
-
module.exports = factory();
|
|
667
|
-
} else {
|
|
668
|
-
global.numeral = factory();
|
|
669
|
-
}
|
|
670
|
-
})(exports$1, function() {
|
|
671
|
-
var numeral, _, VERSION = "2.0.6", formats = {}, locales = {}, defaults = {
|
|
672
|
-
currentLocale: "en",
|
|
673
|
-
zeroFormat: null,
|
|
674
|
-
nullFormat: null,
|
|
675
|
-
defaultFormat: "0,0",
|
|
676
|
-
scalePercentBy100: true
|
|
677
|
-
}, options = {
|
|
678
|
-
currentLocale: defaults.currentLocale,
|
|
679
|
-
zeroFormat: defaults.zeroFormat,
|
|
680
|
-
nullFormat: defaults.nullFormat,
|
|
681
|
-
defaultFormat: defaults.defaultFormat,
|
|
682
|
-
scalePercentBy100: defaults.scalePercentBy100
|
|
683
|
-
};
|
|
684
|
-
function Numeral(input, number) {
|
|
685
|
-
this._input = input;
|
|
686
|
-
this._value = number;
|
|
687
|
-
}
|
|
688
|
-
numeral = function(input) {
|
|
689
|
-
var value, kind, unformatFunction, regexp;
|
|
690
|
-
if (numeral.isNumeral(input)) {
|
|
691
|
-
value = input.value();
|
|
692
|
-
} else if (input === 0 || typeof input === "undefined") {
|
|
693
|
-
value = 0;
|
|
694
|
-
} else if (input === null || _.isNaN(input)) {
|
|
695
|
-
value = null;
|
|
696
|
-
} else if (typeof input === "string") {
|
|
697
|
-
if (options.zeroFormat && input === options.zeroFormat) {
|
|
698
|
-
value = 0;
|
|
699
|
-
} else if (options.nullFormat && input === options.nullFormat || !input.replace(/[^0-9]+/g, "").length) {
|
|
700
|
-
value = null;
|
|
701
|
-
} else {
|
|
702
|
-
for (kind in formats) {
|
|
703
|
-
regexp = typeof formats[kind].regexps.unformat === "function" ? formats[kind].regexps.unformat() : formats[kind].regexps.unformat;
|
|
704
|
-
if (regexp && input.match(regexp)) {
|
|
705
|
-
unformatFunction = formats[kind].unformat;
|
|
706
|
-
break;
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
unformatFunction = unformatFunction || numeral._.stringToNumber;
|
|
710
|
-
value = unformatFunction(input);
|
|
711
|
-
}
|
|
712
|
-
} else {
|
|
713
|
-
value = Number(input) || null;
|
|
714
|
-
}
|
|
715
|
-
return new Numeral(input, value);
|
|
716
|
-
};
|
|
717
|
-
numeral.version = VERSION;
|
|
718
|
-
numeral.isNumeral = function(obj) {
|
|
719
|
-
return obj instanceof Numeral;
|
|
720
|
-
};
|
|
721
|
-
numeral._ = _ = {
|
|
722
|
-
// formats numbers separators, decimals places, signs, abbreviations
|
|
723
|
-
numberToFormat: function(value, format, roundingFunction) {
|
|
724
|
-
var locale = locales[numeral.options.currentLocale], negP = false, optDec = false, leadingCount = 0, abbr = "", trillion = 1e12, billion = 1e9, million = 1e6, thousand = 1e3, decimal = "", neg = false, abbrForce, abs, int, precision, signed, thousands, output;
|
|
725
|
-
value = value || 0;
|
|
726
|
-
abs = Math.abs(value);
|
|
727
|
-
if (numeral._.includes(format, "(")) {
|
|
728
|
-
negP = true;
|
|
729
|
-
format = format.replace(/[\(|\)]/g, "");
|
|
730
|
-
} else if (numeral._.includes(format, "+") || numeral._.includes(format, "-")) {
|
|
731
|
-
signed = numeral._.includes(format, "+") ? format.indexOf("+") : value < 0 ? format.indexOf("-") : -1;
|
|
732
|
-
format = format.replace(/[\+|\-]/g, "");
|
|
733
|
-
}
|
|
734
|
-
if (numeral._.includes(format, "a")) {
|
|
735
|
-
abbrForce = format.match(/a(k|m|b|t)?/);
|
|
736
|
-
abbrForce = abbrForce ? abbrForce[1] : false;
|
|
737
|
-
if (numeral._.includes(format, " a")) {
|
|
738
|
-
abbr = " ";
|
|
739
|
-
}
|
|
740
|
-
format = format.replace(new RegExp(abbr + "a[kmbt]?"), "");
|
|
741
|
-
if (abs >= trillion && !abbrForce || abbrForce === "t") {
|
|
742
|
-
abbr += locale.abbreviations.trillion;
|
|
743
|
-
value = value / trillion;
|
|
744
|
-
} else if (abs < trillion && abs >= billion && !abbrForce || abbrForce === "b") {
|
|
745
|
-
abbr += locale.abbreviations.billion;
|
|
746
|
-
value = value / billion;
|
|
747
|
-
} else if (abs < billion && abs >= million && !abbrForce || abbrForce === "m") {
|
|
748
|
-
abbr += locale.abbreviations.million;
|
|
749
|
-
value = value / million;
|
|
750
|
-
} else if (abs < million && abs >= thousand && !abbrForce || abbrForce === "k") {
|
|
751
|
-
abbr += locale.abbreviations.thousand;
|
|
752
|
-
value = value / thousand;
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
if (numeral._.includes(format, "[.]")) {
|
|
756
|
-
optDec = true;
|
|
757
|
-
format = format.replace("[.]", ".");
|
|
758
|
-
}
|
|
759
|
-
int = value.toString().split(".")[0];
|
|
760
|
-
precision = format.split(".")[1];
|
|
761
|
-
thousands = format.indexOf(",");
|
|
762
|
-
leadingCount = (format.split(".")[0].split(",")[0].match(/0/g) || []).length;
|
|
763
|
-
if (precision) {
|
|
764
|
-
if (numeral._.includes(precision, "[")) {
|
|
765
|
-
precision = precision.replace("]", "");
|
|
766
|
-
precision = precision.split("[");
|
|
767
|
-
decimal = numeral._.toFixed(value, precision[0].length + precision[1].length, roundingFunction, precision[1].length);
|
|
768
|
-
} else {
|
|
769
|
-
decimal = numeral._.toFixed(value, precision.length, roundingFunction);
|
|
770
|
-
}
|
|
771
|
-
int = decimal.split(".")[0];
|
|
772
|
-
if (numeral._.includes(decimal, ".")) {
|
|
773
|
-
decimal = locale.delimiters.decimal + decimal.split(".")[1];
|
|
774
|
-
} else {
|
|
775
|
-
decimal = "";
|
|
776
|
-
}
|
|
777
|
-
if (optDec && Number(decimal.slice(1)) === 0) {
|
|
778
|
-
decimal = "";
|
|
779
|
-
}
|
|
780
|
-
} else {
|
|
781
|
-
int = numeral._.toFixed(value, 0, roundingFunction);
|
|
782
|
-
}
|
|
783
|
-
if (abbr && !abbrForce && Number(int) >= 1e3 && abbr !== locale.abbreviations.trillion) {
|
|
784
|
-
int = String(Number(int) / 1e3);
|
|
785
|
-
switch (abbr) {
|
|
786
|
-
case locale.abbreviations.thousand:
|
|
787
|
-
abbr = locale.abbreviations.million;
|
|
788
|
-
break;
|
|
789
|
-
case locale.abbreviations.million:
|
|
790
|
-
abbr = locale.abbreviations.billion;
|
|
791
|
-
break;
|
|
792
|
-
case locale.abbreviations.billion:
|
|
793
|
-
abbr = locale.abbreviations.trillion;
|
|
794
|
-
break;
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
if (numeral._.includes(int, "-")) {
|
|
798
|
-
int = int.slice(1);
|
|
799
|
-
neg = true;
|
|
800
|
-
}
|
|
801
|
-
if (int.length < leadingCount) {
|
|
802
|
-
for (var i = leadingCount - int.length; i > 0; i--) {
|
|
803
|
-
int = "0" + int;
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
if (thousands > -1) {
|
|
807
|
-
int = int.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1" + locale.delimiters.thousands);
|
|
808
|
-
}
|
|
809
|
-
if (format.indexOf(".") === 0) {
|
|
810
|
-
int = "";
|
|
811
|
-
}
|
|
812
|
-
output = int + decimal + (abbr ? abbr : "");
|
|
813
|
-
if (negP) {
|
|
814
|
-
output = (negP && neg ? "(" : "") + output + (negP && neg ? ")" : "");
|
|
815
|
-
} else {
|
|
816
|
-
if (signed >= 0) {
|
|
817
|
-
output = signed === 0 ? (neg ? "-" : "+") + output : output + (neg ? "-" : "+");
|
|
818
|
-
} else if (neg) {
|
|
819
|
-
output = "-" + output;
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
return output;
|
|
823
|
-
},
|
|
824
|
-
// unformats numbers separators, decimals places, signs, abbreviations
|
|
825
|
-
stringToNumber: function(string) {
|
|
826
|
-
var locale = locales[options.currentLocale], stringOriginal = string, abbreviations = {
|
|
827
|
-
thousand: 3,
|
|
828
|
-
million: 6,
|
|
829
|
-
billion: 9,
|
|
830
|
-
trillion: 12
|
|
831
|
-
}, abbreviation, value, regexp;
|
|
832
|
-
if (options.zeroFormat && string === options.zeroFormat) {
|
|
833
|
-
value = 0;
|
|
834
|
-
} else if (options.nullFormat && string === options.nullFormat || !string.replace(/[^0-9]+/g, "").length) {
|
|
835
|
-
value = null;
|
|
836
|
-
} else {
|
|
837
|
-
value = 1;
|
|
838
|
-
if (locale.delimiters.decimal !== ".") {
|
|
839
|
-
string = string.replace(/\./g, "").replace(locale.delimiters.decimal, ".");
|
|
840
|
-
}
|
|
841
|
-
for (abbreviation in abbreviations) {
|
|
842
|
-
regexp = new RegExp("[^a-zA-Z]" + locale.abbreviations[abbreviation] + "(?:\\)|(\\" + locale.currency.symbol + ")?(?:\\))?)?$");
|
|
843
|
-
if (stringOriginal.match(regexp)) {
|
|
844
|
-
value *= Math.pow(10, abbreviations[abbreviation]);
|
|
845
|
-
break;
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
value *= (string.split("-").length + Math.min(string.split("(").length - 1, string.split(")").length - 1)) % 2 ? 1 : -1;
|
|
849
|
-
string = string.replace(/[^0-9\.]+/g, "");
|
|
850
|
-
value *= Number(string);
|
|
851
|
-
}
|
|
852
|
-
return value;
|
|
853
|
-
},
|
|
854
|
-
isNaN: function(value) {
|
|
855
|
-
return typeof value === "number" && isNaN(value);
|
|
856
|
-
},
|
|
857
|
-
includes: function(string, search) {
|
|
858
|
-
return string.indexOf(search) !== -1;
|
|
859
|
-
},
|
|
860
|
-
insert: function(string, subString, start) {
|
|
861
|
-
return string.slice(0, start) + subString + string.slice(start);
|
|
862
|
-
},
|
|
863
|
-
reduce: function(array3, callback) {
|
|
864
|
-
if (this === null) {
|
|
865
|
-
throw new TypeError("Array.prototype.reduce called on null or undefined");
|
|
866
|
-
}
|
|
867
|
-
if (typeof callback !== "function") {
|
|
868
|
-
throw new TypeError(callback + " is not a function");
|
|
869
|
-
}
|
|
870
|
-
var t = Object(array3), len = t.length >>> 0, k = 0, value;
|
|
871
|
-
if (arguments.length === 3) {
|
|
872
|
-
value = arguments[2];
|
|
873
|
-
} else {
|
|
874
|
-
while (k < len && !(k in t)) {
|
|
875
|
-
k++;
|
|
876
|
-
}
|
|
877
|
-
if (k >= len) {
|
|
878
|
-
throw new TypeError("Reduce of empty array with no initial value");
|
|
879
|
-
}
|
|
880
|
-
value = t[k++];
|
|
881
|
-
}
|
|
882
|
-
for (; k < len; k++) {
|
|
883
|
-
if (k in t) {
|
|
884
|
-
value = callback(value, t[k], k, t);
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
return value;
|
|
888
|
-
},
|
|
889
|
-
/**
|
|
890
|
-
* Computes the multiplier necessary to make x >= 1,
|
|
891
|
-
* effectively eliminating miscalculations caused by
|
|
892
|
-
* finite precision.
|
|
893
|
-
*/
|
|
894
|
-
multiplier: function(x) {
|
|
895
|
-
var parts = x.toString().split(".");
|
|
896
|
-
return parts.length < 2 ? 1 : Math.pow(10, parts[1].length);
|
|
897
|
-
},
|
|
898
|
-
/**
|
|
899
|
-
* Given a variable number of arguments, returns the maximum
|
|
900
|
-
* multiplier that must be used to normalize an operation involving
|
|
901
|
-
* all of them.
|
|
902
|
-
*/
|
|
903
|
-
correctionFactor: function() {
|
|
904
|
-
var args = Array.prototype.slice.call(arguments);
|
|
905
|
-
return args.reduce(function(accum, next) {
|
|
906
|
-
var mn = _.multiplier(next);
|
|
907
|
-
return accum > mn ? accum : mn;
|
|
908
|
-
}, 1);
|
|
909
|
-
},
|
|
910
|
-
/**
|
|
911
|
-
* Implementation of toFixed() that treats floats more like decimals
|
|
912
|
-
*
|
|
913
|
-
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
|
|
914
|
-
* problems for accounting- and finance-related software.
|
|
915
|
-
*/
|
|
916
|
-
toFixed: function(value, maxDecimals, roundingFunction, optionals) {
|
|
917
|
-
var splitValue = value.toString().split("."), minDecimals = maxDecimals - (optionals || 0), boundedPrecision, optionalsRegExp, power, output;
|
|
918
|
-
if (splitValue.length === 2) {
|
|
919
|
-
boundedPrecision = Math.min(Math.max(splitValue[1].length, minDecimals), maxDecimals);
|
|
920
|
-
} else {
|
|
921
|
-
boundedPrecision = minDecimals;
|
|
922
|
-
}
|
|
923
|
-
power = Math.pow(10, boundedPrecision);
|
|
924
|
-
output = (roundingFunction(value + "e+" + boundedPrecision) / power).toFixed(boundedPrecision);
|
|
925
|
-
if (optionals > maxDecimals - boundedPrecision) {
|
|
926
|
-
optionalsRegExp = new RegExp("\\.?0{1," + (optionals - (maxDecimals - boundedPrecision)) + "}$");
|
|
927
|
-
output = output.replace(optionalsRegExp, "");
|
|
928
|
-
}
|
|
929
|
-
return output;
|
|
930
|
-
}
|
|
931
|
-
};
|
|
932
|
-
numeral.options = options;
|
|
933
|
-
numeral.formats = formats;
|
|
934
|
-
numeral.locales = locales;
|
|
935
|
-
numeral.locale = function(key) {
|
|
936
|
-
if (key) {
|
|
937
|
-
options.currentLocale = key.toLowerCase();
|
|
938
|
-
}
|
|
939
|
-
return options.currentLocale;
|
|
940
|
-
};
|
|
941
|
-
numeral.localeData = function(key) {
|
|
942
|
-
if (!key) {
|
|
943
|
-
return locales[options.currentLocale];
|
|
944
|
-
}
|
|
945
|
-
key = key.toLowerCase();
|
|
946
|
-
if (!locales[key]) {
|
|
947
|
-
throw new Error("Unknown locale : " + key);
|
|
948
|
-
}
|
|
949
|
-
return locales[key];
|
|
950
|
-
};
|
|
951
|
-
numeral.reset = function() {
|
|
952
|
-
for (var property in defaults) {
|
|
953
|
-
options[property] = defaults[property];
|
|
954
|
-
}
|
|
955
|
-
};
|
|
956
|
-
numeral.zeroFormat = function(format) {
|
|
957
|
-
options.zeroFormat = typeof format === "string" ? format : null;
|
|
958
|
-
};
|
|
959
|
-
numeral.nullFormat = function(format) {
|
|
960
|
-
options.nullFormat = typeof format === "string" ? format : null;
|
|
961
|
-
};
|
|
962
|
-
numeral.defaultFormat = function(format) {
|
|
963
|
-
options.defaultFormat = typeof format === "string" ? format : "0.0";
|
|
964
|
-
};
|
|
965
|
-
numeral.register = function(type, name, format) {
|
|
966
|
-
name = name.toLowerCase();
|
|
967
|
-
if (this[type + "s"][name]) {
|
|
968
|
-
throw new TypeError(name + " " + type + " already registered.");
|
|
969
|
-
}
|
|
970
|
-
this[type + "s"][name] = format;
|
|
971
|
-
return format;
|
|
972
|
-
};
|
|
973
|
-
numeral.validate = function(val, culture) {
|
|
974
|
-
var _decimalSep, _thousandSep, _currSymbol, _valArray, _abbrObj, _thousandRegEx, localeData, temp;
|
|
975
|
-
if (typeof val !== "string") {
|
|
976
|
-
val += "";
|
|
977
|
-
if (console.warn) {
|
|
978
|
-
console.warn("Numeral.js: Value is not string. It has been co-erced to: ", val);
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
val = val.trim();
|
|
982
|
-
if (!!val.match(/^\d+$/)) {
|
|
983
|
-
return true;
|
|
984
|
-
}
|
|
985
|
-
if (val === "") {
|
|
986
|
-
return false;
|
|
987
|
-
}
|
|
988
|
-
try {
|
|
989
|
-
localeData = numeral.localeData(culture);
|
|
990
|
-
} catch (e) {
|
|
991
|
-
localeData = numeral.localeData(numeral.locale());
|
|
992
|
-
}
|
|
993
|
-
_currSymbol = localeData.currency.symbol;
|
|
994
|
-
_abbrObj = localeData.abbreviations;
|
|
995
|
-
_decimalSep = localeData.delimiters.decimal;
|
|
996
|
-
if (localeData.delimiters.thousands === ".") {
|
|
997
|
-
_thousandSep = "\\.";
|
|
998
|
-
} else {
|
|
999
|
-
_thousandSep = localeData.delimiters.thousands;
|
|
1000
|
-
}
|
|
1001
|
-
temp = val.match(/^[^\d]+/);
|
|
1002
|
-
if (temp !== null) {
|
|
1003
|
-
val = val.substr(1);
|
|
1004
|
-
if (temp[0] !== _currSymbol) {
|
|
1005
|
-
return false;
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
temp = val.match(/[^\d]+$/);
|
|
1009
|
-
if (temp !== null) {
|
|
1010
|
-
val = val.slice(0, -1);
|
|
1011
|
-
if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million && temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
|
|
1012
|
-
return false;
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
_thousandRegEx = new RegExp(_thousandSep + "{2}");
|
|
1016
|
-
if (!val.match(/[^\d.,]/g)) {
|
|
1017
|
-
_valArray = val.split(_decimalSep);
|
|
1018
|
-
if (_valArray.length > 2) {
|
|
1019
|
-
return false;
|
|
1020
|
-
} else {
|
|
1021
|
-
if (_valArray.length < 2) {
|
|
1022
|
-
return !!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx);
|
|
1023
|
-
} else {
|
|
1024
|
-
if (_valArray[0].length === 1) {
|
|
1025
|
-
return !!_valArray[0].match(/^\d+$/) && !_valArray[0].match(_thousandRegEx) && !!_valArray[1].match(/^\d+$/);
|
|
1026
|
-
} else {
|
|
1027
|
-
return !!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx) && !!_valArray[1].match(/^\d+$/);
|
|
1028
|
-
}
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
return false;
|
|
1033
|
-
};
|
|
1034
|
-
numeral.fn = Numeral.prototype = {
|
|
1035
|
-
clone: function() {
|
|
1036
|
-
return numeral(this);
|
|
1037
|
-
},
|
|
1038
|
-
format: function(inputString, roundingFunction) {
|
|
1039
|
-
var value = this._value, format = inputString || options.defaultFormat, kind, output, formatFunction;
|
|
1040
|
-
roundingFunction = roundingFunction || Math.round;
|
|
1041
|
-
if (value === 0 && options.zeroFormat !== null) {
|
|
1042
|
-
output = options.zeroFormat;
|
|
1043
|
-
} else if (value === null && options.nullFormat !== null) {
|
|
1044
|
-
output = options.nullFormat;
|
|
1045
|
-
} else {
|
|
1046
|
-
for (kind in formats) {
|
|
1047
|
-
if (format.match(formats[kind].regexps.format)) {
|
|
1048
|
-
formatFunction = formats[kind].format;
|
|
1049
|
-
break;
|
|
1050
|
-
}
|
|
1051
|
-
}
|
|
1052
|
-
formatFunction = formatFunction || numeral._.numberToFormat;
|
|
1053
|
-
output = formatFunction(value, format, roundingFunction);
|
|
1054
|
-
}
|
|
1055
|
-
return output;
|
|
1056
|
-
},
|
|
1057
|
-
value: function() {
|
|
1058
|
-
return this._value;
|
|
1059
|
-
},
|
|
1060
|
-
input: function() {
|
|
1061
|
-
return this._input;
|
|
1062
|
-
},
|
|
1063
|
-
set: function(value) {
|
|
1064
|
-
this._value = Number(value);
|
|
1065
|
-
return this;
|
|
1066
|
-
},
|
|
1067
|
-
add: function(value) {
|
|
1068
|
-
var corrFactor = _.correctionFactor.call(null, this._value, value);
|
|
1069
|
-
function cback(accum, curr, currI, O) {
|
|
1070
|
-
return accum + Math.round(corrFactor * curr);
|
|
1071
|
-
}
|
|
1072
|
-
this._value = _.reduce([this._value, value], cback, 0) / corrFactor;
|
|
1073
|
-
return this;
|
|
1074
|
-
},
|
|
1075
|
-
subtract: function(value) {
|
|
1076
|
-
var corrFactor = _.correctionFactor.call(null, this._value, value);
|
|
1077
|
-
function cback(accum, curr, currI, O) {
|
|
1078
|
-
return accum - Math.round(corrFactor * curr);
|
|
1079
|
-
}
|
|
1080
|
-
this._value = _.reduce([value], cback, Math.round(this._value * corrFactor)) / corrFactor;
|
|
1081
|
-
return this;
|
|
1082
|
-
},
|
|
1083
|
-
multiply: function(value) {
|
|
1084
|
-
function cback(accum, curr, currI, O) {
|
|
1085
|
-
var corrFactor = _.correctionFactor(accum, curr);
|
|
1086
|
-
return Math.round(accum * corrFactor) * Math.round(curr * corrFactor) / Math.round(corrFactor * corrFactor);
|
|
1087
|
-
}
|
|
1088
|
-
this._value = _.reduce([this._value, value], cback, 1);
|
|
1089
|
-
return this;
|
|
1090
|
-
},
|
|
1091
|
-
divide: function(value) {
|
|
1092
|
-
function cback(accum, curr, currI, O) {
|
|
1093
|
-
var corrFactor = _.correctionFactor(accum, curr);
|
|
1094
|
-
return Math.round(accum * corrFactor) / Math.round(curr * corrFactor);
|
|
1095
|
-
}
|
|
1096
|
-
this._value = _.reduce([this._value, value], cback);
|
|
1097
|
-
return this;
|
|
1098
|
-
},
|
|
1099
|
-
difference: function(value) {
|
|
1100
|
-
return Math.abs(numeral(this._value).subtract(value).value());
|
|
1101
|
-
}
|
|
1102
|
-
};
|
|
1103
|
-
numeral.register("locale", "en", {
|
|
1104
|
-
delimiters: {
|
|
1105
|
-
thousands: ",",
|
|
1106
|
-
decimal: "."
|
|
1107
|
-
},
|
|
1108
|
-
abbreviations: {
|
|
1109
|
-
thousand: "k",
|
|
1110
|
-
million: "m",
|
|
1111
|
-
billion: "b",
|
|
1112
|
-
trillion: "t"
|
|
1113
|
-
},
|
|
1114
|
-
ordinal: function(number) {
|
|
1115
|
-
var b = number % 10;
|
|
1116
|
-
return ~~(number % 100 / 10) === 1 ? "th" : b === 1 ? "st" : b === 2 ? "nd" : b === 3 ? "rd" : "th";
|
|
1117
|
-
},
|
|
1118
|
-
currency: {
|
|
1119
|
-
symbol: "$"
|
|
1120
|
-
}
|
|
1121
|
-
});
|
|
1122
|
-
(function() {
|
|
1123
|
-
numeral.register("format", "bps", {
|
|
1124
|
-
regexps: {
|
|
1125
|
-
format: /(BPS)/,
|
|
1126
|
-
unformat: /(BPS)/
|
|
1127
|
-
},
|
|
1128
|
-
format: function(value, format, roundingFunction) {
|
|
1129
|
-
var space = numeral._.includes(format, " BPS") ? " " : "", output;
|
|
1130
|
-
value = value * 1e4;
|
|
1131
|
-
format = format.replace(/\s?BPS/, "");
|
|
1132
|
-
output = numeral._.numberToFormat(value, format, roundingFunction);
|
|
1133
|
-
if (numeral._.includes(output, ")")) {
|
|
1134
|
-
output = output.split("");
|
|
1135
|
-
output.splice(-1, 0, space + "BPS");
|
|
1136
|
-
output = output.join("");
|
|
1137
|
-
} else {
|
|
1138
|
-
output = output + space + "BPS";
|
|
1139
|
-
}
|
|
1140
|
-
return output;
|
|
1141
|
-
},
|
|
1142
|
-
unformat: function(string) {
|
|
1143
|
-
return +(numeral._.stringToNumber(string) * 1e-4).toFixed(15);
|
|
1144
|
-
}
|
|
1145
|
-
});
|
|
1146
|
-
})();
|
|
1147
|
-
(function() {
|
|
1148
|
-
var decimal = {
|
|
1149
|
-
base: 1e3,
|
|
1150
|
-
suffixes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
|
|
1151
|
-
}, binary = {
|
|
1152
|
-
base: 1024,
|
|
1153
|
-
suffixes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
|
|
1154
|
-
};
|
|
1155
|
-
var allSuffixes = decimal.suffixes.concat(binary.suffixes.filter(function(item) {
|
|
1156
|
-
return decimal.suffixes.indexOf(item) < 0;
|
|
1157
|
-
}));
|
|
1158
|
-
var unformatRegex = allSuffixes.join("|");
|
|
1159
|
-
unformatRegex = "(" + unformatRegex.replace("B", "B(?!PS)") + ")";
|
|
1160
|
-
numeral.register("format", "bytes", {
|
|
1161
|
-
regexps: {
|
|
1162
|
-
format: /([0\s]i?b)/,
|
|
1163
|
-
unformat: new RegExp(unformatRegex)
|
|
1164
|
-
},
|
|
1165
|
-
format: function(value, format, roundingFunction) {
|
|
1166
|
-
var output, bytes = numeral._.includes(format, "ib") ? binary : decimal, suffix = numeral._.includes(format, " b") || numeral._.includes(format, " ib") ? " " : "", power, min, max;
|
|
1167
|
-
format = format.replace(/\s?i?b/, "");
|
|
1168
|
-
for (power = 0; power <= bytes.suffixes.length; power++) {
|
|
1169
|
-
min = Math.pow(bytes.base, power);
|
|
1170
|
-
max = Math.pow(bytes.base, power + 1);
|
|
1171
|
-
if (value === null || value === 0 || value >= min && value < max) {
|
|
1172
|
-
suffix += bytes.suffixes[power];
|
|
1173
|
-
if (min > 0) {
|
|
1174
|
-
value = value / min;
|
|
1175
|
-
}
|
|
1176
|
-
break;
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
output = numeral._.numberToFormat(value, format, roundingFunction);
|
|
1180
|
-
return output + suffix;
|
|
1181
|
-
},
|
|
1182
|
-
unformat: function(string) {
|
|
1183
|
-
var value = numeral._.stringToNumber(string), power, bytesMultiplier;
|
|
1184
|
-
if (value) {
|
|
1185
|
-
for (power = decimal.suffixes.length - 1; power >= 0; power--) {
|
|
1186
|
-
if (numeral._.includes(string, decimal.suffixes[power])) {
|
|
1187
|
-
bytesMultiplier = Math.pow(decimal.base, power);
|
|
1188
|
-
break;
|
|
1189
|
-
}
|
|
1190
|
-
if (numeral._.includes(string, binary.suffixes[power])) {
|
|
1191
|
-
bytesMultiplier = Math.pow(binary.base, power);
|
|
1192
|
-
break;
|
|
1193
|
-
}
|
|
1194
|
-
}
|
|
1195
|
-
value *= bytesMultiplier || 1;
|
|
1196
|
-
}
|
|
1197
|
-
return value;
|
|
1198
|
-
}
|
|
1199
|
-
});
|
|
1200
|
-
})();
|
|
1201
|
-
(function() {
|
|
1202
|
-
numeral.register("format", "currency", {
|
|
1203
|
-
regexps: {
|
|
1204
|
-
format: /(\$)/
|
|
1205
|
-
},
|
|
1206
|
-
format: function(value, format, roundingFunction) {
|
|
1207
|
-
var locale = numeral.locales[numeral.options.currentLocale], symbols = {
|
|
1208
|
-
before: format.match(/^([\+|\-|\(|\s|\$]*)/)[0],
|
|
1209
|
-
after: format.match(/([\+|\-|\)|\s|\$]*)$/)[0]
|
|
1210
|
-
}, output, symbol, i;
|
|
1211
|
-
format = format.replace(/\s?\$\s?/, "");
|
|
1212
|
-
output = numeral._.numberToFormat(value, format, roundingFunction);
|
|
1213
|
-
if (value >= 0) {
|
|
1214
|
-
symbols.before = symbols.before.replace(/[\-\(]/, "");
|
|
1215
|
-
symbols.after = symbols.after.replace(/[\-\)]/, "");
|
|
1216
|
-
} else if (value < 0 && (!numeral._.includes(symbols.before, "-") && !numeral._.includes(symbols.before, "("))) {
|
|
1217
|
-
symbols.before = "-" + symbols.before;
|
|
1218
|
-
}
|
|
1219
|
-
for (i = 0; i < symbols.before.length; i++) {
|
|
1220
|
-
symbol = symbols.before[i];
|
|
1221
|
-
switch (symbol) {
|
|
1222
|
-
case "$":
|
|
1223
|
-
output = numeral._.insert(output, locale.currency.symbol, i);
|
|
1224
|
-
break;
|
|
1225
|
-
case " ":
|
|
1226
|
-
output = numeral._.insert(output, " ", i + locale.currency.symbol.length - 1);
|
|
1227
|
-
break;
|
|
1228
|
-
}
|
|
1229
|
-
}
|
|
1230
|
-
for (i = symbols.after.length - 1; i >= 0; i--) {
|
|
1231
|
-
symbol = symbols.after[i];
|
|
1232
|
-
switch (symbol) {
|
|
1233
|
-
case "$":
|
|
1234
|
-
output = i === symbols.after.length - 1 ? output + locale.currency.symbol : numeral._.insert(output, locale.currency.symbol, -(symbols.after.length - (1 + i)));
|
|
1235
|
-
break;
|
|
1236
|
-
case " ":
|
|
1237
|
-
output = i === symbols.after.length - 1 ? output + " " : numeral._.insert(output, " ", -(symbols.after.length - (1 + i) + locale.currency.symbol.length - 1));
|
|
1238
|
-
break;
|
|
1239
|
-
}
|
|
1240
|
-
}
|
|
1241
|
-
return output;
|
|
1242
|
-
}
|
|
1243
|
-
});
|
|
1244
|
-
})();
|
|
1245
|
-
(function() {
|
|
1246
|
-
numeral.register("format", "exponential", {
|
|
1247
|
-
regexps: {
|
|
1248
|
-
format: /(e\+|e-)/,
|
|
1249
|
-
unformat: /(e\+|e-)/
|
|
1250
|
-
},
|
|
1251
|
-
format: function(value, format, roundingFunction) {
|
|
1252
|
-
var output, exponential = typeof value === "number" && !numeral._.isNaN(value) ? value.toExponential() : "0e+0", parts = exponential.split("e");
|
|
1253
|
-
format = format.replace(/e[\+|\-]{1}0/, "");
|
|
1254
|
-
output = numeral._.numberToFormat(Number(parts[0]), format, roundingFunction);
|
|
1255
|
-
return output + "e" + parts[1];
|
|
1256
|
-
},
|
|
1257
|
-
unformat: function(string) {
|
|
1258
|
-
var parts = numeral._.includes(string, "e+") ? string.split("e+") : string.split("e-"), value = Number(parts[0]), power = Number(parts[1]);
|
|
1259
|
-
power = numeral._.includes(string, "e-") ? power *= -1 : power;
|
|
1260
|
-
function cback(accum, curr, currI, O) {
|
|
1261
|
-
var corrFactor = numeral._.correctionFactor(accum, curr), num = accum * corrFactor * (curr * corrFactor) / (corrFactor * corrFactor);
|
|
1262
|
-
return num;
|
|
1263
|
-
}
|
|
1264
|
-
return numeral._.reduce([value, Math.pow(10, power)], cback, 1);
|
|
1265
|
-
}
|
|
1266
|
-
});
|
|
1267
|
-
})();
|
|
1268
|
-
(function() {
|
|
1269
|
-
numeral.register("format", "ordinal", {
|
|
1270
|
-
regexps: {
|
|
1271
|
-
format: /(o)/
|
|
1272
|
-
},
|
|
1273
|
-
format: function(value, format, roundingFunction) {
|
|
1274
|
-
var locale = numeral.locales[numeral.options.currentLocale], output, ordinal = numeral._.includes(format, " o") ? " " : "";
|
|
1275
|
-
format = format.replace(/\s?o/, "");
|
|
1276
|
-
ordinal += locale.ordinal(value);
|
|
1277
|
-
output = numeral._.numberToFormat(value, format, roundingFunction);
|
|
1278
|
-
return output + ordinal;
|
|
1279
|
-
}
|
|
1280
|
-
});
|
|
1281
|
-
})();
|
|
1282
|
-
(function() {
|
|
1283
|
-
numeral.register("format", "percentage", {
|
|
1284
|
-
regexps: {
|
|
1285
|
-
format: /(%)/,
|
|
1286
|
-
unformat: /(%)/
|
|
1287
|
-
},
|
|
1288
|
-
format: function(value, format, roundingFunction) {
|
|
1289
|
-
var space = numeral._.includes(format, " %") ? " " : "", output;
|
|
1290
|
-
if (numeral.options.scalePercentBy100) {
|
|
1291
|
-
value = value * 100;
|
|
1292
|
-
}
|
|
1293
|
-
format = format.replace(/\s?\%/, "");
|
|
1294
|
-
output = numeral._.numberToFormat(value, format, roundingFunction);
|
|
1295
|
-
if (numeral._.includes(output, ")")) {
|
|
1296
|
-
output = output.split("");
|
|
1297
|
-
output.splice(-1, 0, space + "%");
|
|
1298
|
-
output = output.join("");
|
|
1299
|
-
} else {
|
|
1300
|
-
output = output + space + "%";
|
|
1301
|
-
}
|
|
1302
|
-
return output;
|
|
1303
|
-
},
|
|
1304
|
-
unformat: function(string) {
|
|
1305
|
-
var number = numeral._.stringToNumber(string);
|
|
1306
|
-
if (numeral.options.scalePercentBy100) {
|
|
1307
|
-
return number * 0.01;
|
|
1308
|
-
}
|
|
1309
|
-
return number;
|
|
1310
|
-
}
|
|
1311
|
-
});
|
|
1312
|
-
})();
|
|
1313
|
-
(function() {
|
|
1314
|
-
numeral.register("format", "time", {
|
|
1315
|
-
regexps: {
|
|
1316
|
-
format: /(:)/,
|
|
1317
|
-
unformat: /(:)/
|
|
1318
|
-
},
|
|
1319
|
-
format: function(value, format, roundingFunction) {
|
|
1320
|
-
var hours = Math.floor(value / 60 / 60), minutes = Math.floor((value - hours * 60 * 60) / 60), seconds = Math.round(value - hours * 60 * 60 - minutes * 60);
|
|
1321
|
-
return hours + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
|
|
1322
|
-
},
|
|
1323
|
-
unformat: function(string) {
|
|
1324
|
-
var timeArray = string.split(":"), seconds = 0;
|
|
1325
|
-
if (timeArray.length === 3) {
|
|
1326
|
-
seconds = seconds + Number(timeArray[0]) * 60 * 60;
|
|
1327
|
-
seconds = seconds + Number(timeArray[1]) * 60;
|
|
1328
|
-
seconds = seconds + Number(timeArray[2]);
|
|
1329
|
-
} else if (timeArray.length === 2) {
|
|
1330
|
-
seconds = seconds + Number(timeArray[0]) * 60;
|
|
1331
|
-
seconds = seconds + Number(timeArray[1]);
|
|
1332
|
-
}
|
|
1333
|
-
return Number(seconds);
|
|
1334
|
-
}
|
|
1335
|
-
});
|
|
1336
|
-
})();
|
|
1337
|
-
return numeral;
|
|
1338
|
-
});
|
|
1339
|
-
}
|
|
1340
|
-
});
|
|
1341
|
-
|
|
1342
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/formatters.utils.js
|
|
1343
|
-
var require_formatters_utils = __commonJS({
|
|
1344
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/formatters.utils.js"(exports$1) {
|
|
1345
|
-
var __importDefault = exports$1 && exports$1.__importDefault || function(mod) {
|
|
1346
|
-
return mod && mod.__esModule ? mod : { "default": mod };
|
|
1347
|
-
};
|
|
1348
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
1349
|
-
exports$1.tokenPriceFormatter = exports$1.usdFormatterDyn = exports$1.usdFormatter = exports$1.percentFormatterMod = exports$1.percentFormatterDyn = exports$1.percentFormatter = exports$1.clampedNumeralFormatter = exports$1.numeralFormatter = exports$1.groupedNumberFormatterDyn = exports$1.groupedNumberFormatter = exports$1.CustomNumberFormat = exports$1.dynamicNumeralFormatter = void 0;
|
|
1350
|
-
var numeral_1 = __importDefault(require_numeral());
|
|
1351
|
-
var CustomNumberFormat = class extends Intl.NumberFormat {
|
|
1352
|
-
constructor(locale, options) {
|
|
1353
|
-
super(locale, options);
|
|
1354
|
-
}
|
|
1355
|
-
format(value) {
|
|
1356
|
-
if (value === 0) {
|
|
1357
|
-
return "-";
|
|
1358
|
-
} else {
|
|
1359
|
-
return super.format(value);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
};
|
|
1363
|
-
exports$1.CustomNumberFormat = CustomNumberFormat;
|
|
1364
|
-
var groupedNumberFormatter = new CustomNumberFormat("en-US", {
|
|
1365
|
-
useGrouping: true,
|
|
1366
|
-
minimumFractionDigits: 0,
|
|
1367
|
-
maximumFractionDigits: 2
|
|
1368
|
-
});
|
|
1369
|
-
exports$1.groupedNumberFormatter = groupedNumberFormatter;
|
|
1370
|
-
var numeralFormatter = (value) => {
|
|
1371
|
-
if (value < 0.01) {
|
|
1372
|
-
return "0";
|
|
1373
|
-
} else {
|
|
1374
|
-
return (0, numeral_1.default)(value).format("0.00a");
|
|
1375
|
-
}
|
|
1376
|
-
};
|
|
1377
|
-
exports$1.numeralFormatter = numeralFormatter;
|
|
1378
|
-
var dynamicNumeralFormatter = (value, options = {}) => {
|
|
1379
|
-
const {
|
|
1380
|
-
minDisplay = 1e-5,
|
|
1381
|
-
// Default minDisplay for backward compatibility
|
|
1382
|
-
maxDisplay = 1e4,
|
|
1383
|
-
// Default maxDisplay for backward compatibility
|
|
1384
|
-
tokenPrice,
|
|
1385
|
-
logging = false,
|
|
1386
|
-
ignoreMinDisplay = false,
|
|
1387
|
-
// New flag to control ignoring minDisplay
|
|
1388
|
-
forceDecimals
|
|
1389
|
-
} = options;
|
|
1390
|
-
if (value === 0 || isNaN(value))
|
|
1391
|
-
return "0";
|
|
1392
|
-
const absValue = Math.abs(value);
|
|
1393
|
-
if (logging) {
|
|
1394
|
-
console.log({
|
|
1395
|
-
value,
|
|
1396
|
-
minDisplay,
|
|
1397
|
-
maxDisplay,
|
|
1398
|
-
tokenPrice,
|
|
1399
|
-
ignoreMinDisplay,
|
|
1400
|
-
absValue
|
|
1401
|
-
});
|
|
1402
|
-
}
|
|
1403
|
-
if (!ignoreMinDisplay && absValue < minDisplay) {
|
|
1404
|
-
return `<${minDisplay}`;
|
|
1405
|
-
}
|
|
1406
|
-
if (absValue > maxDisplay) {
|
|
1407
|
-
return (0, numeral_1.default)(value).format(forceDecimals ? "0,0.00a" : "0,0.[00]a");
|
|
1408
|
-
}
|
|
1409
|
-
if (!ignoreMinDisplay && Math.abs(value) >= 0.01) {
|
|
1410
|
-
return (0, numeral_1.default)(value).format(forceDecimals && Math.abs(value) > 0.99 ? "0,0.00a" : "0,0.[0000]a");
|
|
1411
|
-
}
|
|
1412
|
-
if (ignoreMinDisplay) {
|
|
1413
|
-
const decimalPart = absValue - Math.floor(absValue);
|
|
1414
|
-
const decimalPlaces = decimalPart > 0 ? 3 : 0;
|
|
1415
|
-
if (absValue >= 1) {
|
|
1416
|
-
return value.toFixed(decimalPlaces).replace(/\.?0+$/, "");
|
|
1417
|
-
} else {
|
|
1418
|
-
const exponent = Math.floor(Math.log10(absValue));
|
|
1419
|
-
const significantDecimals = Math.max(3, 2 - exponent);
|
|
1420
|
-
return value.toFixed(significantDecimals).replace(/\.?0+$/, "");
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
if (Math.abs(value) >= minDisplay) {
|
|
1424
|
-
const decimalPlaces = Math.max(0, Math.ceil(-Math.log10(minDisplay)));
|
|
1425
|
-
return (0, numeral_1.default)(value).format(`0,0.[${"0".repeat(decimalPlaces)}]`);
|
|
1426
|
-
}
|
|
1427
|
-
if (tokenPrice) {
|
|
1428
|
-
const smallestUnit = minDisplay / tokenPrice;
|
|
1429
|
-
const significantDecimals = Math.max(3, Math.ceil(-Math.log10(smallestUnit)));
|
|
1430
|
-
return value.toFixed(significantDecimals).replace(/\.?0+$/, "");
|
|
1431
|
-
}
|
|
1432
|
-
return "0";
|
|
1433
|
-
};
|
|
1434
|
-
exports$1.dynamicNumeralFormatter = dynamicNumeralFormatter;
|
|
1435
|
-
var groupedNumberFormatterDyn = new Intl.NumberFormat("en-US", {
|
|
1436
|
-
useGrouping: true,
|
|
1437
|
-
minimumFractionDigits: 0,
|
|
1438
|
-
maximumFractionDigits: 2
|
|
1439
|
-
});
|
|
1440
|
-
exports$1.groupedNumberFormatterDyn = groupedNumberFormatterDyn;
|
|
1441
|
-
var usdFormatter = new Intl.NumberFormat("en-US", {
|
|
1442
|
-
style: "currency",
|
|
1443
|
-
currency: "USD",
|
|
1444
|
-
minimumFractionDigits: 2,
|
|
1445
|
-
maximumFractionDigits: 2,
|
|
1446
|
-
signDisplay: "auto"
|
|
1447
|
-
});
|
|
1448
|
-
exports$1.usdFormatter = usdFormatter;
|
|
1449
|
-
var usdFormatterDyn = new Intl.NumberFormat("en-US", {
|
|
1450
|
-
style: "currency",
|
|
1451
|
-
currency: "USD",
|
|
1452
|
-
minimumFractionDigits: 0,
|
|
1453
|
-
maximumFractionDigits: 2,
|
|
1454
|
-
signDisplay: "auto"
|
|
1455
|
-
});
|
|
1456
|
-
exports$1.usdFormatterDyn = usdFormatterDyn;
|
|
1457
|
-
var percentFormatter = new Intl.NumberFormat("en-US", {
|
|
1458
|
-
style: "percent",
|
|
1459
|
-
minimumFractionDigits: 2,
|
|
1460
|
-
maximumFractionDigits: 2
|
|
1461
|
-
});
|
|
1462
|
-
exports$1.percentFormatter = percentFormatter;
|
|
1463
|
-
var percentFormatterDyn = new Intl.NumberFormat("en-US", {
|
|
1464
|
-
style: "percent",
|
|
1465
|
-
minimumFractionDigits: 0,
|
|
1466
|
-
maximumFractionDigits: 2
|
|
1467
|
-
});
|
|
1468
|
-
exports$1.percentFormatterDyn = percentFormatterDyn;
|
|
1469
|
-
var percentFormatterMod = (value, opts = { minFractionDigits: 2, maxFractionDigits: 2 }) => {
|
|
1470
|
-
const percentFormatter2 = new Intl.NumberFormat("en-US", {
|
|
1471
|
-
style: "percent",
|
|
1472
|
-
minimumFractionDigits: opts.minFractionDigits,
|
|
1473
|
-
maximumFractionDigits: opts.maxFractionDigits
|
|
1474
|
-
});
|
|
1475
|
-
if (value === 0) {
|
|
1476
|
-
return "0%";
|
|
1477
|
-
} else {
|
|
1478
|
-
return percentFormatter2.format(value);
|
|
1479
|
-
}
|
|
1480
|
-
};
|
|
1481
|
-
exports$1.percentFormatterMod = percentFormatterMod;
|
|
1482
|
-
var clampedNumeralFormatter = (value) => {
|
|
1483
|
-
if (value === 0) {
|
|
1484
|
-
return "0";
|
|
1485
|
-
} else if (value < 0.01) {
|
|
1486
|
-
return "< 0.01";
|
|
1487
|
-
} else {
|
|
1488
|
-
return (0, numeral_1.default)(value).format("0.00a");
|
|
1489
|
-
}
|
|
1490
|
-
};
|
|
1491
|
-
exports$1.clampedNumeralFormatter = clampedNumeralFormatter;
|
|
1492
|
-
var tokenPriceFormatter = (price, style = "currency") => {
|
|
1493
|
-
if (price === 0) {
|
|
1494
|
-
return 0;
|
|
1495
|
-
}
|
|
1496
|
-
const reformatNum = Number(price.toFixed(20));
|
|
1497
|
-
if (price === 0) {
|
|
1498
|
-
return 0;
|
|
1499
|
-
}
|
|
1500
|
-
if (reformatNum < 1e-8) {
|
|
1501
|
-
return price.toExponential(2);
|
|
1502
|
-
}
|
|
1503
|
-
const { minFractionDigits, maxFractionDigits } = reformatNum > 1 ? { minFractionDigits: 2, maxFractionDigits: 2 } : reformatNum > 1e-6 ? { minFractionDigits: 2, maxFractionDigits: 7 } : { minFractionDigits: 7, maxFractionDigits: 10 };
|
|
1504
|
-
const formatter = new Intl.NumberFormat("en-US", {
|
|
1505
|
-
style,
|
|
1506
|
-
currency: "USD",
|
|
1507
|
-
minimumFractionDigits: minFractionDigits,
|
|
1508
|
-
maximumFractionDigits: maxFractionDigits,
|
|
1509
|
-
signDisplay: "auto"
|
|
1510
|
-
});
|
|
1511
|
-
return formatter.format(price);
|
|
1512
|
-
};
|
|
1513
|
-
exports$1.tokenPriceFormatter = tokenPriceFormatter;
|
|
1514
|
-
}
|
|
1515
|
-
});
|
|
1516
|
-
|
|
1517
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/index.js
|
|
1518
|
-
var require_utils = __commonJS({
|
|
1519
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/utils/index.js"(exports$1) {
|
|
1520
|
-
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
1521
|
-
if (k2 === void 0) k2 = k;
|
|
1522
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
1523
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
1524
|
-
desc = { enumerable: true, get: function() {
|
|
1525
|
-
return m[k];
|
|
1526
|
-
} };
|
|
1527
|
-
}
|
|
1528
|
-
Object.defineProperty(o, k2, desc);
|
|
1529
|
-
}) : (function(o, m, k, k2) {
|
|
1530
|
-
if (k2 === void 0) k2 = k;
|
|
1531
|
-
o[k2] = m[k];
|
|
1532
|
-
}));
|
|
1533
|
-
var __exportStar = exports$1 && exports$1.__exportStar || function(m, exports2) {
|
|
1534
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
|
|
1535
|
-
};
|
|
1536
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
1537
|
-
__exportStar(require_accounting_utils(), exports$1);
|
|
1538
|
-
__exportStar(require_conversion_utils(), exports$1);
|
|
1539
|
-
__exportStar(require_formatters_utils(), exports$1);
|
|
1540
|
-
}
|
|
1541
|
-
});
|
|
1542
|
-
|
|
1543
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/transactions/transaction.utils.js
|
|
1544
|
-
var require_transaction_utils = __commonJS({
|
|
1545
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/transactions/transaction.utils.js"(exports$1) {
|
|
1546
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
1547
|
-
exports$1.microLamportsToUi = exports$1.uiToMicroLamports = void 0;
|
|
1548
|
-
exports$1.isV0Tx = isV0Tx;
|
|
1549
|
-
exports$1.getTxSize = getTxSize;
|
|
1550
|
-
exports$1.getAccountKeys = getAccountKeys;
|
|
1551
|
-
exports$1.decodeInstruction = decodeInstruction;
|
|
1552
|
-
exports$1.decompileV0Transaction = decompileV0Transaction;
|
|
1553
|
-
exports$1.legacyTxToV0Tx = legacyTxToV0Tx;
|
|
1554
|
-
exports$1.updateV0Tx = updateV0Tx;
|
|
1555
|
-
exports$1.compareInstructions = compareInstructions;
|
|
1556
|
-
exports$1.replaceV0TxInstructions = replaceV0TxInstructions;
|
|
1557
|
-
exports$1.replaceV0TxBlockhash = replaceV0TxBlockhash;
|
|
1558
|
-
exports$1.addTransactionMetadata = addTransactionMetadata;
|
|
1559
|
-
exports$1.decodeComputeBudgetInstruction = decodeComputeBudgetInstruction;
|
|
1560
|
-
exports$1.getComputeBudgetUnits = getComputeBudgetUnits;
|
|
1561
|
-
exports$1.splitInstructionsToFitTransactions = splitInstructionsToFitTransactions;
|
|
1562
|
-
var anchor_1 = __require("@coral-xyz/anchor");
|
|
1563
|
-
var web3_js_1 = __require("@solana/web3.js");
|
|
1564
|
-
var constants_1 = require_constants();
|
|
1565
|
-
function isV0Tx(tx) {
|
|
1566
|
-
return "message" in tx;
|
|
1567
|
-
}
|
|
1568
|
-
function getTxSize(tx) {
|
|
1569
|
-
const isVersioned = isV0Tx(tx);
|
|
1570
|
-
const numSigners = tx.signatures.length;
|
|
1571
|
-
const numRequiredSignatures = isVersioned ? tx.message.header.numRequiredSignatures : 0;
|
|
1572
|
-
const feePayerSize = isVersioned || tx.feePayer ? 0 : 32;
|
|
1573
|
-
const signaturesSize = (numRequiredSignatures - numSigners) * 64 + 1;
|
|
1574
|
-
try {
|
|
1575
|
-
const baseTxSize = isVersioned ? tx.serialize().length : tx.serialize({ requireAllSignatures: false, verifySignatures: false }).length;
|
|
1576
|
-
return baseTxSize + feePayerSize + signaturesSize;
|
|
1577
|
-
} catch (error) {
|
|
1578
|
-
return 9999;
|
|
1579
|
-
}
|
|
1580
|
-
}
|
|
1581
|
-
function getAccountKeys(tx, lookupTableAccounts) {
|
|
1582
|
-
const isVersioned = isV0Tx(tx);
|
|
1583
|
-
try {
|
|
1584
|
-
if (isVersioned) {
|
|
1585
|
-
const message = web3_js_1.TransactionMessage.decompile(tx.message, { addressLookupTableAccounts: lookupTableAccounts });
|
|
1586
|
-
return message.compileToLegacyMessage().getAccountKeys().length;
|
|
1587
|
-
} else {
|
|
1588
|
-
return tx.compileMessage().getAccountKeys().length;
|
|
1589
|
-
}
|
|
1590
|
-
} catch (error) {
|
|
1591
|
-
return 9999;
|
|
1592
|
-
}
|
|
1593
|
-
}
|
|
1594
|
-
function decodeInstruction(idl, encoded) {
|
|
1595
|
-
const coder = new anchor_1.BorshInstructionCoder(idl);
|
|
1596
|
-
return coder.decode(encoded, "base58");
|
|
1597
|
-
}
|
|
1598
|
-
function decompileV0Transaction(tx, lookupTableAccounts) {
|
|
1599
|
-
return web3_js_1.TransactionMessage.decompile(tx.message, { addressLookupTableAccounts: lookupTableAccounts });
|
|
1600
|
-
}
|
|
1601
|
-
function legacyTxToV0Tx(transaction, opts) {
|
|
1602
|
-
const feePayer = opts?.feePayer ?? transaction.feePayer;
|
|
1603
|
-
const blockhash = opts?.blockhash ?? transaction.recentBlockhash;
|
|
1604
|
-
const additionalIxs = opts?.additionalIxs ?? [];
|
|
1605
|
-
const addressLookupTables = opts?.addressLookupTables ?? [];
|
|
1606
|
-
if (!feePayer || !blockhash) {
|
|
1607
|
-
throw new Error("Fee payer and blockhash are required");
|
|
1608
|
-
}
|
|
1609
|
-
const ixs = transaction.instructions;
|
|
1610
|
-
const versionedMessage = new web3_js_1.TransactionMessage({
|
|
1611
|
-
instructions: [...additionalIxs, ...ixs],
|
|
1612
|
-
payerKey: feePayer,
|
|
1613
|
-
recentBlockhash: blockhash
|
|
1614
|
-
});
|
|
1615
|
-
return new web3_js_1.VersionedTransaction(versionedMessage.compileToV0Message(addressLookupTables));
|
|
1616
|
-
}
|
|
1617
|
-
function updateV0Tx(transaction, opts) {
|
|
1618
|
-
const additionalIxs = opts?.additionalIxs ?? [];
|
|
1619
|
-
const addressLookupTables = opts?.addressLookupTables ?? [];
|
|
1620
|
-
let instructions = [];
|
|
1621
|
-
const message = decompileV0Transaction(transaction, addressLookupTables);
|
|
1622
|
-
const feePayer = opts?.feePayer ?? message.payerKey;
|
|
1623
|
-
const blockhash = opts?.blockhash ?? message.recentBlockhash;
|
|
1624
|
-
if (additionalIxs.length > 0) {
|
|
1625
|
-
instructions = replaceV0TxInstructions(additionalIxs, message.instructions, opts?.replaceOnly, opts?.indexOffset);
|
|
1626
|
-
} else {
|
|
1627
|
-
instructions = message.instructions;
|
|
1628
|
-
}
|
|
1629
|
-
const versionedMessage = new web3_js_1.TransactionMessage({
|
|
1630
|
-
instructions,
|
|
1631
|
-
payerKey: feePayer,
|
|
1632
|
-
recentBlockhash: blockhash
|
|
1633
|
-
});
|
|
1634
|
-
return new web3_js_1.VersionedTransaction(versionedMessage.compileToV0Message(addressLookupTables));
|
|
1635
|
-
}
|
|
1636
|
-
function compareInstructions(ix1, ix2) {
|
|
1637
|
-
const dataCompare = ix1.data.equals(ix2.data);
|
|
1638
|
-
const programIdCompare = ix1.programId.equals(ix2.programId);
|
|
1639
|
-
const keysCompare = ix1.keys.length === ix2.keys.length && ix1.keys.every((key, index) => {
|
|
1640
|
-
const key2 = ix2.keys[index];
|
|
1641
|
-
return key.pubkey.equals(key2.pubkey) && key.isSigner === key2.isSigner && key.isWritable === key2.isWritable;
|
|
1642
|
-
});
|
|
1643
|
-
return dataCompare && programIdCompare && keysCompare;
|
|
1644
|
-
}
|
|
1645
|
-
function replaceV0TxInstructions(additionalInstructions, instructions, replaceOnly, indexOffset) {
|
|
1646
|
-
let updatedAdditionalIxs = additionalInstructions;
|
|
1647
|
-
const updatedInstructions = instructions.map((ix) => {
|
|
1648
|
-
const programId = ix.programId;
|
|
1649
|
-
const additionalIxs = additionalInstructions.filter((a) => a.programId.equals(programId));
|
|
1650
|
-
if (additionalIxs.length > 0) {
|
|
1651
|
-
if (ix.programId.equals(web3_js_1.ComputeBudgetProgram.programId)) {
|
|
1652
|
-
const decoded = decodeComputeBudgetInstruction(ix);
|
|
1653
|
-
const updatedCuPriceIx = additionalIxs.find((a) => decodeComputeBudgetInstruction(a).instructionType === "SetComputeUnitPrice");
|
|
1654
|
-
const updatedCuLimitIx = additionalIxs.find((a) => decodeComputeBudgetInstruction(a).instructionType === "SetComputeUnitLimit");
|
|
1655
|
-
if (decoded.instructionType === "SetComputeUnitPrice" && updatedCuPriceIx) {
|
|
1656
|
-
updatedAdditionalIxs = updatedAdditionalIxs.filter((a) => !compareInstructions(a, updatedCuPriceIx));
|
|
1657
|
-
return updatedCuPriceIx;
|
|
1658
|
-
}
|
|
1659
|
-
if (decoded.instructionType === "SetComputeUnitLimit" && updatedCuLimitIx) {
|
|
1660
|
-
updatedAdditionalIxs = updatedAdditionalIxs.filter((a) => !compareInstructions(a, updatedCuLimitIx));
|
|
1661
|
-
return updatedCuLimitIx;
|
|
1662
|
-
}
|
|
1663
|
-
}
|
|
1664
|
-
}
|
|
1665
|
-
return ix;
|
|
1666
|
-
});
|
|
1667
|
-
if (replaceOnly) {
|
|
1668
|
-
return updatedInstructions;
|
|
1669
|
-
}
|
|
1670
|
-
if (indexOffset === void 0) {
|
|
1671
|
-
return [...updatedAdditionalIxs, ...updatedInstructions];
|
|
1672
|
-
}
|
|
1673
|
-
const result = [...updatedInstructions];
|
|
1674
|
-
result.splice(indexOffset, 0, ...updatedAdditionalIxs);
|
|
1675
|
-
return result;
|
|
1676
|
-
}
|
|
1677
|
-
function replaceV0TxBlockhash(transaction, blockhash) {
|
|
1678
|
-
let message = transaction.message;
|
|
1679
|
-
message.recentBlockhash = blockhash;
|
|
1680
|
-
return new web3_js_1.VersionedTransaction(message);
|
|
1681
|
-
}
|
|
1682
|
-
function addTransactionMetadata(transaction, options) {
|
|
1683
|
-
return Object.assign(transaction, options);
|
|
1684
|
-
}
|
|
1685
|
-
function identifyComputeBudgetInstruction(data) {
|
|
1686
|
-
const discriminator = data.readUInt8(0);
|
|
1687
|
-
switch (discriminator) {
|
|
1688
|
-
case 0:
|
|
1689
|
-
return "RequestUnits";
|
|
1690
|
-
case 1:
|
|
1691
|
-
return "RequestHeapFrame";
|
|
1692
|
-
case 2:
|
|
1693
|
-
return "SetComputeUnitLimit";
|
|
1694
|
-
case 3:
|
|
1695
|
-
return "SetComputeUnitPrice";
|
|
1696
|
-
case 4:
|
|
1697
|
-
return "SetLoadedAccountsDataSizeLimit";
|
|
1698
|
-
default:
|
|
1699
|
-
throw new Error("Unknown ComputeBudget instruction discriminator.");
|
|
1700
|
-
}
|
|
1701
|
-
}
|
|
1702
|
-
function decodeComputeBudgetInstruction(instruction) {
|
|
1703
|
-
const data = Buffer.from(instruction.data || instruction);
|
|
1704
|
-
const instructionType = identifyComputeBudgetInstruction(data);
|
|
1705
|
-
switch (instructionType) {
|
|
1706
|
-
case "RequestUnits": {
|
|
1707
|
-
if (data.length !== 9) {
|
|
1708
|
-
throw new Error("Invalid data length for RequestUnits");
|
|
1709
|
-
}
|
|
1710
|
-
const units = data.readUInt32LE(1);
|
|
1711
|
-
const additionalFee = data.readUInt32LE(5);
|
|
1712
|
-
return { instructionType, units, additionalFee };
|
|
1713
|
-
}
|
|
1714
|
-
case "RequestHeapFrame": {
|
|
1715
|
-
if (data.length !== 5) {
|
|
1716
|
-
throw new Error("Invalid data length for RequestHeapFrame");
|
|
1717
|
-
}
|
|
1718
|
-
const bytes = data.readUInt32LE(1);
|
|
1719
|
-
return { instructionType, bytes };
|
|
1720
|
-
}
|
|
1721
|
-
case "SetComputeUnitLimit": {
|
|
1722
|
-
if (data.length !== 5) {
|
|
1723
|
-
throw new Error("Invalid data length for SetComputeUnitLimit");
|
|
1724
|
-
}
|
|
1725
|
-
const units = data.readUInt32LE(1);
|
|
1726
|
-
return { instructionType, units };
|
|
1727
|
-
}
|
|
1728
|
-
case "SetComputeUnitPrice": {
|
|
1729
|
-
if (data.length !== 9) {
|
|
1730
|
-
throw new Error("Invalid data length for SetComputeUnitPrice");
|
|
1731
|
-
}
|
|
1732
|
-
const microLamports = data.readBigUInt64LE(1);
|
|
1733
|
-
return { instructionType, microLamports: microLamports.toString() };
|
|
1734
|
-
}
|
|
1735
|
-
case "SetLoadedAccountsDataSizeLimit": {
|
|
1736
|
-
if (data.length !== 5) {
|
|
1737
|
-
throw new Error("Invalid data length for SetLoadedAccountsDataSizeLimit");
|
|
1738
|
-
}
|
|
1739
|
-
const accountDataSizeLimit = data.readUInt32LE(1);
|
|
1740
|
-
return { instructionType, accountDataSizeLimit };
|
|
1741
|
-
}
|
|
1742
|
-
default:
|
|
1743
|
-
throw new Error("Unknown ComputeBudget instruction type.");
|
|
1744
|
-
}
|
|
1745
|
-
}
|
|
1746
|
-
var DEFAULT_COMPUTE_BUDGET_IX = 2e5;
|
|
1747
|
-
function getComputeBudgetUnits(tx) {
|
|
1748
|
-
let instructions = [];
|
|
1749
|
-
if (isV0Tx(tx)) {
|
|
1750
|
-
const addressLookupTableAccounts = tx.addressLookupTables ?? [];
|
|
1751
|
-
const message = decompileV0Transaction(tx, addressLookupTableAccounts);
|
|
1752
|
-
instructions = message.instructions;
|
|
1753
|
-
} else {
|
|
1754
|
-
instructions = tx.instructions;
|
|
1755
|
-
}
|
|
1756
|
-
const computeBudgetIxs = instructions.filter((ix) => ix.programId.equals(web3_js_1.ComputeBudgetProgram.programId));
|
|
1757
|
-
if (computeBudgetIxs.length === 0) {
|
|
1758
|
-
return Math.min(instructions.length * DEFAULT_COMPUTE_BUDGET_IX, 14e5);
|
|
1759
|
-
}
|
|
1760
|
-
const decoded = computeBudgetIxs.map((ix) => decodeComputeBudgetInstruction(ix));
|
|
1761
|
-
const limit = decoded.find((ix) => ix.instructionType === "SetComputeUnitLimit");
|
|
1762
|
-
return limit?.units ?? instructions.length * DEFAULT_COMPUTE_BUDGET_IX;
|
|
1763
|
-
}
|
|
1764
|
-
var uiToMicroLamports = (ui, limitCU = 14e5) => {
|
|
1765
|
-
const priorityFeeMicroLamports = ui * web3_js_1.LAMPORTS_PER_SOL * 1e6;
|
|
1766
|
-
return priorityFeeMicroLamports / limitCU;
|
|
1767
|
-
};
|
|
1768
|
-
exports$1.uiToMicroLamports = uiToMicroLamports;
|
|
1769
|
-
var microLamportsToUi = (microLamports, limitCU = 14e5) => {
|
|
1770
|
-
const priorityFeeMicroLamports = microLamports * limitCU;
|
|
1771
|
-
const priorityFeeUi = priorityFeeMicroLamports / (web3_js_1.LAMPORTS_PER_SOL * 1e6);
|
|
1772
|
-
return Math.trunc(priorityFeeUi * web3_js_1.LAMPORTS_PER_SOL) / web3_js_1.LAMPORTS_PER_SOL;
|
|
1773
|
-
};
|
|
1774
|
-
exports$1.microLamportsToUi = microLamportsToUi;
|
|
1775
|
-
function splitInstructionsToFitTransactions(mandatoryIxs, ixs, opts) {
|
|
1776
|
-
const result = [];
|
|
1777
|
-
let buffer = [];
|
|
1778
|
-
function buildTx(mandatoryIxs2, extraIxs, opts2) {
|
|
1779
|
-
const messageV0 = new web3_js_1.TransactionMessage({
|
|
1780
|
-
payerKey: opts2.payerKey,
|
|
1781
|
-
recentBlockhash: opts2.blockhash,
|
|
1782
|
-
instructions: [...mandatoryIxs2, ...extraIxs]
|
|
1783
|
-
}).compileToV0Message(opts2.luts);
|
|
1784
|
-
return new web3_js_1.VersionedTransaction(messageV0);
|
|
1785
|
-
}
|
|
1786
|
-
for (const ix of ixs) {
|
|
1787
|
-
const trial = buildTx(mandatoryIxs, [...buffer, ix], opts);
|
|
1788
|
-
if (getTxSize(trial) <= constants_1.MAX_TX_SIZE) {
|
|
1789
|
-
buffer.push(ix);
|
|
1790
|
-
} else {
|
|
1791
|
-
if (buffer.length === 0) {
|
|
1792
|
-
throw new Error("Single instruction too large to fit in a transaction");
|
|
1793
|
-
}
|
|
1794
|
-
const tx = buildTx(mandatoryIxs, buffer, opts);
|
|
1795
|
-
result.push(tx);
|
|
1796
|
-
buffer = [ix];
|
|
1797
|
-
const solo = buildTx(mandatoryIxs, buffer, opts);
|
|
1798
|
-
if (getTxSize(solo) > constants_1.MAX_TX_SIZE) {
|
|
1799
|
-
throw new Error("Single instruction too large to fit in a transaction");
|
|
1800
|
-
}
|
|
1801
|
-
}
|
|
1802
|
-
}
|
|
1803
|
-
if (buffer.length > 0) {
|
|
1804
|
-
const tx = buildTx(mandatoryIxs, buffer, opts);
|
|
1805
|
-
result.push(tx);
|
|
1806
|
-
}
|
|
1807
|
-
return result;
|
|
1808
|
-
}
|
|
1809
|
-
}
|
|
1810
|
-
});
|
|
1811
|
-
|
|
1812
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/transactions/transaction.types.js
|
|
1813
|
-
var require_transaction_types = __commonJS({
|
|
1814
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/transactions/transaction.types.js"(exports$1) {
|
|
1815
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
1816
|
-
exports$1.TransactionArenaKeyMap = exports$1.TransactionConfigMap = exports$1.TransactionType = void 0;
|
|
1817
|
-
var web3_js_1 = __require("@solana/web3.js");
|
|
1818
|
-
var TransactionType;
|
|
1819
|
-
(function(TransactionType2) {
|
|
1820
|
-
TransactionType2["DEPOSIT"] = "DEPOSIT";
|
|
1821
|
-
TransactionType2["WITHDRAW"] = "WITHDRAW";
|
|
1822
|
-
TransactionType2["REPAY"] = "REPAY";
|
|
1823
|
-
TransactionType2["BORROW"] = "BORROW";
|
|
1824
|
-
TransactionType2["FLASHLOAN"] = "FLASHLOAN";
|
|
1825
|
-
TransactionType2["LOOP"] = "LOOP";
|
|
1826
|
-
TransactionType2["REPAY_COLLAT"] = "REPAY_COLLAT";
|
|
1827
|
-
TransactionType2["LONG"] = "LONG";
|
|
1828
|
-
TransactionType2["SHORT"] = "SHORT";
|
|
1829
|
-
TransactionType2["CREATE_ACCOUNT"] = "CREATE_ACCOUNT";
|
|
1830
|
-
TransactionType2["CREATE_ATA"] = "CREATE_ATA";
|
|
1831
|
-
TransactionType2["CLOSE_ACCOUNT"] = "CLOSE_ACCOUNT";
|
|
1832
|
-
TransactionType2["CLOSE_POSITION"] = "CLOSE_POSITION";
|
|
1833
|
-
TransactionType2["MOVE_POSITION_WITHDRAW"] = "MOVE_POSITION_WITHDRAW";
|
|
1834
|
-
TransactionType2["MOVE_POSITION_DEPOSIT"] = "MOVE_POSITION_DEPOSIT";
|
|
1835
|
-
TransactionType2["WITHDRAW_ALL"] = "WITHDRAW_ALL";
|
|
1836
|
-
TransactionType2["TRANSFER_AUTH"] = "TRANSFER_AUTH";
|
|
1837
|
-
TransactionType2["CRANK"] = "CRANK";
|
|
1838
|
-
TransactionType2["DEPOSIT_STAKE"] = "DEPOSIT_STAKE";
|
|
1839
|
-
TransactionType2["WITHDRAW_STAKE"] = "WITHDRAW_STAKE";
|
|
1840
|
-
TransactionType2["INITIALIZE_STAKED_POOL"] = "INITIALIZE_STAKED_POOL";
|
|
1841
|
-
TransactionType2["ADD_STAKED_BANK"] = "ADD_STAKED_BANK";
|
|
1842
|
-
TransactionType2["MERGE_STAKE_ACCOUNTS"] = "MERGE_STAKE_ACCOUNTS";
|
|
1843
|
-
TransactionType2["STAKE_TO_STAKE"] = "STAKE_TO_STAKE";
|
|
1844
|
-
TransactionType2["MINT_LST_NATIVE"] = "MINT_LST_NATIVE";
|
|
1845
|
-
TransactionType2["SWAP_TO_SOL"] = "SWAP_TO_SOL";
|
|
1846
|
-
TransactionType2["SOL_TO_LST"] = "SOL_TO_LST";
|
|
1847
|
-
TransactionType2["UNSTAKE_LST"] = "UNSTAKE_LST";
|
|
1848
|
-
TransactionType2["WITHDRAW_EMISSIONS"] = "WITHDRAW_EMISSIONS";
|
|
1849
|
-
TransactionType2["LIQUIDATE_ACCOUNT"] = "LIQUIDATE_ACCOUNT";
|
|
1850
|
-
TransactionType2["CREATE_PERM_BANK"] = "CREATE_PERM_BANK";
|
|
1851
|
-
TransactionType2["CREATE_GROUP"] = "CREATE_GROUP";
|
|
1852
|
-
TransactionType2["JUPITER_SWAP"] = "JUPITER_SWAP";
|
|
1853
|
-
})(TransactionType || (exports$1.TransactionType = TransactionType = {}));
|
|
1854
|
-
exports$1.TransactionConfigMap = {
|
|
1855
|
-
// BASE LENDING ACTIONS
|
|
1856
|
-
[TransactionType.DEPOSIT]: {
|
|
1857
|
-
label: ({ amount, token } = {}) => amount && token ? `Deposit ${amount} ${token}` : "Deposit"
|
|
1858
|
-
},
|
|
1859
|
-
[TransactionType.WITHDRAW]: {
|
|
1860
|
-
label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw"
|
|
1861
|
-
},
|
|
1862
|
-
[TransactionType.REPAY]: {
|
|
1863
|
-
label: ({ amount, token } = {}) => amount && token ? `Repay ${amount} ${token}` : "Repay"
|
|
1864
|
-
},
|
|
1865
|
-
[TransactionType.BORROW]: {
|
|
1866
|
-
label: ({ amount, token } = {}) => amount && token ? `Borrow ${amount} ${token}` : "Borrow"
|
|
1867
|
-
},
|
|
1868
|
-
// FLASHLOANS
|
|
1869
|
-
[TransactionType.FLASHLOAN]: { label: () => "Executing Flashloan" },
|
|
1870
|
-
[TransactionType.LOOP]: {
|
|
1871
|
-
label: ({ depositAmount, depositToken, borrowAmount, borrowToken } = {}) => depositAmount && depositToken && borrowAmount && borrowToken ? `Loop ${depositAmount} ${depositToken} with ${borrowAmount} ${borrowToken}` : "Loop"
|
|
1872
|
-
},
|
|
1873
|
-
[TransactionType.REPAY_COLLAT]: {
|
|
1874
|
-
label: ({ repayAmount, repayToken, amount, token } = {}) => repayAmount && repayToken && amount && token ? `Repay ${repayAmount} ${token} with ${amount} ${repayToken}` : "Repay with collateral"
|
|
1875
|
-
},
|
|
1876
|
-
[TransactionType.LONG]: {
|
|
1877
|
-
label: ({ depositToken, depositAmount, borrowToken } = {}) => depositToken && depositAmount && borrowToken ? `Long ${depositToken} with ${depositAmount} ${borrowToken}` : "Open long position"
|
|
1878
|
-
},
|
|
1879
|
-
[TransactionType.SHORT]: {
|
|
1880
|
-
label: ({ borrowToken, depositAmount, depositToken } = {}) => borrowToken && depositAmount && depositToken ? `Short ${borrowToken} with ${depositAmount} ${depositToken}` : "Open short position"
|
|
1881
|
-
},
|
|
1882
|
-
// SWB
|
|
1883
|
-
[TransactionType.CRANK]: { label: () => "Updating latest prices" },
|
|
1884
|
-
[TransactionType.JUPITER_SWAP]: {
|
|
1885
|
-
label: ({ originAmount, originToken, destinationAmount, destinationToken } = {}) => originAmount && originToken && destinationAmount && destinationToken ? `Swap ${originAmount} ${originToken} for ${destinationAmount} ${destinationToken}` : "Swap tokens"
|
|
1886
|
-
},
|
|
1887
|
-
// SETUP
|
|
1888
|
-
[TransactionType.CREATE_ACCOUNT]: { label: () => "Create marginfi account" },
|
|
1889
|
-
[TransactionType.CREATE_ATA]: { label: () => "Configure token account" },
|
|
1890
|
-
// ACCOUNT MANAGEMENT
|
|
1891
|
-
[TransactionType.CLOSE_ACCOUNT]: { label: () => "Close marginfi account" },
|
|
1892
|
-
[TransactionType.CLOSE_POSITION]: { label: () => "Close position" },
|
|
1893
|
-
[TransactionType.MOVE_POSITION_WITHDRAW]: {
|
|
1894
|
-
label: ({ originAccountAddress } = {}) => `Move position from ${originAccountAddress}`
|
|
1895
|
-
},
|
|
1896
|
-
[TransactionType.MOVE_POSITION_DEPOSIT]: {
|
|
1897
|
-
label: ({ destinationAccountAddress } = {}) => `Move position to ${destinationAccountAddress}`
|
|
1898
|
-
},
|
|
1899
|
-
[TransactionType.TRANSFER_AUTH]: { label: () => "Authorize account transfer" },
|
|
1900
|
-
// NATIVE STAKE ACTIONS
|
|
1901
|
-
[TransactionType.DEPOSIT_STAKE]: {
|
|
1902
|
-
label: ({ amount, token } = {}) => amount && token ? `Authorize stake account and deposit ${amount} ${token}` : "Authorize stake and deposit"
|
|
1903
|
-
},
|
|
1904
|
-
[TransactionType.WITHDRAW_STAKE]: {
|
|
1905
|
-
label: ({ amount, token } = {}) => "Authorize stake account"
|
|
1906
|
-
},
|
|
1907
|
-
[TransactionType.INITIALIZE_STAKED_POOL]: { label: () => "Initialize stake pool" },
|
|
1908
|
-
[TransactionType.ADD_STAKED_BANK]: { label: () => "Create staked asset bank" },
|
|
1909
|
-
[TransactionType.MERGE_STAKE_ACCOUNTS]: { label: () => "Merge stake accounts" },
|
|
1910
|
-
// LST (Liquid Staking Tokens)
|
|
1911
|
-
[TransactionType.STAKE_TO_STAKE]: { label: () => "Convert stake" },
|
|
1912
|
-
[TransactionType.MINT_LST_NATIVE]: { label: () => "Mint LST" },
|
|
1913
|
-
[TransactionType.SWAP_TO_SOL]: {
|
|
1914
|
-
label: ({ swapAmount, token } = {}) => swapAmount && token ? `Swap ${swapAmount} ${token} to SOL` : "Swap to SOL"
|
|
1915
|
-
},
|
|
1916
|
-
[TransactionType.SOL_TO_LST]: {
|
|
1917
|
-
label: ({ amount } = {}) => amount ? `Mint LST with ${amount} SOL` : "Mint LST with SOL"
|
|
1918
|
-
},
|
|
1919
|
-
[TransactionType.UNSTAKE_LST]: { label: ({ amount } = {}) => amount ? `Unstake ${amount} LST` : "Unstake LST" },
|
|
1920
|
-
// EMISSIONS
|
|
1921
|
-
[TransactionType.WITHDRAW_EMISSIONS]: { label: () => "Withdraw emissions" },
|
|
1922
|
-
// LIQUIDATE
|
|
1923
|
-
[TransactionType.LIQUIDATE_ACCOUNT]: { label: () => "Liquidate account" },
|
|
1924
|
-
// BANK and GROUPS
|
|
1925
|
-
[TransactionType.CREATE_PERM_BANK]: { label: () => "Create permissionless bank" },
|
|
1926
|
-
[TransactionType.CREATE_GROUP]: { label: () => "Create marginfi group" },
|
|
1927
|
-
[TransactionType.WITHDRAW_ALL]: {
|
|
1928
|
-
label: ({ amount, token } = {}) => amount && token ? `Withdraw ${amount} ${token}` : "Withdraw all"
|
|
1929
|
-
}
|
|
1930
|
-
};
|
|
1931
|
-
exports$1.TransactionArenaKeyMap = {
|
|
1932
|
-
[TransactionType.DEPOSIT]: new web3_js_1.PublicKey("ArenaDeposit1111111111111111111111111111111"),
|
|
1933
|
-
[TransactionType.WITHDRAW]: new web3_js_1.PublicKey("ArenaWithdraw111111111111111111111111111111"),
|
|
1934
|
-
[TransactionType.BORROW]: new web3_js_1.PublicKey("ArenaBorrow11111111111111111111111111111111"),
|
|
1935
|
-
[TransactionType.REPAY]: new web3_js_1.PublicKey("ArenaRepay111111111111111111111111111111111"),
|
|
1936
|
-
[TransactionType.REPAY_COLLAT]: new web3_js_1.PublicKey("ArenaRepayCo11at111111111111111111111111111"),
|
|
1937
|
-
[TransactionType.LONG]: new web3_js_1.PublicKey("ArenaLong1111111111111111111111111111111111"),
|
|
1938
|
-
[TransactionType.SHORT]: new web3_js_1.PublicKey("ArenaShort111111111111111111111111111111111"),
|
|
1939
|
-
[TransactionType.CLOSE_POSITION]: new web3_js_1.PublicKey("ArenaC1ose111111111111111111111111111111111")
|
|
1940
|
-
// Add more mappings if needed
|
|
1941
|
-
};
|
|
1942
|
-
}
|
|
1943
|
-
});
|
|
1944
|
-
|
|
1945
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/transactions/index.js
|
|
1946
|
-
var require_transactions = __commonJS({
|
|
1947
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/transactions/index.js"(exports$1) {
|
|
1948
|
-
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
1949
|
-
if (k2 === void 0) k2 = k;
|
|
1950
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
1951
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
1952
|
-
desc = { enumerable: true, get: function() {
|
|
1953
|
-
return m[k];
|
|
1954
|
-
} };
|
|
1955
|
-
}
|
|
1956
|
-
Object.defineProperty(o, k2, desc);
|
|
1957
|
-
}) : (function(o, m, k, k2) {
|
|
1958
|
-
if (k2 === void 0) k2 = k;
|
|
1959
|
-
o[k2] = m[k];
|
|
1960
|
-
}));
|
|
1961
|
-
var __exportStar = exports$1 && exports$1.__exportStar || function(m, exports2) {
|
|
1962
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
|
|
1963
|
-
};
|
|
1964
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
1965
|
-
__exportStar(require_transaction_utils(), exports$1);
|
|
1966
|
-
__exportStar(require_transaction_types(), exports$1);
|
|
1967
|
-
}
|
|
1968
|
-
});
|
|
1969
|
-
|
|
1970
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/index.js
|
|
1971
|
-
var require_modules = __commonJS({
|
|
1972
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/modules/index.js"(exports$1) {
|
|
1973
|
-
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
1974
|
-
if (k2 === void 0) k2 = k;
|
|
1975
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
1976
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
1977
|
-
desc = { enumerable: true, get: function() {
|
|
1978
|
-
return m[k];
|
|
1979
|
-
} };
|
|
1980
|
-
}
|
|
1981
|
-
Object.defineProperty(o, k2, desc);
|
|
1982
|
-
}) : (function(o, m, k, k2) {
|
|
1983
|
-
if (k2 === void 0) k2 = k;
|
|
1984
|
-
o[k2] = m[k];
|
|
1985
|
-
}));
|
|
1986
|
-
var __exportStar = exports$1 && exports$1.__exportStar || function(m, exports2) {
|
|
1987
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
|
|
1988
|
-
};
|
|
1989
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
1990
|
-
__exportStar(require_transactions(), exports$1);
|
|
1991
|
-
}
|
|
1992
|
-
});
|
|
1993
|
-
|
|
1994
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/spl.js
|
|
1995
|
-
var require_spl = __commonJS({
|
|
1996
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/spl.js"(exports$1) {
|
|
1997
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
1998
|
-
exports$1.MEMO_PROGRAM_ID = exports$1.MINT_SIZE = exports$1.MintLayout = exports$1.initializeAccountInstructionData = exports$1.TokenInstruction = exports$1.transferCheckedInstructionData = exports$1.closeAccountInstructionData = exports$1.syncNativeInstructionData = exports$1.ASSOCIATED_TOKEN_PROGRAM_ID = exports$1.LENGTH_SIZE = exports$1.TYPE_SIZE = exports$1.ExtensionType = exports$1.TOKEN_2022_PROGRAM_ID = exports$1.TOKEN_PROGRAM_ID = exports$1.NATIVE_MINT = exports$1.ACCOUNT_SIZE = exports$1.AccountLayout = exports$1.AccountState = exports$1.TokenUnsupportedInstructionError = exports$1.TokenInvalidInstructionTypeError = exports$1.TokenInvalidInstructionDataError = exports$1.TokenInvalidInstructionKeysError = exports$1.TokenInvalidInstructionProgramError = exports$1.TokenOwnerOffCurveError = exports$1.TokenInvalidOwnerError = exports$1.TokenInvalidMintError = exports$1.TokenInvalidAccountSizeError = exports$1.TokenInvalidAccountOwnerError = exports$1.TokenInvalidAccountError = exports$1.TokenAccountNotFoundError = exports$1.TokenError = exports$1.ACCOUNT_TYPE_SIZE = exports$1.SplAccountType = exports$1.MULTISIG_SIZE = exports$1.MultisigLayout = void 0;
|
|
1999
|
-
exports$1.getAccount = getAccount2;
|
|
2000
|
-
exports$1.getMultipleAccounts = getMultipleAccounts2;
|
|
2001
|
-
exports$1.getMinimumBalanceForRentExemptAccount = getMinimumBalanceForRentExemptAccount2;
|
|
2002
|
-
exports$1.getAccountLen = getAccountLen2;
|
|
2003
|
-
exports$1.getMinimumBalanceForRentExemptAccountWithExtensions = getMinimumBalanceForRentExemptAccountWithExtensions2;
|
|
2004
|
-
exports$1.unpackAccount = unpackAccount2;
|
|
2005
|
-
exports$1.getAssociatedTokenAddressSync = getAssociatedTokenAddressSync2;
|
|
2006
|
-
exports$1.createAssociatedTokenAccountInstruction = createAssociatedTokenAccountInstruction2;
|
|
2007
|
-
exports$1.createAssociatedTokenAccountIdempotentInstruction = createAssociatedTokenAccountIdempotentInstruction2;
|
|
2008
|
-
exports$1.createSyncNativeInstruction = createSyncNativeInstruction2;
|
|
2009
|
-
exports$1.createCloseAccountInstruction = createCloseAccountInstruction2;
|
|
2010
|
-
exports$1.createTransferCheckedInstruction = createTransferCheckedInstruction2;
|
|
2011
|
-
exports$1.createInitializeAccountInstruction = createInitializeAccountInstruction2;
|
|
2012
|
-
exports$1.addSigners = addSigners2;
|
|
2013
|
-
exports$1.getMint = getMint2;
|
|
2014
|
-
exports$1.createMemoInstruction = createMemoInstruction2;
|
|
2015
|
-
var buffer_layout_1 = __require("@solana/buffer-layout");
|
|
2016
|
-
var buffer_layout_utils_1 = __require("@solana/buffer-layout-utils");
|
|
2017
|
-
var web3_js_1 = __require("@solana/web3.js");
|
|
2018
|
-
var buffer_1 = __require("buffer");
|
|
2019
|
-
exports$1.MultisigLayout = (0, buffer_layout_1.struct)([
|
|
2020
|
-
(0, buffer_layout_1.u8)("m"),
|
|
2021
|
-
(0, buffer_layout_1.u8)("n"),
|
|
2022
|
-
(0, buffer_layout_utils_1.bool)("isInitialized"),
|
|
2023
|
-
(0, buffer_layout_utils_1.publicKey)("signer1"),
|
|
2024
|
-
(0, buffer_layout_utils_1.publicKey)("signer2"),
|
|
2025
|
-
(0, buffer_layout_utils_1.publicKey)("signer3"),
|
|
2026
|
-
(0, buffer_layout_utils_1.publicKey)("signer4"),
|
|
2027
|
-
(0, buffer_layout_utils_1.publicKey)("signer5"),
|
|
2028
|
-
(0, buffer_layout_utils_1.publicKey)("signer6"),
|
|
2029
|
-
(0, buffer_layout_utils_1.publicKey)("signer7"),
|
|
2030
|
-
(0, buffer_layout_utils_1.publicKey)("signer8"),
|
|
2031
|
-
(0, buffer_layout_utils_1.publicKey)("signer9"),
|
|
2032
|
-
(0, buffer_layout_utils_1.publicKey)("signer10"),
|
|
2033
|
-
(0, buffer_layout_utils_1.publicKey)("signer11")
|
|
2034
|
-
]);
|
|
2035
|
-
exports$1.MULTISIG_SIZE = exports$1.MultisigLayout.span;
|
|
2036
|
-
var SplAccountType2;
|
|
2037
|
-
(function(SplAccountType3) {
|
|
2038
|
-
SplAccountType3[SplAccountType3["Uninitialized"] = 0] = "Uninitialized";
|
|
2039
|
-
SplAccountType3[SplAccountType3["Mint"] = 1] = "Mint";
|
|
2040
|
-
SplAccountType3[SplAccountType3["Account"] = 2] = "Account";
|
|
2041
|
-
})(SplAccountType2 || (exports$1.SplAccountType = SplAccountType2 = {}));
|
|
2042
|
-
exports$1.ACCOUNT_TYPE_SIZE = 1;
|
|
2043
|
-
var TokenError2 = class extends Error {
|
|
2044
|
-
constructor(message) {
|
|
2045
|
-
super(message);
|
|
2046
|
-
}
|
|
2047
|
-
};
|
|
2048
|
-
exports$1.TokenError = TokenError2;
|
|
2049
|
-
var TokenAccountNotFoundError2 = class extends TokenError2 {
|
|
2050
|
-
constructor() {
|
|
2051
|
-
super(...arguments);
|
|
2052
|
-
this.name = "TokenAccountNotFoundError";
|
|
2053
|
-
}
|
|
2054
|
-
};
|
|
2055
|
-
exports$1.TokenAccountNotFoundError = TokenAccountNotFoundError2;
|
|
2056
|
-
var TokenInvalidAccountError2 = class extends TokenError2 {
|
|
2057
|
-
constructor() {
|
|
2058
|
-
super(...arguments);
|
|
2059
|
-
this.name = "TokenInvalidAccountError";
|
|
2060
|
-
}
|
|
2061
|
-
};
|
|
2062
|
-
exports$1.TokenInvalidAccountError = TokenInvalidAccountError2;
|
|
2063
|
-
var TokenInvalidAccountOwnerError2 = class extends TokenError2 {
|
|
2064
|
-
constructor() {
|
|
2065
|
-
super(...arguments);
|
|
2066
|
-
this.name = "TokenInvalidAccountOwnerError";
|
|
2067
|
-
}
|
|
2068
|
-
};
|
|
2069
|
-
exports$1.TokenInvalidAccountOwnerError = TokenInvalidAccountOwnerError2;
|
|
2070
|
-
var TokenInvalidAccountSizeError2 = class extends TokenError2 {
|
|
2071
|
-
constructor() {
|
|
2072
|
-
super(...arguments);
|
|
2073
|
-
this.name = "TokenInvalidAccountSizeError";
|
|
2074
|
-
}
|
|
2075
|
-
};
|
|
2076
|
-
exports$1.TokenInvalidAccountSizeError = TokenInvalidAccountSizeError2;
|
|
2077
|
-
var TokenInvalidMintError2 = class extends TokenError2 {
|
|
2078
|
-
constructor() {
|
|
2079
|
-
super(...arguments);
|
|
2080
|
-
this.name = "TokenInvalidMintError";
|
|
2081
|
-
}
|
|
2082
|
-
};
|
|
2083
|
-
exports$1.TokenInvalidMintError = TokenInvalidMintError2;
|
|
2084
|
-
var TokenInvalidOwnerError2 = class extends TokenError2 {
|
|
2085
|
-
constructor() {
|
|
2086
|
-
super(...arguments);
|
|
2087
|
-
this.name = "TokenInvalidOwnerError";
|
|
2088
|
-
}
|
|
2089
|
-
};
|
|
2090
|
-
exports$1.TokenInvalidOwnerError = TokenInvalidOwnerError2;
|
|
2091
|
-
var TokenOwnerOffCurveError2 = class extends TokenError2 {
|
|
2092
|
-
constructor() {
|
|
2093
|
-
super(...arguments);
|
|
2094
|
-
this.name = "TokenOwnerOffCurveError";
|
|
2095
|
-
}
|
|
2096
|
-
};
|
|
2097
|
-
exports$1.TokenOwnerOffCurveError = TokenOwnerOffCurveError2;
|
|
2098
|
-
var TokenInvalidInstructionProgramError2 = class extends TokenError2 {
|
|
2099
|
-
constructor() {
|
|
2100
|
-
super(...arguments);
|
|
2101
|
-
this.name = "TokenInvalidInstructionProgramError";
|
|
2102
|
-
}
|
|
2103
|
-
};
|
|
2104
|
-
exports$1.TokenInvalidInstructionProgramError = TokenInvalidInstructionProgramError2;
|
|
2105
|
-
var TokenInvalidInstructionKeysError2 = class extends TokenError2 {
|
|
2106
|
-
constructor() {
|
|
2107
|
-
super(...arguments);
|
|
2108
|
-
this.name = "TokenInvalidInstructionKeysError";
|
|
2109
|
-
}
|
|
2110
|
-
};
|
|
2111
|
-
exports$1.TokenInvalidInstructionKeysError = TokenInvalidInstructionKeysError2;
|
|
2112
|
-
var TokenInvalidInstructionDataError2 = class extends TokenError2 {
|
|
2113
|
-
constructor() {
|
|
2114
|
-
super(...arguments);
|
|
2115
|
-
this.name = "TokenInvalidInstructionDataError";
|
|
2116
|
-
}
|
|
2117
|
-
};
|
|
2118
|
-
exports$1.TokenInvalidInstructionDataError = TokenInvalidInstructionDataError2;
|
|
2119
|
-
var TokenInvalidInstructionTypeError2 = class extends TokenError2 {
|
|
2120
|
-
constructor() {
|
|
2121
|
-
super(...arguments);
|
|
2122
|
-
this.name = "TokenInvalidInstructionTypeError";
|
|
2123
|
-
}
|
|
2124
|
-
};
|
|
2125
|
-
exports$1.TokenInvalidInstructionTypeError = TokenInvalidInstructionTypeError2;
|
|
2126
|
-
var TokenUnsupportedInstructionError2 = class extends TokenError2 {
|
|
2127
|
-
constructor() {
|
|
2128
|
-
super(...arguments);
|
|
2129
|
-
this.name = "TokenUnsupportedInstructionError";
|
|
2130
|
-
}
|
|
2131
|
-
};
|
|
2132
|
-
exports$1.TokenUnsupportedInstructionError = TokenUnsupportedInstructionError2;
|
|
2133
|
-
var AccountState2;
|
|
2134
|
-
(function(AccountState3) {
|
|
2135
|
-
AccountState3[AccountState3["Uninitialized"] = 0] = "Uninitialized";
|
|
2136
|
-
AccountState3[AccountState3["Initialized"] = 1] = "Initialized";
|
|
2137
|
-
AccountState3[AccountState3["Frozen"] = 2] = "Frozen";
|
|
2138
|
-
})(AccountState2 || (exports$1.AccountState = AccountState2 = {}));
|
|
2139
|
-
exports$1.AccountLayout = (0, buffer_layout_1.struct)([
|
|
2140
|
-
(0, buffer_layout_utils_1.publicKey)("mint"),
|
|
2141
|
-
(0, buffer_layout_utils_1.publicKey)("owner"),
|
|
2142
|
-
(0, buffer_layout_utils_1.u64)("amount"),
|
|
2143
|
-
(0, buffer_layout_1.u32)("delegateOption"),
|
|
2144
|
-
(0, buffer_layout_utils_1.publicKey)("delegate"),
|
|
2145
|
-
(0, buffer_layout_1.u8)("state"),
|
|
2146
|
-
(0, buffer_layout_1.u32)("isNativeOption"),
|
|
2147
|
-
(0, buffer_layout_utils_1.u64)("isNative"),
|
|
2148
|
-
(0, buffer_layout_utils_1.u64)("delegatedAmount"),
|
|
2149
|
-
(0, buffer_layout_1.u32)("closeAuthorityOption"),
|
|
2150
|
-
(0, buffer_layout_utils_1.publicKey)("closeAuthority")
|
|
2151
|
-
]);
|
|
2152
|
-
exports$1.ACCOUNT_SIZE = exports$1.AccountLayout.span;
|
|
2153
|
-
exports$1.NATIVE_MINT = new web3_js_1.PublicKey("So11111111111111111111111111111111111111112");
|
|
2154
|
-
async function getAccount2(connection, address, commitment, programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2155
|
-
const info = await connection.getAccountInfo(address, commitment);
|
|
2156
|
-
return unpackAccount2(address, info, programId);
|
|
2157
|
-
}
|
|
2158
|
-
exports$1.TOKEN_PROGRAM_ID = new web3_js_1.PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
|
|
2159
|
-
exports$1.TOKEN_2022_PROGRAM_ID = new web3_js_1.PublicKey("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");
|
|
2160
|
-
async function getMultipleAccounts2(connection, addresses, commitment, programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2161
|
-
const infos = await connection.getMultipleAccountsInfo(addresses, commitment);
|
|
2162
|
-
return addresses.map((address, i) => (
|
|
2163
|
-
//@ts-ignore
|
|
2164
|
-
unpackAccount2(address, infos[i], programId)
|
|
2165
|
-
));
|
|
2166
|
-
}
|
|
2167
|
-
async function getMinimumBalanceForRentExemptAccount2(connection, commitment) {
|
|
2168
|
-
return await getMinimumBalanceForRentExemptAccountWithExtensions2(connection, [], commitment);
|
|
2169
|
-
}
|
|
2170
|
-
var ExtensionType2;
|
|
2171
|
-
(function(ExtensionType3) {
|
|
2172
|
-
ExtensionType3[ExtensionType3["Uninitialized"] = 0] = "Uninitialized";
|
|
2173
|
-
ExtensionType3[ExtensionType3["TransferFeeConfig"] = 1] = "TransferFeeConfig";
|
|
2174
|
-
ExtensionType3[ExtensionType3["TransferFeeAmount"] = 2] = "TransferFeeAmount";
|
|
2175
|
-
ExtensionType3[ExtensionType3["MintCloseAuthority"] = 3] = "MintCloseAuthority";
|
|
2176
|
-
ExtensionType3[ExtensionType3["ConfidentialTransferMint"] = 4] = "ConfidentialTransferMint";
|
|
2177
|
-
ExtensionType3[ExtensionType3["ConfidentialTransferAccount"] = 5] = "ConfidentialTransferAccount";
|
|
2178
|
-
ExtensionType3[ExtensionType3["DefaultAccountState"] = 6] = "DefaultAccountState";
|
|
2179
|
-
ExtensionType3[ExtensionType3["ImmutableOwner"] = 7] = "ImmutableOwner";
|
|
2180
|
-
ExtensionType3[ExtensionType3["MemoTransfer"] = 8] = "MemoTransfer";
|
|
2181
|
-
ExtensionType3[ExtensionType3["NonTransferable"] = 9] = "NonTransferable";
|
|
2182
|
-
ExtensionType3[ExtensionType3["InterestBearingMint"] = 10] = "InterestBearingMint";
|
|
2183
|
-
})(ExtensionType2 || (exports$1.ExtensionType = ExtensionType2 = {}));
|
|
2184
|
-
function getAccountLen2(extensionTypes) {
|
|
2185
|
-
return getLen2(extensionTypes, exports$1.ACCOUNT_SIZE);
|
|
2186
|
-
}
|
|
2187
|
-
exports$1.TYPE_SIZE = 2;
|
|
2188
|
-
exports$1.LENGTH_SIZE = 2;
|
|
2189
|
-
function getLen2(extensionTypes, baseSize) {
|
|
2190
|
-
if (extensionTypes.length === 0) {
|
|
2191
|
-
return baseSize;
|
|
2192
|
-
} else {
|
|
2193
|
-
const accountLength = exports$1.ACCOUNT_SIZE + exports$1.ACCOUNT_TYPE_SIZE;
|
|
2194
|
-
if (accountLength === exports$1.MULTISIG_SIZE) {
|
|
2195
|
-
return accountLength + exports$1.TYPE_SIZE;
|
|
2196
|
-
} else {
|
|
2197
|
-
return accountLength;
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
}
|
|
2201
|
-
async function getMinimumBalanceForRentExemptAccountWithExtensions2(connection, extensions, commitment) {
|
|
2202
|
-
const accountLen = getAccountLen2(extensions);
|
|
2203
|
-
return await connection.getMinimumBalanceForRentExemption(accountLen, commitment);
|
|
2204
|
-
}
|
|
2205
|
-
function unpackAccount2(address, info, programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2206
|
-
if (!info)
|
|
2207
|
-
throw new TokenAccountNotFoundError2();
|
|
2208
|
-
if (!info.owner.equals(programId))
|
|
2209
|
-
throw new TokenInvalidAccountOwnerError2();
|
|
2210
|
-
if (info.data.length < exports$1.ACCOUNT_SIZE)
|
|
2211
|
-
throw new TokenInvalidAccountSizeError2();
|
|
2212
|
-
const rawAccount = exports$1.AccountLayout.decode(info.data.slice(0, exports$1.ACCOUNT_SIZE));
|
|
2213
|
-
let tlvData = buffer_1.Buffer.alloc(0);
|
|
2214
|
-
if (info.data.length > exports$1.ACCOUNT_SIZE) {
|
|
2215
|
-
if (info.data.length === exports$1.MULTISIG_SIZE)
|
|
2216
|
-
throw new TokenInvalidAccountSizeError2();
|
|
2217
|
-
if (info.data[exports$1.ACCOUNT_SIZE] != SplAccountType2.Account)
|
|
2218
|
-
throw new TokenInvalidAccountError2();
|
|
2219
|
-
tlvData = info.data.slice(exports$1.ACCOUNT_SIZE + exports$1.ACCOUNT_TYPE_SIZE);
|
|
2220
|
-
}
|
|
2221
|
-
return {
|
|
2222
|
-
address,
|
|
2223
|
-
mint: rawAccount.mint,
|
|
2224
|
-
owner: rawAccount.owner,
|
|
2225
|
-
amount: rawAccount.amount,
|
|
2226
|
-
delegate: rawAccount.delegateOption ? rawAccount.delegate : null,
|
|
2227
|
-
delegatedAmount: rawAccount.delegatedAmount,
|
|
2228
|
-
isInitialized: rawAccount.state !== AccountState2.Uninitialized,
|
|
2229
|
-
isFrozen: rawAccount.state === AccountState2.Frozen,
|
|
2230
|
-
isNative: !!rawAccount.isNativeOption,
|
|
2231
|
-
rentExemptReserve: rawAccount.isNativeOption ? rawAccount.isNative : null,
|
|
2232
|
-
closeAuthority: rawAccount.closeAuthorityOption ? rawAccount.closeAuthority : null,
|
|
2233
|
-
tlvData
|
|
2234
|
-
};
|
|
2235
|
-
}
|
|
2236
|
-
exports$1.ASSOCIATED_TOKEN_PROGRAM_ID = new web3_js_1.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
|
|
2237
|
-
function getAssociatedTokenAddressSync2(mint, owner, allowOwnerOffCurve = false, programId = exports$1.TOKEN_PROGRAM_ID, associatedTokenProgramId = exports$1.ASSOCIATED_TOKEN_PROGRAM_ID) {
|
|
2238
|
-
if (!allowOwnerOffCurve && !web3_js_1.PublicKey.isOnCurve(owner.toBuffer()))
|
|
2239
|
-
throw new TokenOwnerOffCurveError2();
|
|
2240
|
-
const [address] = web3_js_1.PublicKey.findProgramAddressSync([owner.toBuffer(), programId.toBuffer(), mint.toBuffer()], associatedTokenProgramId);
|
|
2241
|
-
return address;
|
|
2242
|
-
}
|
|
2243
|
-
function createAssociatedTokenAccountInstruction2(payer, associatedToken, owner, mint, programId = exports$1.TOKEN_PROGRAM_ID, associatedTokenProgramId = exports$1.ASSOCIATED_TOKEN_PROGRAM_ID) {
|
|
2244
|
-
const keys = [
|
|
2245
|
-
{ pubkey: payer, isSigner: true, isWritable: true },
|
|
2246
|
-
{ pubkey: associatedToken, isSigner: false, isWritable: true },
|
|
2247
|
-
{ pubkey: owner, isSigner: false, isWritable: false },
|
|
2248
|
-
{ pubkey: mint, isSigner: false, isWritable: false },
|
|
2249
|
-
{ pubkey: web3_js_1.SystemProgram.programId, isSigner: false, isWritable: false },
|
|
2250
|
-
{ pubkey: programId, isSigner: false, isWritable: false },
|
|
2251
|
-
{ pubkey: web3_js_1.SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false }
|
|
2252
|
-
];
|
|
2253
|
-
return new web3_js_1.TransactionInstruction({
|
|
2254
|
-
keys,
|
|
2255
|
-
programId: associatedTokenProgramId,
|
|
2256
|
-
data: buffer_1.Buffer.alloc(0)
|
|
2257
|
-
});
|
|
2258
|
-
}
|
|
2259
|
-
function createAssociatedTokenAccountIdempotentInstruction2(payer, associatedToken, owner, mint, programId = exports$1.TOKEN_PROGRAM_ID, associatedTokenProgramId = exports$1.ASSOCIATED_TOKEN_PROGRAM_ID) {
|
|
2260
|
-
return buildAssociatedTokenAccountInstruction2(payer, associatedToken, owner, mint, buffer_1.Buffer.from([1]), programId, associatedTokenProgramId);
|
|
2261
|
-
}
|
|
2262
|
-
exports$1.syncNativeInstructionData = (0, buffer_layout_1.struct)([(0, buffer_layout_1.u8)("instruction")]);
|
|
2263
|
-
function createSyncNativeInstruction2(account, programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2264
|
-
const keys = [{ pubkey: account, isSigner: false, isWritable: true }];
|
|
2265
|
-
const data = buffer_1.Buffer.alloc(exports$1.syncNativeInstructionData.span);
|
|
2266
|
-
exports$1.syncNativeInstructionData.encode({ instruction: TokenInstruction2.SyncNative }, data);
|
|
2267
|
-
return new web3_js_1.TransactionInstruction({ keys, programId, data });
|
|
2268
|
-
}
|
|
2269
|
-
exports$1.closeAccountInstructionData = (0, buffer_layout_1.struct)([(0, buffer_layout_1.u8)("instruction")]);
|
|
2270
|
-
function createCloseAccountInstruction2(account, destination, authority, multiSigners = [], programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2271
|
-
const keys = addSigners2([
|
|
2272
|
-
{ pubkey: account, isSigner: false, isWritable: true },
|
|
2273
|
-
{ pubkey: destination, isSigner: false, isWritable: true }
|
|
2274
|
-
], authority, multiSigners);
|
|
2275
|
-
const data = buffer_1.Buffer.alloc(exports$1.closeAccountInstructionData.span);
|
|
2276
|
-
exports$1.closeAccountInstructionData.encode({ instruction: TokenInstruction2.CloseAccount }, data);
|
|
2277
|
-
return new web3_js_1.TransactionInstruction({ keys, programId, data });
|
|
2278
|
-
}
|
|
2279
|
-
function buildAssociatedTokenAccountInstruction2(payer, associatedToken, owner, mint, instructionData, programId = exports$1.TOKEN_PROGRAM_ID, associatedTokenProgramId = exports$1.ASSOCIATED_TOKEN_PROGRAM_ID) {
|
|
2280
|
-
const keys = [
|
|
2281
|
-
{ pubkey: payer, isSigner: true, isWritable: true },
|
|
2282
|
-
{ pubkey: associatedToken, isSigner: false, isWritable: true },
|
|
2283
|
-
{ pubkey: owner, isSigner: false, isWritable: false },
|
|
2284
|
-
{ pubkey: mint, isSigner: false, isWritable: false },
|
|
2285
|
-
{ pubkey: web3_js_1.SystemProgram.programId, isSigner: false, isWritable: false },
|
|
2286
|
-
{ pubkey: programId, isSigner: false, isWritable: false }
|
|
2287
|
-
];
|
|
2288
|
-
return new web3_js_1.TransactionInstruction({
|
|
2289
|
-
keys,
|
|
2290
|
-
programId: associatedTokenProgramId,
|
|
2291
|
-
data: instructionData
|
|
2292
|
-
});
|
|
2293
|
-
}
|
|
2294
|
-
exports$1.transferCheckedInstructionData = (0, buffer_layout_1.struct)([
|
|
2295
|
-
(0, buffer_layout_1.u8)("instruction"),
|
|
2296
|
-
(0, buffer_layout_utils_1.u64)("amount"),
|
|
2297
|
-
(0, buffer_layout_1.u8)("decimals")
|
|
2298
|
-
]);
|
|
2299
|
-
function createTransferCheckedInstruction2(source, mint, destination, owner, amount, decimals, multiSigners = [], programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2300
|
-
const keys = addSigners2([
|
|
2301
|
-
{ pubkey: source, isSigner: false, isWritable: true },
|
|
2302
|
-
{ pubkey: mint, isSigner: false, isWritable: false },
|
|
2303
|
-
{ pubkey: destination, isSigner: false, isWritable: true }
|
|
2304
|
-
], owner, multiSigners);
|
|
2305
|
-
const data = buffer_1.Buffer.alloc(exports$1.transferCheckedInstructionData.span);
|
|
2306
|
-
exports$1.transferCheckedInstructionData.encode({
|
|
2307
|
-
instruction: TokenInstruction2.TransferChecked,
|
|
2308
|
-
amount: BigInt(amount),
|
|
2309
|
-
decimals
|
|
2310
|
-
}, data);
|
|
2311
|
-
return new web3_js_1.TransactionInstruction({ keys, programId, data });
|
|
2312
|
-
}
|
|
2313
|
-
var TokenInstruction2;
|
|
2314
|
-
(function(TokenInstruction3) {
|
|
2315
|
-
TokenInstruction3[TokenInstruction3["InitializeAccount"] = 1] = "InitializeAccount";
|
|
2316
|
-
TokenInstruction3[TokenInstruction3["TransferChecked"] = 12] = "TransferChecked";
|
|
2317
|
-
TokenInstruction3[TokenInstruction3["CloseAccount"] = 9] = "CloseAccount";
|
|
2318
|
-
TokenInstruction3[TokenInstruction3["SyncNative"] = 17] = "SyncNative";
|
|
2319
|
-
})(TokenInstruction2 || (exports$1.TokenInstruction = TokenInstruction2 = {}));
|
|
2320
|
-
exports$1.initializeAccountInstructionData = (0, buffer_layout_1.struct)([(0, buffer_layout_1.u8)("instruction")]);
|
|
2321
|
-
function createInitializeAccountInstruction2(account, mint, owner, programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2322
|
-
const keys = [
|
|
2323
|
-
{ pubkey: account, isSigner: false, isWritable: true },
|
|
2324
|
-
{ pubkey: mint, isSigner: false, isWritable: false },
|
|
2325
|
-
{ pubkey: owner, isSigner: false, isWritable: false },
|
|
2326
|
-
{ pubkey: web3_js_1.SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false }
|
|
2327
|
-
];
|
|
2328
|
-
const data = buffer_1.Buffer.alloc(exports$1.initializeAccountInstructionData.span);
|
|
2329
|
-
exports$1.initializeAccountInstructionData.encode({ instruction: TokenInstruction2.InitializeAccount }, data);
|
|
2330
|
-
return new web3_js_1.TransactionInstruction({ keys, programId, data });
|
|
2331
|
-
}
|
|
2332
|
-
function addSigners2(keys, ownerOrAuthority, multiSigners) {
|
|
2333
|
-
if (multiSigners.length) {
|
|
2334
|
-
keys.push({ pubkey: ownerOrAuthority, isSigner: false, isWritable: false });
|
|
2335
|
-
for (const signer of multiSigners) {
|
|
2336
|
-
keys.push({
|
|
2337
|
-
pubkey: signer.publicKey,
|
|
2338
|
-
isSigner: true,
|
|
2339
|
-
isWritable: false
|
|
2340
|
-
});
|
|
2341
|
-
}
|
|
2342
|
-
} else {
|
|
2343
|
-
keys.push({ pubkey: ownerOrAuthority, isSigner: true, isWritable: false });
|
|
2344
|
-
}
|
|
2345
|
-
return keys;
|
|
2346
|
-
}
|
|
2347
|
-
exports$1.MintLayout = (0, buffer_layout_1.struct)([
|
|
2348
|
-
(0, buffer_layout_1.u32)("mintAuthorityOption"),
|
|
2349
|
-
(0, buffer_layout_utils_1.publicKey)("mintAuthority"),
|
|
2350
|
-
(0, buffer_layout_utils_1.u64)("supply"),
|
|
2351
|
-
(0, buffer_layout_1.u8)("decimals"),
|
|
2352
|
-
(0, buffer_layout_utils_1.bool)("isInitialized"),
|
|
2353
|
-
(0, buffer_layout_1.u32)("freezeAuthorityOption"),
|
|
2354
|
-
(0, buffer_layout_utils_1.publicKey)("freezeAuthority")
|
|
2355
|
-
]);
|
|
2356
|
-
exports$1.MINT_SIZE = exports$1.MintLayout.span;
|
|
2357
|
-
async function getMint2(connection, address, commitment, programId = exports$1.TOKEN_PROGRAM_ID) {
|
|
2358
|
-
const info = await connection.getAccountInfo(address, commitment);
|
|
2359
|
-
if (!info)
|
|
2360
|
-
throw new TokenAccountNotFoundError2();
|
|
2361
|
-
if (!info.owner.equals(programId))
|
|
2362
|
-
throw new TokenInvalidAccountOwnerError2();
|
|
2363
|
-
if (info.data.length != exports$1.MINT_SIZE)
|
|
2364
|
-
throw new TokenInvalidAccountSizeError2();
|
|
2365
|
-
const rawMint = exports$1.MintLayout.decode(info.data);
|
|
2366
|
-
return {
|
|
2367
|
-
address,
|
|
2368
|
-
mintAuthority: rawMint.mintAuthorityOption ? rawMint.mintAuthority : null,
|
|
2369
|
-
supply: rawMint.supply,
|
|
2370
|
-
decimals: rawMint.decimals,
|
|
2371
|
-
isInitialized: rawMint.isInitialized,
|
|
2372
|
-
freezeAuthority: rawMint.freezeAuthorityOption ? rawMint.freezeAuthority : null
|
|
2373
|
-
};
|
|
2374
|
-
}
|
|
2375
|
-
exports$1.MEMO_PROGRAM_ID = new web3_js_1.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr");
|
|
2376
|
-
function createMemoInstruction2(memo, signerPubkeys) {
|
|
2377
|
-
const keys = signerPubkeys == null ? [] : signerPubkeys.map(function(key) {
|
|
2378
|
-
return { pubkey: key, isSigner: true, isWritable: false };
|
|
2379
|
-
});
|
|
2380
|
-
return new web3_js_1.TransactionInstruction({
|
|
2381
|
-
keys,
|
|
2382
|
-
programId: exports$1.MEMO_PROGRAM_ID,
|
|
2383
|
-
data: buffer_1.Buffer.from(memo, "utf8")
|
|
2384
|
-
});
|
|
2385
|
-
}
|
|
2386
|
-
}
|
|
2387
|
-
});
|
|
2388
|
-
|
|
2389
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/priority.js
|
|
2390
|
-
var require_priority = __commonJS({
|
|
2391
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/priority.js"(exports$1) {
|
|
2392
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
2393
|
-
exports$1.getRecentPrioritizationFeesByPercentile = exports$1.getMedianPrioritizationFeeByPercentile = exports$1.getMeanPrioritizationFeeByPercentile = exports$1.getMaxPrioritizationFeeByPercentile = exports$1.getMinPrioritizationFeeByPercentile = exports$1.getCalculatedPrioritizationFeeByPercentile = exports$1.PriotitizationFeeLevels = void 0;
|
|
2394
|
-
var PriotitizationFeeLevels;
|
|
2395
|
-
(function(PriotitizationFeeLevels2) {
|
|
2396
|
-
PriotitizationFeeLevels2[PriotitizationFeeLevels2["LOW"] = 2500] = "LOW";
|
|
2397
|
-
PriotitizationFeeLevels2[PriotitizationFeeLevels2["MEDIAN"] = 5e3] = "MEDIAN";
|
|
2398
|
-
PriotitizationFeeLevels2[PriotitizationFeeLevels2["HIGH"] = 7500] = "HIGH";
|
|
2399
|
-
PriotitizationFeeLevels2[PriotitizationFeeLevels2["MAX"] = 1e4] = "MAX";
|
|
2400
|
-
})(PriotitizationFeeLevels || (exports$1.PriotitizationFeeLevels = PriotitizationFeeLevels = {}));
|
|
2401
|
-
var getCalculatedPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
|
|
2402
|
-
const fees = await (0, exports$1.getRecentPrioritizationFeesByPercentile)(connection, config, slotsToReturn);
|
|
2403
|
-
const { min, max, sum } = fees.reduce((acc, fee) => ({
|
|
2404
|
-
min: fee.prioritizationFee < acc.min.prioritizationFee ? fee : acc.min,
|
|
2405
|
-
max: fee.prioritizationFee > acc.max.prioritizationFee ? fee : acc.max,
|
|
2406
|
-
sum: acc.sum + fee.prioritizationFee
|
|
2407
|
-
}), { min: fees[0], max: fees[0], sum: 0 });
|
|
2408
|
-
const mean = Math.ceil(sum / fees.length);
|
|
2409
|
-
const sortedFees = [...fees].sort((a, b) => a.prioritizationFee - b.prioritizationFee);
|
|
2410
|
-
const midIndex = Math.floor(fees.length / 2);
|
|
2411
|
-
const median = fees.length % 2 === 0 ? Math.ceil((sortedFees[midIndex - 1].prioritizationFee + sortedFees[midIndex].prioritizationFee) / 2) : sortedFees[midIndex].prioritizationFee;
|
|
2412
|
-
return {
|
|
2413
|
-
min,
|
|
2414
|
-
max,
|
|
2415
|
-
mean,
|
|
2416
|
-
median
|
|
2417
|
-
};
|
|
2418
|
-
};
|
|
2419
|
-
exports$1.getCalculatedPrioritizationFeeByPercentile = getCalculatedPrioritizationFeeByPercentile;
|
|
2420
|
-
var getMinPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
|
|
2421
|
-
const recentPrioritizationFees = await (0, exports$1.getRecentPrioritizationFeesByPercentile)(connection, config, slotsToReturn);
|
|
2422
|
-
const minPriorityFee = recentPrioritizationFees.reduce((min, current) => {
|
|
2423
|
-
return current.prioritizationFee < min.prioritizationFee ? current : min;
|
|
2424
|
-
});
|
|
2425
|
-
return minPriorityFee.prioritizationFee;
|
|
2426
|
-
};
|
|
2427
|
-
exports$1.getMinPrioritizationFeeByPercentile = getMinPrioritizationFeeByPercentile;
|
|
2428
|
-
var getMaxPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
|
|
2429
|
-
const recentPrioritizationFees = await (0, exports$1.getRecentPrioritizationFeesByPercentile)(connection, config, slotsToReturn);
|
|
2430
|
-
const maxPriorityFee = recentPrioritizationFees.reduce((max, current) => {
|
|
2431
|
-
return current.prioritizationFee > max.prioritizationFee ? current : max;
|
|
2432
|
-
});
|
|
2433
|
-
return maxPriorityFee.prioritizationFee;
|
|
2434
|
-
};
|
|
2435
|
-
exports$1.getMaxPrioritizationFeeByPercentile = getMaxPrioritizationFeeByPercentile;
|
|
2436
|
-
var getMeanPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
|
|
2437
|
-
const recentPrioritizationFees = await (0, exports$1.getRecentPrioritizationFeesByPercentile)(connection, config, slotsToReturn);
|
|
2438
|
-
const mean = Math.ceil(recentPrioritizationFees.reduce((acc, fee) => acc + fee.prioritizationFee, 0) / recentPrioritizationFees.length);
|
|
2439
|
-
return mean;
|
|
2440
|
-
};
|
|
2441
|
-
exports$1.getMeanPrioritizationFeeByPercentile = getMeanPrioritizationFeeByPercentile;
|
|
2442
|
-
var getMedianPrioritizationFeeByPercentile = async (connection, config, slotsToReturn) => {
|
|
2443
|
-
const recentPrioritizationFees = await (0, exports$1.getRecentPrioritizationFeesByPercentile)(connection, config, slotsToReturn);
|
|
2444
|
-
recentPrioritizationFees.sort((a, b) => a.prioritizationFee - b.prioritizationFee);
|
|
2445
|
-
const half = Math.floor(recentPrioritizationFees.length / 2);
|
|
2446
|
-
if (recentPrioritizationFees.length % 2) {
|
|
2447
|
-
return recentPrioritizationFees[half].prioritizationFee;
|
|
2448
|
-
}
|
|
2449
|
-
return Math.ceil((recentPrioritizationFees[half - 1].prioritizationFee + recentPrioritizationFees[half].prioritizationFee) / 2);
|
|
2450
|
-
};
|
|
2451
|
-
exports$1.getMedianPrioritizationFeeByPercentile = getMedianPrioritizationFeeByPercentile;
|
|
2452
|
-
var getRecentPrioritizationFeesFromRpc = async (config, rpcRequest) => {
|
|
2453
|
-
const accounts = config?.lockedWritableAccounts?.map((key) => key.toBase58());
|
|
2454
|
-
const args = accounts?.length ? [accounts] : [[]];
|
|
2455
|
-
config.percentile && args.push({ percentile: config.percentile });
|
|
2456
|
-
const response = await rpcRequest("getRecentPrioritizationFees", args);
|
|
2457
|
-
return response;
|
|
2458
|
-
};
|
|
2459
|
-
var getRecentPrioritizationFeesByPercentile = async (connection, config, slotsToReturn) => {
|
|
2460
|
-
const { fallback = true, lockedWritableAccounts = [] } = config || {};
|
|
2461
|
-
slotsToReturn = slotsToReturn && Number.isInteger(slotsToReturn) ? slotsToReturn : -1;
|
|
2462
|
-
const promises = [];
|
|
2463
|
-
let tritonRpcResponse = void 0;
|
|
2464
|
-
let fallbackRpcResponse = void 0;
|
|
2465
|
-
const rpcRequest = connection._rpcRequest;
|
|
2466
|
-
promises.push(getRecentPrioritizationFeesFromRpc(config, rpcRequest).then((result) => {
|
|
2467
|
-
tritonRpcResponse = result;
|
|
2468
|
-
}));
|
|
2469
|
-
if (fallback) {
|
|
2470
|
-
promises.push(getRecentPrioritizationFeesFromRpc({ lockedWritableAccounts }, rpcRequest).then((result) => {
|
|
2471
|
-
fallbackRpcResponse = result;
|
|
2472
|
-
}));
|
|
2473
|
-
}
|
|
2474
|
-
await Promise.all(promises);
|
|
2475
|
-
const tritonGRPFResponse = tritonRpcResponse;
|
|
2476
|
-
const fallbackGRPFResponse = fallbackRpcResponse;
|
|
2477
|
-
let recentPrioritizationFees = [];
|
|
2478
|
-
if (tritonGRPFResponse?.result) {
|
|
2479
|
-
recentPrioritizationFees = tritonGRPFResponse.result;
|
|
2480
|
-
}
|
|
2481
|
-
if (fallbackGRPFResponse?.result && !tritonGRPFResponse?.result) {
|
|
2482
|
-
recentPrioritizationFees = fallbackGRPFResponse.result;
|
|
2483
|
-
}
|
|
2484
|
-
if (fallback && fallbackGRPFResponse.error) {
|
|
2485
|
-
return fallbackGRPFResponse.error;
|
|
2486
|
-
}
|
|
2487
|
-
if (tritonGRPFResponse?.error) {
|
|
2488
|
-
return tritonGRPFResponse.error;
|
|
2489
|
-
}
|
|
2490
|
-
recentPrioritizationFees.sort((a, b) => a.slot - b.slot);
|
|
2491
|
-
if (slotsToReturn > 0)
|
|
2492
|
-
return recentPrioritizationFees.slice(0, slotsToReturn);
|
|
2493
|
-
return recentPrioritizationFees;
|
|
2494
|
-
};
|
|
2495
|
-
exports$1.getRecentPrioritizationFeesByPercentile = getRecentPrioritizationFeesByPercentile;
|
|
2496
|
-
}
|
|
2497
|
-
});
|
|
2498
|
-
|
|
2499
|
-
// node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/index.js
|
|
2500
|
-
var require_dist = __commonJS({
|
|
2501
|
-
"node_modules/.pnpm/@mrgnlabs+mrgn-common@2.0.5_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10/node_modules/@mrgnlabs/mrgn-common/dist/index.js"(exports$1) {
|
|
2502
|
-
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
2503
|
-
if (k2 === void 0) k2 = k;
|
|
2504
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
2505
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
2506
|
-
desc = { enumerable: true, get: function() {
|
|
2507
|
-
return m[k];
|
|
2508
|
-
} };
|
|
2509
|
-
}
|
|
2510
|
-
Object.defineProperty(o, k2, desc);
|
|
2511
|
-
}) : (function(o, m, k, k2) {
|
|
2512
|
-
if (k2 === void 0) k2 = k;
|
|
2513
|
-
o[k2] = m[k];
|
|
2514
|
-
}));
|
|
2515
|
-
var __exportStar = exports$1 && exports$1.__exportStar || function(m, exports2) {
|
|
2516
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
|
|
2517
|
-
};
|
|
2518
|
-
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
2519
|
-
exports$1.NodeWallet = void 0;
|
|
2520
|
-
var nodeWallet_1 = require_nodeWallet();
|
|
2521
|
-
Object.defineProperty(exports$1, "NodeWallet", { enumerable: true, get: function() {
|
|
2522
|
-
return nodeWallet_1.NodeWallet;
|
|
2523
|
-
} });
|
|
2524
|
-
__exportStar(require_cache(), exports$1);
|
|
2525
|
-
__exportStar(require_types(), exports$1);
|
|
2526
|
-
__exportStar(require_misc(), exports$1);
|
|
2527
|
-
__exportStar(require_math(), exports$1);
|
|
2528
|
-
__exportStar(require_utils(), exports$1);
|
|
2529
|
-
__exportStar(require_modules(), exports$1);
|
|
2530
|
-
__exportStar(require_spl(), exports$1);
|
|
2531
|
-
__exportStar(require_priority(), exports$1);
|
|
2532
|
-
__exportStar(require_constants(), exports$1);
|
|
2533
|
-
}
|
|
2534
|
-
});
|
|
2535
|
-
|
|
2536
38
|
// src/vendor/pyth_legacy/readBig.ts
|
|
2537
39
|
var ERR_BUFFER_OUT_OF_BOUNDS = () => new Error("Attempt to access memory outside buffer bounds");
|
|
2538
40
|
var ERR_INVALID_ARG_TYPE = (name, expected, actual) => new Error(
|
|
@@ -2762,6 +264,9 @@ var SYSVAR_STAKE_HISTORY_ID = new web3_js.PublicKey(
|
|
|
2762
264
|
new web3_js.PublicKey(
|
|
2763
265
|
"StakeConfig11111111111111111111111111111111"
|
|
2764
266
|
);
|
|
267
|
+
new web3_js.PublicKey("So11111111111111111111111111111111111111112");
|
|
268
|
+
new web3_js.PublicKey("LSTxxxnJzKDFSLr4dUkPcmCf5VyryEqzPLz5j4bpxFp");
|
|
269
|
+
var USDC_MINT = new web3_js.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
|
2765
270
|
|
|
2766
271
|
// src/vendor/spl/types/account.types.ts
|
|
2767
272
|
var AccountState = /* @__PURE__ */ ((AccountState2) => {
|
|
@@ -15487,7 +12992,7 @@ function roundNearest(decimal) {
|
|
|
15487
12992
|
var interpolateLinear = (x, x0, y0, x1, y1) => {
|
|
15488
12993
|
return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
|
|
15489
12994
|
};
|
|
15490
|
-
var
|
|
12995
|
+
var getKaminoBorrowRate = (currentUtilization, curve) => {
|
|
15491
12996
|
let [x0, y0, x1, y1] = [0, 0, 0, 0];
|
|
15492
12997
|
if (currentUtilization > 1) {
|
|
15493
12998
|
currentUtilization = 1;
|
|
@@ -15519,29 +13024,21 @@ var getBorrowRate = (currentUtilization, curve) => {
|
|
|
15519
13024
|
function calculateAPYFromAPR(apr) {
|
|
15520
13025
|
return Math.pow(1 + apr / SLOTS_PER_YEAR, SLOTS_PER_YEAR) - 1;
|
|
15521
13026
|
}
|
|
15522
|
-
function
|
|
15523
|
-
const liquidityAvailableAmount = new Decimal3__default.default(
|
|
15524
|
-
|
|
15525
|
-
);
|
|
15526
|
-
const borrowedAmount = new Fraction(
|
|
15527
|
-
reserve.liquidity.borrowedAmountSf
|
|
15528
|
-
).toDecimal();
|
|
13027
|
+
function getKaminoTotalSupply(reserve) {
|
|
13028
|
+
const liquidityAvailableAmount = new Decimal3__default.default(reserve.liquidity.availableAmount.toString());
|
|
13029
|
+
const borrowedAmount = new Fraction(reserve.liquidity.borrowedAmountSf).toDecimal();
|
|
15529
13030
|
const accumulatedProtocolFee = new Fraction(
|
|
15530
13031
|
reserve.liquidity.accumulatedProtocolFeesSf
|
|
15531
13032
|
).toDecimal();
|
|
15532
13033
|
const accumulatedReferrerFees = new Fraction(
|
|
15533
13034
|
reserve.liquidity.accumulatedReferrerFeesSf
|
|
15534
13035
|
).toDecimal();
|
|
15535
|
-
const pendingReferrerFees = new Fraction(
|
|
15536
|
-
reserve.liquidity.pendingReferrerFeesSf
|
|
15537
|
-
).toDecimal();
|
|
13036
|
+
const pendingReferrerFees = new Fraction(reserve.liquidity.pendingReferrerFeesSf).toDecimal();
|
|
15538
13037
|
return liquidityAvailableAmount.add(borrowedAmount).sub(accumulatedProtocolFee).sub(accumulatedReferrerFees).sub(pendingReferrerFees);
|
|
15539
13038
|
}
|
|
15540
13039
|
function calculateUtilizationRatio(reserve) {
|
|
15541
|
-
const totalBorrows = new Fraction(
|
|
15542
|
-
|
|
15543
|
-
).toDecimal();
|
|
15544
|
-
const totalSupply = getTotalSupply(reserve);
|
|
13040
|
+
const totalBorrows = new Fraction(reserve.liquidity.borrowedAmountSf).toDecimal();
|
|
13041
|
+
const totalSupply = getKaminoTotalSupply(reserve);
|
|
15545
13042
|
if (totalSupply.eq(0)) {
|
|
15546
13043
|
return 0;
|
|
15547
13044
|
}
|
|
@@ -15553,38 +13050,28 @@ function slotAdjustmentFactor(recentSlotDurationMs = DEFAULT_RECENT_SLOT_DURATIO
|
|
|
15553
13050
|
function calculateSlotAdjustmentFactor(reserve, recentSlotDurationMs) {
|
|
15554
13051
|
return 1e3 / SLOTS_PER_SECOND / recentSlotDurationMs;
|
|
15555
13052
|
}
|
|
15556
|
-
function
|
|
13053
|
+
function calculateKaminoEstimatedBorrowRate(reserve, recentSlotDurationMs = DEFAULT_RECENT_SLOT_DURATION_MS) {
|
|
15557
13054
|
const slotAdjFactor = slotAdjustmentFactor(recentSlotDurationMs);
|
|
15558
13055
|
const currentUtilization = calculateUtilizationRatio(reserve);
|
|
15559
13056
|
const curve = truncateBorrowCurve(reserve.config.borrowRateCurve.points);
|
|
15560
|
-
return
|
|
13057
|
+
return getKaminoBorrowRate(currentUtilization, curve) * slotAdjFactor;
|
|
15561
13058
|
}
|
|
15562
|
-
function
|
|
15563
|
-
const borrowRate =
|
|
15564
|
-
reserve,
|
|
15565
|
-
recentSlotDurationMs
|
|
15566
|
-
);
|
|
13059
|
+
function calculateKaminoEstimatedSupplyRate(reserve, recentSlotDurationMs = DEFAULT_RECENT_SLOT_DURATION_MS) {
|
|
13060
|
+
const borrowRate = calculateKaminoEstimatedBorrowRate(reserve, recentSlotDurationMs);
|
|
15567
13061
|
const currentUtilization = calculateUtilizationRatio(reserve);
|
|
15568
13062
|
const protocolTakeRatePct = 1 - reserve.config.protocolTakeRatePct / 100;
|
|
15569
13063
|
return borrowRate * currentUtilization * protocolTakeRatePct;
|
|
15570
13064
|
}
|
|
15571
|
-
function
|
|
13065
|
+
function calculateKaminoSupplyAPY(reserve, recentSlotDurationMs = DEFAULT_RECENT_SLOT_DURATION_MS) {
|
|
15572
13066
|
const currentUtilization = calculateUtilizationRatio(reserve);
|
|
15573
|
-
const borrowRate =
|
|
15574
|
-
reserve,
|
|
15575
|
-
recentSlotDurationMs
|
|
15576
|
-
);
|
|
13067
|
+
const borrowRate = calculateKaminoEstimatedBorrowRate(reserve, recentSlotDurationMs);
|
|
15577
13068
|
const protocolTakeRatePct = 1 - reserve.config.protocolTakeRatePct / 100;
|
|
15578
|
-
return calculateAPYFromAPR(
|
|
15579
|
-
currentUtilization * borrowRate * protocolTakeRatePct
|
|
15580
|
-
);
|
|
13069
|
+
return calculateAPYFromAPR(currentUtilization * borrowRate * protocolTakeRatePct);
|
|
15581
13070
|
}
|
|
15582
13071
|
function scaledSupplies(state) {
|
|
15583
13072
|
const liqMintDecimals = new Decimal3__default.default(state.liquidity.mintDecimals.toString());
|
|
15584
|
-
const totalSupplyLamports =
|
|
15585
|
-
const mintTotalSupplyLam = new Decimal3__default.default(
|
|
15586
|
-
state.collateral.mintTotalSupply.toString()
|
|
15587
|
-
);
|
|
13073
|
+
const totalSupplyLamports = getKaminoTotalSupply(state);
|
|
13074
|
+
const mintTotalSupplyLam = new Decimal3__default.default(state.collateral.mintTotalSupply.toString());
|
|
15588
13075
|
const liqScale = new Decimal3__default.default(10).pow(liqMintDecimals);
|
|
15589
13076
|
const collScale = new Decimal3__default.default(10).pow(liqMintDecimals);
|
|
15590
13077
|
const totalSupply = totalSupplyLamports.div(liqScale);
|
|
@@ -15617,7 +13104,7 @@ function generateKaminoReserveCurve(curvePoints, slotAdjustmentFactor2, fixedHos
|
|
|
15617
13104
|
const curve = truncateBorrowCurve(curvePoints);
|
|
15618
13105
|
return Array.from({ length: 101 }, (_, i) => {
|
|
15619
13106
|
const utilization = i / 100;
|
|
15620
|
-
const baseBorrowRate =
|
|
13107
|
+
const baseBorrowRate = getKaminoBorrowRate(utilization, curve) * slotAdjustmentFactor2;
|
|
15621
13108
|
const borrowAPR = baseBorrowRate + fixedHostInterestRate;
|
|
15622
13109
|
const supplyAPR = utilization * borrowAPR * protocolTakeRatePct;
|
|
15623
13110
|
const borrowAPY = calculateAPYFromAPR(borrowAPR);
|
|
@@ -15655,9 +13142,7 @@ function getRewardPerTimeUnitSecond(reward) {
|
|
|
15655
13142
|
const rewardAmountPerUnitDecimals = new Decimal3__default.default(10).pow(
|
|
15656
13143
|
reward.rewardsPerSecondDecimals.toString()
|
|
15657
13144
|
);
|
|
15658
|
-
const rewardAmountPerUnitLamports = new Decimal3__default.default(10).pow(
|
|
15659
|
-
rewardTokenDecimals.toString()
|
|
15660
|
-
);
|
|
13145
|
+
const rewardAmountPerUnitLamports = new Decimal3__default.default(10).pow(rewardTokenDecimals.toString());
|
|
15661
13146
|
const rpsAdjusted = new Decimal3__default.default(rewardPerTimeUnitSecond.toString()).div(rewardAmountPerUnitDecimals).div(rewardAmountPerUnitLamports);
|
|
15662
13147
|
return rewardPerTimeUnitSecond ? rpsAdjusted : new Decimal3__default.default(0);
|
|
15663
13148
|
}
|
|
@@ -15673,18 +13158,14 @@ async function getReserveRewardsApy(priceByMint, farmState, reserveState) {
|
|
|
15673
13158
|
if (reservePrice === void 0 || reservePrice === null || rewardPrice === void 0 || rewardPrice === null) {
|
|
15674
13159
|
continue;
|
|
15675
13160
|
}
|
|
15676
|
-
const { apy, apr } = calculateRewardApy(
|
|
15677
|
-
priceByMint,
|
|
15678
|
-
reserveState,
|
|
15679
|
-
rewardInfo
|
|
15680
|
-
);
|
|
13161
|
+
const { apy, apr } = calculateRewardApy(priceByMint, reserveState, rewardInfo);
|
|
15681
13162
|
rewardApys.push({ rewardApy: apy, rewardInfo, rewardApr: apr });
|
|
15682
13163
|
}
|
|
15683
13164
|
return rewardApys;
|
|
15684
13165
|
}
|
|
15685
13166
|
function calculateRewardApy(priceByMint, reserve, rewardInfo) {
|
|
15686
13167
|
const decimals = reserve.liquidity.mintDecimals.toNumber();
|
|
15687
|
-
const totalSupply =
|
|
13168
|
+
const totalSupply = getKaminoTotalSupply(reserve);
|
|
15688
13169
|
const mintAddress = reserve.liquidity.mintPubkey;
|
|
15689
13170
|
const totalAmount = lamportsToNumberDecimal(totalSupply, decimals);
|
|
15690
13171
|
const mintPrice = priceByMint[mintAddress.toString()] ?? 0;
|
|
@@ -30042,7 +27523,8 @@ function driftSpotMarketRawToDto(spotMarketRaw) {
|
|
|
30042
27523
|
minBorrowRate: spotMarketRaw.minBorrowRate,
|
|
30043
27524
|
insuranceFund: {
|
|
30044
27525
|
totalFactor: spotMarketRaw.insuranceFund.totalFactor
|
|
30045
|
-
}
|
|
27526
|
+
},
|
|
27527
|
+
poolId: spotMarketRaw.poolId
|
|
30046
27528
|
};
|
|
30047
27529
|
}
|
|
30048
27530
|
function driftRewardsRawToDto(rewardsRaw) {
|
|
@@ -30212,7 +27694,8 @@ function dtoToDriftSpotMarketRaw(spotMarketDto) {
|
|
|
30212
27694
|
optimalBorrowRate: spotMarketDto.optimalBorrowRate,
|
|
30213
27695
|
maxBorrowRate: spotMarketDto.maxBorrowRate,
|
|
30214
27696
|
minBorrowRate: spotMarketDto.minBorrowRate,
|
|
30215
|
-
insuranceFund: spotMarketDto.insuranceFund
|
|
27697
|
+
insuranceFund: spotMarketDto.insuranceFund,
|
|
27698
|
+
poolId: spotMarketDto.poolId
|
|
30216
27699
|
};
|
|
30217
27700
|
}
|
|
30218
27701
|
function decodeDriftSpotMarketData(data) {
|
|
@@ -30473,9 +27956,7 @@ var TEN = new anchor.BN(10);
|
|
|
30473
27956
|
var PERCENTAGE_PRECISION_EXP = new anchor.BN(6);
|
|
30474
27957
|
var PERCENTAGE_PRECISION = new anchor.BN(10).pow(PERCENTAGE_PRECISION_EXP);
|
|
30475
27958
|
var SPOT_MARKET_RATE_PRECISION_EXP = new anchor.BN(6);
|
|
30476
|
-
var SPOT_MARKET_RATE_PRECISION = new anchor.BN(10).pow(
|
|
30477
|
-
SPOT_MARKET_RATE_PRECISION_EXP
|
|
30478
|
-
);
|
|
27959
|
+
var SPOT_MARKET_RATE_PRECISION = new anchor.BN(10).pow(SPOT_MARKET_RATE_PRECISION_EXP);
|
|
30479
27960
|
var SPOT_MARKET_UTILIZATION_PRECISION_EXP = new anchor.BN(6);
|
|
30480
27961
|
var SPOT_MARKET_UTILIZATION_PRECISION = new anchor.BN(10).pow(
|
|
30481
27962
|
SPOT_MARKET_UTILIZATION_PRECISION_EXP
|
|
@@ -30489,24 +27970,21 @@ function divCeil(a, b) {
|
|
|
30489
27970
|
}
|
|
30490
27971
|
return quotient;
|
|
30491
27972
|
}
|
|
30492
|
-
function
|
|
27973
|
+
function getDriftTokenAmount(balanceAmount, spotMarket, balanceType) {
|
|
30493
27974
|
const precisionDecrease = TEN.pow(new anchor.BN(19 - spotMarket.decimals));
|
|
30494
27975
|
if (isSpotBalanceTypeVariant(balanceType, "deposit")) {
|
|
30495
27976
|
return balanceAmount.mul(spotMarket.cumulativeDepositInterest).div(precisionDecrease);
|
|
30496
27977
|
} else {
|
|
30497
|
-
return divCeil(
|
|
30498
|
-
balanceAmount.mul(spotMarket.cumulativeBorrowInterest),
|
|
30499
|
-
precisionDecrease
|
|
30500
|
-
);
|
|
27978
|
+
return divCeil(balanceAmount.mul(spotMarket.cumulativeBorrowInterest), precisionDecrease);
|
|
30501
27979
|
}
|
|
30502
27980
|
}
|
|
30503
|
-
function
|
|
30504
|
-
let tokenDepositAmount =
|
|
27981
|
+
function calculateDriftUtilization(bank, delta = ZERO) {
|
|
27982
|
+
let tokenDepositAmount = getDriftTokenAmount(
|
|
30505
27983
|
bank.depositBalance,
|
|
30506
27984
|
bank,
|
|
30507
27985
|
"deposit" /* DEPOSIT */
|
|
30508
27986
|
);
|
|
30509
|
-
let tokenBorrowAmount =
|
|
27987
|
+
let tokenBorrowAmount = getDriftTokenAmount(
|
|
30510
27988
|
bank.borrowBalance,
|
|
30511
27989
|
bank,
|
|
30512
27990
|
"borrow" /* BORROW */
|
|
@@ -30526,14 +28004,12 @@ function calculateUtilization(bank, delta = ZERO) {
|
|
|
30526
28004
|
}
|
|
30527
28005
|
return utilization;
|
|
30528
28006
|
}
|
|
30529
|
-
function
|
|
30530
|
-
const utilization = currentUtilization ||
|
|
28007
|
+
function calculateDriftInterestRate(bank, delta = ZERO, currentUtilization = null) {
|
|
28008
|
+
const utilization = currentUtilization || calculateDriftUtilization(bank, delta);
|
|
30531
28009
|
const optimalUtil = new anchor.BN(bank.optimalUtilization);
|
|
30532
28010
|
const optimalRate = new anchor.BN(bank.optimalBorrowRate);
|
|
30533
28011
|
const maxRate = new anchor.BN(bank.maxBorrowRate);
|
|
30534
|
-
const minRate = new anchor.BN(bank.minBorrowRate).mul(
|
|
30535
|
-
PERCENTAGE_PRECISION.divn(200)
|
|
30536
|
-
);
|
|
28012
|
+
const minRate = new anchor.BN(bank.minBorrowRate).mul(PERCENTAGE_PRECISION.divn(200));
|
|
30537
28013
|
const weightsDivisor = new anchor.BN(1e3);
|
|
30538
28014
|
const segments = [
|
|
30539
28015
|
[new anchor.BN(85e4), new anchor.BN(50)],
|
|
@@ -30568,17 +28044,17 @@ function calculateInterestRate(bank, delta = ZERO, currentUtilization = null) {
|
|
|
30568
28044
|
}
|
|
30569
28045
|
return anchor.BN.max(minRate, rate);
|
|
30570
28046
|
}
|
|
30571
|
-
function
|
|
30572
|
-
return
|
|
28047
|
+
function calculateDriftBorrowRate(bank, delta = ZERO, currentUtilization = null) {
|
|
28048
|
+
return calculateDriftInterestRate(bank, delta, currentUtilization);
|
|
30573
28049
|
}
|
|
30574
|
-
function
|
|
30575
|
-
const utilization = currentUtilization ||
|
|
30576
|
-
const borrowRate =
|
|
28050
|
+
function calculateDriftDepositRate(bank, delta = ZERO, currentUtilization = null) {
|
|
28051
|
+
const utilization = currentUtilization || calculateDriftUtilization(bank, delta);
|
|
28052
|
+
const borrowRate = calculateDriftBorrowRate(bank, delta, utilization);
|
|
30577
28053
|
const depositRate = borrowRate.mul(PERCENTAGE_PRECISION.sub(new anchor.BN(bank.insuranceFund.totalFactor))).mul(utilization).div(SPOT_MARKET_UTILIZATION_PRECISION).div(PERCENTAGE_PRECISION);
|
|
30578
28054
|
return depositRate;
|
|
30579
28055
|
}
|
|
30580
|
-
function
|
|
30581
|
-
const depositRate =
|
|
28056
|
+
function calculateDriftLendingAPY(bank, delta = ZERO, currentUtilization = null, compoundingPeriodsPerYear = 365) {
|
|
28057
|
+
const depositRate = calculateDriftDepositRate(bank, delta, currentUtilization);
|
|
30582
28058
|
if (depositRate.eq(ZERO)) {
|
|
30583
28059
|
return ZERO;
|
|
30584
28060
|
}
|
|
@@ -30605,13 +28081,13 @@ function calculateLendingAPY(bank, delta = ZERO, currentUtilization = null, comp
|
|
|
30605
28081
|
const apy = apyInCalcPrecision.mul(PERCENTAGE_PRECISION).div(CALC_PRECISION);
|
|
30606
28082
|
return apy;
|
|
30607
28083
|
}
|
|
30608
|
-
function
|
|
30609
|
-
const depositRate =
|
|
28084
|
+
function calculateDriftLendingAPR(bank, delta = ZERO, currentUtilization = null) {
|
|
28085
|
+
const depositRate = calculateDriftDepositRate(bank, delta, currentUtilization);
|
|
30610
28086
|
const apr = depositRate.mul(PERCENTAGE_PRECISION).div(SPOT_MARKET_RATE_PRECISION);
|
|
30611
28087
|
return apr;
|
|
30612
28088
|
}
|
|
30613
|
-
function
|
|
30614
|
-
const borrowRate =
|
|
28089
|
+
function calculateDriftBorrowAPY(bank, delta = ZERO, currentUtilization = null, compoundingPeriodsPerYear = 365) {
|
|
28090
|
+
const borrowRate = calculateDriftBorrowRate(bank, delta, currentUtilization);
|
|
30615
28091
|
if (borrowRate.eq(ZERO)) {
|
|
30616
28092
|
return ZERO;
|
|
30617
28093
|
}
|
|
@@ -30638,22 +28114,46 @@ function calculateBorrowAPY(bank, delta = ZERO, currentUtilization = null, compo
|
|
|
30638
28114
|
const apy = apyInCalcPrecision.mul(PERCENTAGE_PRECISION).div(CALC_PRECISION);
|
|
30639
28115
|
return apy;
|
|
30640
28116
|
}
|
|
30641
|
-
function
|
|
30642
|
-
const borrowRate =
|
|
28117
|
+
function calculateDriftBorrowAPR(bank, delta = ZERO, currentUtilization = null) {
|
|
28118
|
+
const borrowRate = calculateDriftBorrowRate(bank, delta, currentUtilization);
|
|
30643
28119
|
const apr = borrowRate.mul(PERCENTAGE_PRECISION).div(SPOT_MARKET_RATE_PRECISION);
|
|
30644
28120
|
return apr;
|
|
30645
28121
|
}
|
|
28122
|
+
var SLOTS_PER_YEAR2 = 63072e3;
|
|
28123
|
+
function calculateAPYFromAPR2(apr) {
|
|
28124
|
+
if (apr === 0) return 0;
|
|
28125
|
+
return Math.pow(1 + apr / SLOTS_PER_YEAR2, SLOTS_PER_YEAR2) - 1;
|
|
28126
|
+
}
|
|
28127
|
+
function generateDriftReserveCurve(spotMarket) {
|
|
28128
|
+
return Array.from({ length: 101 }, (_, i) => {
|
|
28129
|
+
const utilizationPercent = i / 100;
|
|
28130
|
+
const utilizationBN = new anchor.BN(
|
|
28131
|
+
Math.floor(utilizationPercent * SPOT_MARKET_UTILIZATION_PRECISION.toNumber())
|
|
28132
|
+
);
|
|
28133
|
+
const borrowRateBN = calculateDriftBorrowRate(spotMarket, ZERO, utilizationBN);
|
|
28134
|
+
const depositRateBN = calculateDriftDepositRate(spotMarket, ZERO, utilizationBN);
|
|
28135
|
+
const borrowAPR = borrowRateBN.toNumber() / SPOT_MARKET_RATE_PRECISION.toNumber();
|
|
28136
|
+
const supplyAPR = depositRateBN.toNumber() / SPOT_MARKET_RATE_PRECISION.toNumber();
|
|
28137
|
+
const borrowAPY = calculateAPYFromAPR2(borrowAPR);
|
|
28138
|
+
const supplyAPY = calculateAPYFromAPR2(supplyAPR);
|
|
28139
|
+
return {
|
|
28140
|
+
utilization: utilizationPercent * 100,
|
|
28141
|
+
// Convert to percentage (0-100)
|
|
28142
|
+
borrowAPY: borrowAPY * 100,
|
|
28143
|
+
// Convert to percentage
|
|
28144
|
+
supplyAPY: supplyAPY * 100
|
|
28145
|
+
// Convert to percentage
|
|
28146
|
+
};
|
|
28147
|
+
});
|
|
28148
|
+
}
|
|
30646
28149
|
|
|
30647
28150
|
// src/vendor/drift/utils/rewards.utils.ts
|
|
30648
|
-
var import_mrgn_common = __toESM(require_dist());
|
|
30649
28151
|
async function getDriftRewards(spotMarkets, userStates, connection) {
|
|
30650
28152
|
let missingMarketIndexes = /* @__PURE__ */ new Set();
|
|
30651
|
-
const spotMarketsMap = new Map(
|
|
30652
|
-
spotMarkets.map((market) => [market.marketIndex, market])
|
|
30653
|
-
);
|
|
28153
|
+
const spotMarketsMap = new Map(spotMarkets.map((market) => [market.marketIndex, market]));
|
|
30654
28154
|
const userStatesWithRewards = userStates.map((userState) => {
|
|
30655
28155
|
const spotPositions = userState.driftUser.spotPositions;
|
|
30656
|
-
const isUsdc = userState.marketMint.equals(
|
|
28156
|
+
const isUsdc = userState.marketMint.equals(USDC_MINT);
|
|
30657
28157
|
spotPositions.length;
|
|
30658
28158
|
const rewardIndex = isUsdc ? 1 : 2;
|
|
30659
28159
|
const rewards = spotPositions.slice(rewardIndex).filter((p) => p.marketIndex !== 0);
|
|
@@ -30678,9 +28178,7 @@ async function getDriftRewards(spotMarkets, userStates, connection) {
|
|
|
30678
28178
|
const missingMarketsAccounts = missingMarketKeys.length ? await connection.getMultipleAccountsInfo(missingMarketKeys) : [];
|
|
30679
28179
|
const missingMarketsMap = new Map([
|
|
30680
28180
|
// Include all existing spot markets
|
|
30681
|
-
...spotMarkets.map(
|
|
30682
|
-
(market) => [market.marketIndex, market]
|
|
30683
|
-
),
|
|
28181
|
+
...spotMarkets.map((market) => [market.marketIndex, market]),
|
|
30684
28182
|
// Add newly fetched missing markets
|
|
30685
28183
|
...missingMarketsAccounts.map((account, idx) => {
|
|
30686
28184
|
const marketIndex = missingMarketIndexesArray[idx];
|
|
@@ -30689,18 +28187,13 @@ async function getDriftRewards(spotMarkets, userStates, connection) {
|
|
|
30689
28187
|
return null;
|
|
30690
28188
|
}
|
|
30691
28189
|
if (!account) {
|
|
30692
|
-
console.error(
|
|
30693
|
-
"Missing market account, for ",
|
|
30694
|
-
missingMarketKeys[idx]?.toBase58()
|
|
30695
|
-
);
|
|
28190
|
+
console.error("Missing market account, for ", missingMarketKeys[idx]?.toBase58());
|
|
30696
28191
|
return null;
|
|
30697
28192
|
} else {
|
|
30698
28193
|
const decodedMarket = decodeDriftSpotMarketData(account.data);
|
|
30699
28194
|
return [marketIndex, decodedMarket];
|
|
30700
28195
|
}
|
|
30701
|
-
}).filter(
|
|
30702
|
-
(market) => market !== null
|
|
30703
|
-
)
|
|
28196
|
+
}).filter((market) => market !== null)
|
|
30704
28197
|
]);
|
|
30705
28198
|
const driftRewardsByBank = new Map(
|
|
30706
28199
|
userStatesWithRewards.map((userStateWithRewards) => {
|
|
@@ -30734,15 +28227,11 @@ async function getAllRequiredMarkets(spotMarkets, driftUsers, connection) {
|
|
|
30734
28227
|
const missingMarketIndexes = Array.from(allKeysFlattened).filter(
|
|
30735
28228
|
(index) => !spotMarkets.some((market) => market.marketIndex === index)
|
|
30736
28229
|
);
|
|
30737
|
-
const missingMarketKeys = missingMarketIndexes.map(
|
|
30738
|
-
(index) => deriveDriftSpotMarket(index)[0]
|
|
30739
|
-
);
|
|
28230
|
+
const missingMarketKeys = missingMarketIndexes.map((index) => deriveDriftSpotMarket(index)[0]);
|
|
30740
28231
|
const missingMarketsAccounts = missingMarketKeys.length ? await connection.getMultipleAccountsInfo(missingMarketKeys) : [];
|
|
30741
28232
|
const allMarketsMap = new Map([
|
|
30742
28233
|
// Include all existing spot markets
|
|
30743
|
-
...spotMarkets.map(
|
|
30744
|
-
(market) => [market.marketIndex, market]
|
|
30745
|
-
),
|
|
28234
|
+
...spotMarkets.map((market) => [market.marketIndex, market]),
|
|
30746
28235
|
// Add newly fetched missing markets
|
|
30747
28236
|
...missingMarketsAccounts.map((account, idx) => {
|
|
30748
28237
|
const marketIndex = missingMarketIndexes[idx];
|
|
@@ -30751,18 +28240,13 @@ async function getAllRequiredMarkets(spotMarkets, driftUsers, connection) {
|
|
|
30751
28240
|
return null;
|
|
30752
28241
|
}
|
|
30753
28242
|
if (!account) {
|
|
30754
|
-
console.error(
|
|
30755
|
-
"Missing market account, for ",
|
|
30756
|
-
missingMarketKeys[idx]?.toBase58()
|
|
30757
|
-
);
|
|
28243
|
+
console.error("Missing market account, for ", missingMarketKeys[idx]?.toBase58());
|
|
30758
28244
|
return null;
|
|
30759
28245
|
} else {
|
|
30760
28246
|
const decodedMarket = decodeDriftSpotMarketData(account.data);
|
|
30761
28247
|
return [marketIndex, decodedMarket];
|
|
30762
28248
|
}
|
|
30763
|
-
}).filter(
|
|
30764
|
-
(market) => market !== null
|
|
30765
|
-
)
|
|
28249
|
+
}).filter((market) => market !== null)
|
|
30766
28250
|
]);
|
|
30767
28251
|
return Array.from(allMarketsMap.values());
|
|
30768
28252
|
}
|
|
@@ -30811,17 +28295,6 @@ function makeUpdateSpotMarketIx({ spotMarket }) {
|
|
|
30811
28295
|
spotMarketVault
|
|
30812
28296
|
);
|
|
30813
28297
|
}
|
|
30814
|
-
/*! Bundled license information:
|
|
30815
|
-
|
|
30816
|
-
numeral/numeral.js:
|
|
30817
|
-
(*! @preserve
|
|
30818
|
-
* numeral.js
|
|
30819
|
-
* version : 2.0.6
|
|
30820
|
-
* author : Adam Draper
|
|
30821
|
-
* license : MIT
|
|
30822
|
-
* http://adamwdraper.github.com/Numeral-js/
|
|
30823
|
-
*)
|
|
30824
|
-
*/
|
|
30825
28298
|
|
|
30826
28299
|
exports.ACCOUNT_SIZE = ACCOUNT_SIZE;
|
|
30827
28300
|
exports.ACCOUNT_TYPE_SIZE = ACCOUNT_TYPE_SIZE;
|
|
@@ -30906,19 +28379,19 @@ exports.TokenUnsupportedInstructionError = TokenUnsupportedInstructionError;
|
|
|
30906
28379
|
exports.ZERO = ZERO;
|
|
30907
28380
|
exports.addSigners = addSigners;
|
|
30908
28381
|
exports.calculateAPYFromAPR = calculateAPYFromAPR;
|
|
30909
|
-
exports.
|
|
30910
|
-
exports.
|
|
30911
|
-
exports.
|
|
30912
|
-
exports.
|
|
30913
|
-
exports.
|
|
30914
|
-
exports.
|
|
30915
|
-
exports.
|
|
30916
|
-
exports.
|
|
30917
|
-
exports.
|
|
28382
|
+
exports.calculateDriftBorrowAPR = calculateDriftBorrowAPR;
|
|
28383
|
+
exports.calculateDriftBorrowAPY = calculateDriftBorrowAPY;
|
|
28384
|
+
exports.calculateDriftBorrowRate = calculateDriftBorrowRate;
|
|
28385
|
+
exports.calculateDriftDepositRate = calculateDriftDepositRate;
|
|
28386
|
+
exports.calculateDriftInterestRate = calculateDriftInterestRate;
|
|
28387
|
+
exports.calculateDriftLendingAPR = calculateDriftLendingAPR;
|
|
28388
|
+
exports.calculateDriftLendingAPY = calculateDriftLendingAPY;
|
|
28389
|
+
exports.calculateDriftUtilization = calculateDriftUtilization;
|
|
28390
|
+
exports.calculateKaminoEstimatedBorrowRate = calculateKaminoEstimatedBorrowRate;
|
|
28391
|
+
exports.calculateKaminoEstimatedSupplyRate = calculateKaminoEstimatedSupplyRate;
|
|
28392
|
+
exports.calculateKaminoSupplyAPY = calculateKaminoSupplyAPY;
|
|
30918
28393
|
exports.calculateRewardApy = calculateRewardApy;
|
|
30919
28394
|
exports.calculateSlotAdjustmentFactor = calculateSlotAdjustmentFactor;
|
|
30920
|
-
exports.calculateSupplyAPY = calculateSupplyAPY;
|
|
30921
|
-
exports.calculateUtilization = calculateUtilization;
|
|
30922
28395
|
exports.calculateUtilizationRatio = calculateUtilizationRatio;
|
|
30923
28396
|
exports.closeAccountInstructionData = closeAccountInstructionData;
|
|
30924
28397
|
exports.createAccountIx = createAccountIx;
|
|
@@ -30979,6 +28452,7 @@ exports.findPoolMplAuthorityAddress = findPoolMplAuthorityAddress;
|
|
|
30979
28452
|
exports.findPoolOnRampAddress = findPoolOnRampAddress;
|
|
30980
28453
|
exports.findPoolStakeAddress = findPoolStakeAddress;
|
|
30981
28454
|
exports.findPoolStakeAuthorityAddress = findPoolStakeAuthorityAddress;
|
|
28455
|
+
exports.generateDriftReserveCurve = generateDriftReserveCurve;
|
|
30982
28456
|
exports.generateKaminoReserveCurve = generateKaminoReserveCurve;
|
|
30983
28457
|
exports.getAccount = getAccount;
|
|
30984
28458
|
exports.getAccountLen = getAccountLen;
|
|
@@ -30986,9 +28460,11 @@ exports.getAllDerivedDriftAccounts = getAllDerivedDriftAccounts;
|
|
|
30986
28460
|
exports.getAllDerivedKaminoAccounts = getAllDerivedKaminoAccounts;
|
|
30987
28461
|
exports.getAllRequiredMarkets = getAllRequiredMarkets;
|
|
30988
28462
|
exports.getAssociatedTokenAddressSync = getAssociatedTokenAddressSync;
|
|
30989
|
-
exports.getBorrowRate = getBorrowRate;
|
|
30990
28463
|
exports.getDriftRewards = getDriftRewards;
|
|
28464
|
+
exports.getDriftTokenAmount = getDriftTokenAmount;
|
|
30991
28465
|
exports.getFixedHostInterestRate = getFixedHostInterestRate;
|
|
28466
|
+
exports.getKaminoBorrowRate = getKaminoBorrowRate;
|
|
28467
|
+
exports.getKaminoTotalSupply = getKaminoTotalSupply;
|
|
30992
28468
|
exports.getMinimumBalanceForRentExemptAccount = getMinimumBalanceForRentExemptAccount;
|
|
30993
28469
|
exports.getMinimumBalanceForRentExemptAccountWithExtensions = getMinimumBalanceForRentExemptAccountWithExtensions;
|
|
30994
28470
|
exports.getMint = getMint;
|
|
@@ -30998,8 +28474,6 @@ exports.getReserveRewardsApy = getReserveRewardsApy;
|
|
|
30998
28474
|
exports.getRewardPerTimeUnitSecond = getRewardPerTimeUnitSecond;
|
|
30999
28475
|
exports.getStakeAccount = getStakeAccount;
|
|
31000
28476
|
exports.getSwitchboardProgram = getSwitchboardProgram;
|
|
31001
|
-
exports.getTokenAmount = getTokenAmount;
|
|
31002
|
-
exports.getTotalSupply = getTotalSupply;
|
|
31003
28477
|
exports.initializeAccountInstructionData = initializeAccountInstructionData;
|
|
31004
28478
|
exports.initializeStakedPoolIxs = initializeStakedPoolIxs;
|
|
31005
28479
|
exports.initializeStakedPoolTx = initializeStakedPoolTx;
|