@flipflop-sdk/tools
Version:
[](https://deepwiki.com/flipflop-fun/sdk) [](https://badge.fury.io/js/%40flipflop-sdk%2Ftools) [ • 53.4 kB
JavaScript
"use strict";
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.connection = exports.configAccount = exports.compareMints = exports.cleanMetadata = exports.BN_MILLION = exports.BN_LAMPORTS_PER_SOL = void 0;
exports.getFeeValue = getFeeValue;
exports.getLegacyTokenMetadata = getLegacyTokenMetadata;
exports.systemConfigAccount = exports.refundAccountPda = exports.referralAccount = exports.processVersionedTransaction = exports.processTransaction = exports.parseConfigData = exports.numberStringToBN = exports.mintBy = exports.mintAccount = exports.metadataAccountPda = exports.getTokenBalance = exports.getSystemConfig = exports.getSolanaBalance = exports.getReferrerCodeHash = exports.getReferralDataByCodeHash = void 0;
var _web = require("@solana/web3.js");
var _config = require("../config");
var _buffer = require("buffer");
var _anchor = require("@coral-xyz/anchor");
var _splToken = require("@solana/spl-token");
var _pda = require("./pda");
var _token = require("@coral-xyz/anchor/dist/cjs/utils/token");
var _system = require("@coral-xyz/anchor/dist/cjs/native/system");
var _raydiumSdkV = require("@raydium-io/raydium-sdk-v2");
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return r; }; var t, r = {}, e = Object.prototype, n = e.hasOwnProperty, o = "function" == typeof Symbol ? Symbol : {}, i = o.iterator || "@@iterator", a = o.asyncIterator || "@@asyncIterator", u = o.toStringTag || "@@toStringTag"; function c(t, r, e, n) { return Object.defineProperty(t, r, { value: e, enumerable: !n, configurable: !n, writable: !n }); } try { c({}, ""); } catch (t) { c = function c(t, r, e) { return t[r] = e; }; } function h(r, e, n, o) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype); return c(a, "_invoke", function (r, e, n) { var o = 1; return function (i, a) { if (3 === o) throw Error("Generator is already running"); if (4 === o) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var u = n.delegate; if (u) { var c = d(u, n); if (c) { if (c === f) continue; return c; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (1 === o) throw o = 4, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = 3; var h = s(r, e, n); if ("normal" === h.type) { if (o = n.done ? 4 : 2, h.arg === f) continue; return { value: h.arg, done: n.done }; } "throw" === h.type && (o = 4, n.method = "throw", n.arg = h.arg); } }; }(r, n, new Context(o || [])), !0), a; } function s(t, r, e) { try { return { type: "normal", arg: t.call(r, e) }; } catch (t) { return { type: "throw", arg: t }; } } r.wrap = h; var f = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var l = {}; c(l, i, function () { return this; }); var p = Object.getPrototypeOf, y = p && p(p(x([]))); y && y !== e && n.call(y, i) && (l = y); var v = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(l); function g(t) { ["next", "throw", "return"].forEach(function (r) { c(t, r, function (t) { return this._invoke(r, t); }); }); } function AsyncIterator(t, r) { function e(o, i, a, u) { var c = s(t[o], t, i); if ("throw" !== c.type) { var h = c.arg, f = h.value; return f && "object" == _typeof(f) && n.call(f, "__await") ? r.resolve(f.__await).then(function (t) { e("next", t, a, u); }, function (t) { e("throw", t, a, u); }) : r.resolve(f).then(function (t) { h.value = t, a(h); }, function (t) { return e("throw", t, a, u); }); } u(c.arg); } var o; c(this, "_invoke", function (t, n) { function i() { return new r(function (r, o) { e(t, n, r, o); }); } return o = o ? o.then(i, i) : i(); }, !0); } function d(r, e) { var n = e.method, o = r.i[n]; if (o === t) return e.delegate = null, "throw" === n && r.i["return"] && (e.method = "return", e.arg = t, d(r, e), "throw" === e.method) || "return" !== n && (e.method = "throw", e.arg = new TypeError("The iterator does not provide a '" + n + "' method")), f; var i = s(o, r.i, e.arg); if ("throw" === i.type) return e.method = "throw", e.arg = i.arg, e.delegate = null, f; var a = i.arg; return a ? a.done ? (e[r.r] = a.value, e.next = r.n, "return" !== e.method && (e.method = "next", e.arg = t), e.delegate = null, f) : a : (e.method = "throw", e.arg = new TypeError("iterator result is not an object"), e.delegate = null, f); } function w(t) { this.tryEntries.push(t); } function m(r) { var e = r[4] || {}; e.type = "normal", e.arg = t, r[4] = e; } function Context(t) { this.tryEntries = [[-1]], t.forEach(w, this), this.reset(!0); } function x(r) { if (null != r) { var e = r[i]; if (e) return e.call(r); if ("function" == typeof r.next) return r; if (!isNaN(r.length)) { var o = -1, a = function e() { for (; ++o < r.length;) if (n.call(r, o)) return e.value = r[o], e.done = !1, e; return e.value = t, e.done = !0, e; }; return a.next = a; } } throw new TypeError(_typeof(r) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, c(v, "constructor", GeneratorFunctionPrototype), c(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = c(GeneratorFunctionPrototype, u, "GeneratorFunction"), r.isGeneratorFunction = function (t) { var r = "function" == typeof t && t.constructor; return !!r && (r === GeneratorFunction || "GeneratorFunction" === (r.displayName || r.name)); }, r.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, c(t, u, "GeneratorFunction")), t.prototype = Object.create(v), t; }, r.awrap = function (t) { return { __await: t }; }, g(AsyncIterator.prototype), c(AsyncIterator.prototype, a, function () { return this; }), r.AsyncIterator = AsyncIterator, r.async = function (t, e, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(h(t, e, n, o), i); return r.isGeneratorFunction(e) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, g(v), c(v, u, "Generator"), c(v, i, function () { return this; }), c(v, "toString", function () { return "[object Generator]"; }), r.keys = function (t) { var r = Object(t), e = []; for (var n in r) e.unshift(n); return function t() { for (; e.length;) if ((n = e.pop()) in r) return t.value = n, t.done = !1, t; return t.done = !0, t; }; }, r.values = x, Context.prototype = { constructor: Context, reset: function reset(r) { if (this.prev = this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(m), !r) for (var e in this) "t" === e.charAt(0) && n.call(this, e) && !isNaN(+e.slice(1)) && (this[e] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0][4]; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(r) { if (this.done) throw r; var e = this; function n(t) { a.type = "throw", a.arg = r, e.next = t; } for (var o = e.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i[4], u = this.prev, c = i[1], h = i[2]; if (-1 === i[0]) return n("end"), !1; if (!c && !h) throw Error("try statement without catch or finally"); if (null != i[0] && i[0] <= u) { if (u < c) return this.method = "next", this.arg = t, n(c), !0; if (u < h) return n(h), !1; } } }, abrupt: function abrupt(t, r) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var n = this.tryEntries[e]; if (n[0] > -1 && n[0] <= this.prev && this.prev < n[2]) { var o = n; break; } } o && ("break" === t || "continue" === t) && o[0] <= r && r <= o[2] && (o = null); var i = o ? o[4] : {}; return i.type = t, i.arg = r, o ? (this.method = "next", this.next = o[2], f) : this.complete(i); }, complete: function complete(t, r) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && r && (this.next = r), f; }, finish: function finish(t) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var e = this.tryEntries[r]; if (e[2] === t) return this.complete(e[4], e[3]), m(e), f; } }, "catch": function _catch(t) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var e = this.tryEntries[r]; if (e[0] === t) { var n = e[4]; if ("throw" === n.type) { var o = n.arg; m(e); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(r, e, n) { return this.delegate = { i: x(r), r: e, n: n }, "next" === this.method && (this.arg = t), f; } }, r; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
var BN_MILLION = exports.BN_MILLION = new _anchor.BN(1000000);
var BN_LAMPORTS_PER_SOL = exports.BN_LAMPORTS_PER_SOL = new _anchor.BN(1000000000);
var connection = exports.connection = function connection(rpc) {
return new _web.Connection(rpc, 'confirmed');
};
// export const updateProgramProvider = (keypair: anchor.web3.Keypair, rpc: string) => {
// const _connection = connection(rpc) as Connection;
// const newProvider = new anchor.AnchorProvider(
// _connection,
// {
// publicKey: keypair.publicKey,
// signTransaction: async (tx) => {
// if ('partialSign' in tx) {
// tx.partialSign(keypair);
// } else {
// tx.sign([keypair]);
// }
// return tx;
// },
// signAllTransactions: async (txs) => {
// txs.forEach(tx => {
// if ('partialSign' in tx) {
// tx.partialSign(keypair);
// } else {
// tx.sign([keypair]);
// }
// });
// return txs;
// },
// },
// { commitment: 'confirmed' }
// );
// return {
// provider: newProvider,
// program: new anchor.Program<FairMintToken>(idl, newProvider),
// }
// };
// export const program = new anchor.Program<FairMintToken>(idl, provider);
var mintAccount = exports.mintAccount = function mintAccount(program, tokenName, tokenSymbol) {
return _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.MINT_SEED), _buffer.Buffer.from(tokenName), _buffer.Buffer.from(tokenSymbol.toLowerCase())], program.programId)[0];
};
var configAccount = exports.configAccount = function configAccount(program, mintAccount) {
return _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.CONFIG_DATA_SEED), mintAccount.toBuffer()], program.programId)[0];
};
var systemConfigAccount = exports.systemConfigAccount = function systemConfigAccount(program, systemMangerAccount) {
return _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.SYSTEM_CONFIG_SEEDS), systemMangerAccount.toBuffer()], program.programId)[0];
};
var referralAccount = exports.referralAccount = function referralAccount(program, mintAccount, refAccount) {
return _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.REFERRAL_SEED), mintAccount.toBuffer(), refAccount.toBuffer()], program.programId)[0];
};
var getReferrerCodeHash = exports.getReferrerCodeHash = function getReferrerCodeHash(program, code) {
return _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.REFERRAL_CODE_SEED), _buffer.Buffer.from(code)], program.programId)[0];
};
var refundAccountPda = exports.refundAccountPda = function refundAccountPda(program, mintAccount, userAccount) {
return _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.REFUND_SEEDS), new _web.PublicKey(mintAccount).toBuffer(), userAccount.toBuffer()], program.programId)[0];
};
var getReferralDataByCodeHash = exports.getReferralDataByCodeHash = /*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(rpc, program, codeHash) {
var _PublicKey$findProgra, _PublicKey$findProgra2, codeAccountPda, connection, codeAccountInfo, codeAccountData, referralAccountPda, referralAccountInfo, referralAccountData;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_PublicKey$findProgra = _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.CODE_ACCOUNT_SEEDS), codeHash.toBuffer()], program.programId), _PublicKey$findProgra2 = _slicedToArray(_PublicKey$findProgra, 1), codeAccountPda = _PublicKey$findProgra2[0];
connection = new _web.Connection(rpc, "confirmed");
_context.next = 4;
return connection.getAccountInfo(codeAccountPda);
case 4:
codeAccountInfo = _context.sent;
if (codeAccountInfo) {
_context.next = 7;
break;
}
return _context.abrupt("return", {
success: false,
message: 'Code account does not exist'
});
case 7:
_context.next = 9;
return program.account.codeAccountData.fetch(codeAccountPda);
case 9:
codeAccountData = _context.sent;
referralAccountPda = codeAccountData.referralAccount;
_context.next = 13;
return connection.getAccountInfo(referralAccountPda);
case 13:
referralAccountInfo = _context.sent;
if (referralAccountInfo) {
_context.next = 16;
break;
}
return _context.abrupt("return", {
success: false,
message: 'Referral account does not exist'
});
case 16:
_context.next = 18;
return program.account.tokenReferralData.fetch(referralAccountPda);
case 18:
referralAccountData = _context.sent;
return _context.abrupt("return", {
success: true,
data: _objectSpread(_objectSpread({}, referralAccountData), {}, {
referralAccount: referralAccountPda
})
});
case 20:
case "end":
return _context.stop();
}
}, _callee);
}));
return function getReferralDataByCodeHash(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}();
var getTokenBalance = exports.getTokenBalance = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ata, connection) {
var account;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return connection.getTokenAccountBalance(ata);
case 2:
account = _context2.sent;
return _context2.abrupt("return", account.value.uiAmount);
case 4:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function getTokenBalance(_x4, _x5) {
return _ref2.apply(this, arguments);
};
}();
var getSystemConfig = exports.getSystemConfig = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(program, network) {
var _PublicKey$findProgra3, _PublicKey$findProgra4, systemConfigAccountPda, systemConfigData;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
_PublicKey$findProgra3 = _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.SYSTEM_CONFIG_SEEDS), new _web.PublicKey(_config.NETWORK_CONFIGS[network].systemDeployer).toBuffer()], program.programId), _PublicKey$findProgra4 = _slicedToArray(_PublicKey$findProgra3, 1), systemConfigAccountPda = _PublicKey$findProgra4[0];
_context3.next = 4;
return program.account.systemConfigData.fetch(systemConfigAccountPda);
case 4:
systemConfigData = _context3.sent;
return _context3.abrupt("return", {
success: true,
data: {
systemConfigData: systemConfigData,
systemConfigAccountPda: systemConfigAccountPda
}
});
case 8:
_context3.prev = 8;
_context3.t0 = _context3["catch"](0);
console.log(_context3.t0);
return _context3.abrupt("return", {
success: false,
message: 'Error getting system config'
});
case 12:
case "end":
return _context3.stop();
}
}, _callee3, null, [[0, 8]]);
}));
return function getSystemConfig(_x6, _x7) {
return _ref3.apply(this, arguments);
};
}();
function getFeeValue(feeRate, difficultyCoefficient, referrerAtaBalance, totalSupply) {
// For special processing in BN, we scale by 1000000
var SCALE = BN_MILLION; // new BN(1000000);
// Calculate balance ratio with scale
var balanceRatioScaled = totalSupply.gt(new _anchor.BN(0)) ? referrerAtaBalance.mul(SCALE).div(totalSupply) : new _anchor.BN(0);
var balanceRatio = balanceRatioScaled.toNumber() / SCALE.toNumber();
// Determine discount rate and convert to scaled BN
var discountRateScaled;
if (balanceRatio >= 0.01) {
discountRateScaled = new _anchor.BN(250000); // 0.25 * SCALE
} else if (balanceRatio >= 0.008) {
discountRateScaled = new _anchor.BN(200000); // 0.20 * SCALE
} else if (balanceRatio >= 0.006) {
discountRateScaled = new _anchor.BN(150000); // 0.15 * SCALE
} else if (balanceRatio >= 0.004) {
discountRateScaled = new _anchor.BN(100000); // 0.10 * SCALE
} else if (balanceRatio >= 0.002) {
discountRateScaled = new _anchor.BN(50000); // 0.05 * SCALE
} else {
discountRateScaled = new _anchor.BN(0);
}
// const discountRate = discountRateScaled.toNumber() / SCALE.toNumber();
// Convert difficultyCoefficient to scaled BN
var difficultyScaled = new _anchor.BN(Math.floor(difficultyCoefficient * SCALE.toNumber()));
// Calculate fee: feeRate * (1 + discountRate/difficultyCoefficient - discountRate)
var one = SCALE;
var discountByDifficulty = discountRateScaled.mul(SCALE).div(difficultyScaled);
var scaledMultiplier = one.add(discountByDifficulty).sub(discountRateScaled);
var fee = feeRate.mul(scaledMultiplier).div(SCALE);
// console.log(
// "fee:",
// `${1} + ${discountRate} / ${difficultyCoefficient} - ${discountRate} = ${fee.toString()}`
// );
// Calculate code sharer reward: 0.2 * feeRate * discountRate * (1 - 1/difficultyCoefficient)
var rewardBase = new _anchor.BN(200000); // 0.2 * SCALE
var difficultyFactor = SCALE.sub(SCALE.mul(SCALE).div(difficultyScaled));
var rewardMultiplier = rewardBase.mul(discountRateScaled).mul(difficultyFactor);
var codeSharerReward = feeRate.mul(rewardMultiplier).div(SCALE.mul(SCALE).mul(SCALE));
return [fee, codeSharerReward];
}
var numberStringToBN = exports.numberStringToBN = function numberStringToBN(decimalStr) {
return new _anchor.BN(decimalStr.replace(/[,\s]/g, '').split('.')[0] || '0');
};
// Create medatata PDA
var metadataAccountPda = exports.metadataAccountPda = function metadataAccountPda(network, mintAccount) {
return _web.PublicKey.findProgramAddressSync([_buffer.Buffer.from(_config.METADATA_SEED), _config.NETWORK_CONFIGS[network].tokenMetadataProgramId.toBuffer(), mintAccount.toBuffer()], _config.NETWORK_CONFIGS[network].tokenMetadataProgramId)[0];
};
var getSolanaBalance = exports.getSolanaBalance = /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(publicKey, connection) {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return connection.getBalance(publicKey);
case 2:
return _context4.abrupt("return", _context4.sent);
case 3:
case "end":
return _context4.stop();
}
}, _callee4);
}));
return function getSolanaBalance(_x8, _x9) {
return _ref4.apply(this, arguments);
};
}();
var compareMints = exports.compareMints = function compareMints(mintA, mintB) {
var bufferA = mintA.toBuffer();
var bufferB = mintB.toBuffer();
for (var i = 0; i < bufferA.length; i++) {
if (bufferA[i] !== bufferB[i]) {
return bufferA[i] - bufferB[i];
}
}
return 0;
};
function getLegacyTokenMetadata(_x0) {
return _getLegacyTokenMetadata.apply(this, arguments);
}
function _getLegacyTokenMetadata() {
_getLegacyTokenMetadata = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(metadataAccountInfo) {
var data, key, updateAuthority, mint, nameLength, currentPos, name, symbolLength, symbol, uriLength, uri, sellerFeeBasisPoints, hasCreators, creators, creatorsLength, i, creatorAddress, verified, share, hasCollection, collection, collectionKey, _verified, isMutable, result;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
_context9.prev = 0;
if (metadataAccountInfo) {
_context9.next = 3;
break;
}
return _context9.abrupt("return", {
success: false,
message: 'Metadata account not found'
});
case 3:
data = metadataAccountInfo.data; // Parse key (1 byte)
key = data[0]; // Parse update authority (32 bytes)
updateAuthority = new _web.PublicKey(data.slice(1, 33)); // Parse mint (32 bytes)
mint = new _web.PublicKey(data.slice(33, 65)); // Parse name
nameLength = data.readUInt32LE(65);
currentPos = 69;
name = data.slice(currentPos, currentPos + nameLength).toString('utf8');
currentPos += nameLength;
// Parse symbol
symbolLength = data.readUInt32LE(currentPos);
currentPos += 4;
symbol = data.slice(currentPos, currentPos + symbolLength).toString('utf8');
currentPos += symbolLength;
// Parse uri
uriLength = data.readUInt32LE(currentPos);
currentPos += 4;
uri = data.slice(currentPos, currentPos + uriLength).toString('utf8');
currentPos += uriLength;
// Parse seller fee basis points (2 bytes)
sellerFeeBasisPoints = data.readUInt16LE(currentPos);
currentPos += 2;
// Parse creators
hasCreators = data[currentPos];
currentPos += 1;
creators = [];
if (hasCreators) {
creatorsLength = data.readUInt32LE(currentPos);
currentPos += 4;
for (i = 0; i < creatorsLength; i++) {
creatorAddress = new _web.PublicKey(data.slice(currentPos, currentPos + 32));
currentPos += 32;
verified = data[currentPos] === 1;
currentPos += 1;
share = data[currentPos];
currentPos += 1;
creators.push({
address: creatorAddress,
verified: verified,
share: share
});
}
}
// Parse collection
hasCollection = data[currentPos];
currentPos += 1;
collection = null;
if (hasCollection) {
collectionKey = new _web.PublicKey(data.slice(currentPos, currentPos + 32));
currentPos += 32;
_verified = data[currentPos] === 1;
currentPos += 1;
collection = {
key: collectionKey,
verified: _verified
};
}
// Finally, parse isMutable
isMutable = data[currentPos] === 1; // Log the parsed metadata
result = {
key: key,
updateAuthority: updateAuthority.toBase58(),
mint: mint.toBase58(),
data: {
name: name,
symbol: symbol,
uri: uri,
sellerFeeBasisPoints: sellerFeeBasisPoints,
creators: creators.map(function (c) {
return {
address: c.address.toBase58(),
verified: c.verified,
share: c.share
};
})
},
isMutable: isMutable,
collection: collection ? {
key: collection.key.toBase58(),
verified: collection.verified
} : null
};
return _context9.abrupt("return", {
success: true,
data: result
});
case 34:
_context9.prev = 34;
_context9.t0 = _context9["catch"](0);
return _context9.abrupt("return", {
success: false,
message: 'Error fetching metadata: ' + _context9.t0.message
});
case 37:
case "end":
return _context9.stop();
}
}, _callee9, null, [[0, 34]]);
}));
return _getLegacyTokenMetadata.apply(this, arguments);
}
var processVersionedTransaction = exports.processVersionedTransaction = /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(versionedTx, connection, wallet, latestBlockhash) {
var confirmLevel,
signedTx,
serializedTx,
signature,
status,
_args5 = arguments;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
confirmLevel = _args5.length > 4 && _args5[4] !== undefined ? _args5[4] : 'confirmed';
_context5.prev = 1;
versionedTx.message.recentBlockhash = latestBlockhash.blockhash;
_context5.next = 5;
return wallet.signTransaction(versionedTx);
case 5:
signedTx = _context5.sent;
serializedTx = signedTx.serialize();
_context5.next = 9;
return connection.sendRawTransaction(serializedTx, {
skipPreflight: true
});
case 9:
signature = _context5.sent;
_context5.next = 12;
return connection.confirmTransaction({
signature: signature,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
}, confirmLevel);
case 12:
status = _context5.sent;
if (!status.value.err) {
_context5.next = 15;
break;
}
return _context5.abrupt("return", {
success: false,
message: "Mint failed: ".concat(JSON.stringify(status.value.err))
});
case 15:
return _context5.abrupt("return", {
success: true,
message: "Mint succeeded",
data: {
tx: signature
}
});
case 18:
_context5.prev = 18;
_context5.t0 = _context5["catch"](1);
return _context5.abrupt("return", {
success: false,
message: _context5.t0.message
});
case 21:
case "end":
return _context5.stop();
}
}, _callee5, null, [[1, 18]]);
}));
return function processVersionedTransaction(_x1, _x10, _x11, _x12) {
return _ref5.apply(this, arguments);
};
}();
var mintBy = exports.mintBy = /*#__PURE__*/function () {
var _ref6 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(network, program, mintAccount, configAccount, referralAccount, referrerMain, tokenMetadata, codeHash, account, systemConfigAccount, connection, lookupTableAddress, protocolFeeAccount) {
var balance, destinationAta, destinationAtaInfo, destinationWsolAta, destinationWsolInfo, mintTokenVaultAta, tokenVaultAta, referrerAta, refundAccount, referrerAccountInfo, codeHashInReferralAccount, protocolWsolAta, wsolVaultAta, token0Mint, token1Mint, token0Program, token1Program, _ref7, _ref8, _cpSwapProgram, _cpSwapConfigAddress, _createPoolFeeReceive, _getAuthAddress, _getAuthAddress2, authority, _getPoolAddress, _getPoolAddress2, poolAddress, _getPoolLpMintAddress, _getPoolLpMintAddress2, lpMintAddress, _getPoolVaultAddress, _getPoolVaultAddress2, vault0, _getPoolVaultAddress3, _getPoolVaultAddress4, vault1, _getOrcleAccountAddre, _getOrcleAccountAddre2, observationAddress, creatorLpTokenAddress, creatorToken0, creatorToken1, context, remainingAccounts, instructionSetComputerUnitLimit, instructionCreateWSOLAta, instructionCreateTokenAta, accountInfo, lookupTable, ix, latestBlockhash, instructions, versionedTx, _result$data, result;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return getSolanaBalance(account.publicKey, connection);
case 2:
balance = _context6.sent;
if (!(balance == 0)) {
_context6.next = 5;
break;
}
return _context6.abrupt("return", {
success: false,
message: "Balance not enough"
});
case 5:
_context6.next = 7;
return (0, _splToken.getAssociatedTokenAddress)(new _web.PublicKey(mintAccount), account.publicKey, false, _splToken.TOKEN_PROGRAM_ID);
case 7:
destinationAta = _context6.sent;
_context6.next = 10;
return connection.getAccountInfo(destinationAta);
case 10:
destinationAtaInfo = _context6.sent;
destinationWsolAta = (0, _splToken.getAssociatedTokenAddressSync)(_splToken.NATIVE_MINT, account.publicKey, false, _splToken.TOKEN_PROGRAM_ID);
_context6.next = 14;
return connection.getAccountInfo(destinationWsolAta);
case 14:
destinationWsolInfo = _context6.sent;
_context6.next = 17;
return (0, _splToken.getAssociatedTokenAddress)(mintAccount, mintAccount, true, _splToken.TOKEN_PROGRAM_ID);
case 17:
mintTokenVaultAta = _context6.sent;
_context6.next = 20;
return (0, _splToken.getAssociatedTokenAddress)(mintAccount, configAccount, true, _splToken.TOKEN_PROGRAM_ID);
case 20:
tokenVaultAta = _context6.sent;
_context6.next = 23;
return (0, _splToken.getAssociatedTokenAddress)(mintAccount, referrerMain, false, _splToken.TOKEN_PROGRAM_ID);
case 23:
referrerAta = _context6.sent;
refundAccount = refundAccountPda(program, mintAccount, account.publicKey);
_context6.next = 27;
return connection.getAccountInfo(referrerAta);
case 27:
referrerAccountInfo = _context6.sent;
if (!(referrerAccountInfo === null)) {
_context6.next = 30;
break;
}
return _context6.abrupt("return", {
success: false,
message: "Referrer ata not exist"
});
case 30:
_context6.next = 32;
return program.account.tokenReferralData.fetch(referralAccount);
case 32:
codeHashInReferralAccount = _context6.sent;
if (!(codeHashInReferralAccount.codeHash.toBase58() !== codeHash.toBase58())) {
_context6.next = 35;
break;
}
return _context6.abrupt("return", {
success: false,
message: "Code hash not match"
});
case 35:
protocolWsolAta = (0, _splToken.getAssociatedTokenAddressSync)(_splToken.NATIVE_MINT, protocolFeeAccount, _config.NETWORK_CONFIGS[network].allowOwnerOffCurveForProtocolFeeAccount, _splToken.TOKEN_PROGRAM_ID);
_context6.next = 38;
return (0, _splToken.getAssociatedTokenAddress)(_splToken.NATIVE_MINT, configAccount, true, _splToken.TOKEN_PROGRAM_ID);
case 38:
wsolVaultAta = _context6.sent;
token0Mint = mintAccount;
token1Mint = _splToken.NATIVE_MINT;
token0Program = _splToken.TOKEN_PROGRAM_ID;
token1Program = _splToken.TOKEN_PROGRAM_ID;
if (compareMints(token0Mint, token1Mint) > 0) {
_ref7 = [token1Mint, token0Mint];
token0Mint = _ref7[0];
token1Mint = _ref7[1];
_ref8 = [token1Program, token0Program];
token0Program = _ref8[0];
token1Program = _ref8[1];
}
_cpSwapProgram = _config.NETWORK_CONFIGS[network].cpSwapProgram;
_cpSwapConfigAddress = _config.NETWORK_CONFIGS[network].cpSwapConfigAddress;
_createPoolFeeReceive = _config.NETWORK_CONFIGS[network].createPoolFeeReceive;
_getAuthAddress = (0, _pda.getAuthAddress)(_cpSwapProgram), _getAuthAddress2 = _slicedToArray(_getAuthAddress, 1), authority = _getAuthAddress2[0];
_getPoolAddress = (0, _pda.getPoolAddress)(_cpSwapConfigAddress, token0Mint, token1Mint, _cpSwapProgram), _getPoolAddress2 = _slicedToArray(_getPoolAddress, 1), poolAddress = _getPoolAddress2[0];
_getPoolLpMintAddress = (0, _pda.getPoolLpMintAddress)(poolAddress, _cpSwapProgram), _getPoolLpMintAddress2 = _slicedToArray(_getPoolLpMintAddress, 1), lpMintAddress = _getPoolLpMintAddress2[0];
_getPoolVaultAddress = (0, _pda.getPoolVaultAddress)(poolAddress, token0Mint, _cpSwapProgram), _getPoolVaultAddress2 = _slicedToArray(_getPoolVaultAddress, 1), vault0 = _getPoolVaultAddress2[0];
_getPoolVaultAddress3 = (0, _pda.getPoolVaultAddress)(poolAddress, token1Mint, _cpSwapProgram), _getPoolVaultAddress4 = _slicedToArray(_getPoolVaultAddress3, 1), vault1 = _getPoolVaultAddress4[0];
_getOrcleAccountAddre = (0, _pda.getOrcleAccountAddress)(poolAddress, _cpSwapProgram), _getOrcleAccountAddre2 = _slicedToArray(_getOrcleAccountAddre, 1), observationAddress = _getOrcleAccountAddre2[0];
creatorLpTokenAddress = (0, _splToken.getAssociatedTokenAddressSync)(lpMintAddress, account.publicKey, false, _splToken.TOKEN_PROGRAM_ID);
creatorToken0 = (0, _splToken.getAssociatedTokenAddressSync)(token0Mint, account.publicKey, false, token0Program);
creatorToken1 = (0, _splToken.getAssociatedTokenAddressSync)(token1Mint, account.publicKey, false, token1Program);
context = {
mint: mintAccount,
destination: destinationAta,
destinationWsolAta: destinationWsolAta,
refundAccount: refundAccount,
user: account.publicKey,
configAccount: configAccount,
systemConfigAccount: systemConfigAccount,
mintTokenVault: mintTokenVaultAta,
tokenVault: tokenVaultAta,
wsolVault: wsolVaultAta,
wsolMint: _splToken.NATIVE_MINT,
referrerAta: referrerAta,
referrerMain: referrerMain,
referralAccount: referralAccount,
protocolFeeAccount: protocolFeeAccount,
protocolWsolVault: protocolWsolAta,
poolState: poolAddress,
ammConfig: _cpSwapConfigAddress,
cpSwapProgram: _cpSwapProgram,
token0Mint: token0Mint,
token1Mint: token1Mint
}; // =============== Use RemainingAccounts for initializing pool accounts, total 21 accounts ===============
remainingAccounts = [{
pubkey: _cpSwapProgram,
// <- 1
isWritable: false,
isSigner: false
}, {
pubkey: account.publicKey,
// <- 2
isWritable: true,
isSigner: true
}, {
pubkey: _cpSwapConfigAddress,
// <- 3
isWritable: true,
isSigner: false
}, {
pubkey: authority,
// <- 4
isWritable: true,
isSigner: false
}, {
pubkey: poolAddress,
// <- 5
isWritable: true,
isSigner: false
}, {
pubkey: token0Mint,
// <- 6
isWritable: true,
isSigner: false
}, {
pubkey: token1Mint,
// <- 7
isWritable: true,
isSigner: false
}, {
pubkey: lpMintAddress,
// <- 8
isWritable: true,
isSigner: false
}, {
pubkey: creatorToken0,
// <- 9
isWritable: true,
isSigner: false
}, {
pubkey: creatorToken1,
// <- 10
isWritable: true,
isSigner: false
}, {
pubkey: creatorLpTokenAddress,
// <- 11
isWritable: true,
isSigner: false
}, {
pubkey: vault0,
// <- 12
isWritable: true,
isSigner: false
}, {
pubkey: vault1,
// <- 13
isWritable: true,
isSigner: false
}, {
pubkey: _createPoolFeeReceive,
// <- 14
isWritable: true,
isSigner: false
}, {
pubkey: observationAddress,
// <- 15
isWritable: true,
isSigner: false
}, {
pubkey: _splToken.TOKEN_PROGRAM_ID,
// <- 16
isWritable: true,
isSigner: false
}, {
pubkey: token0Program,
// <- 17
isWritable: true,
isSigner: false
}, {
pubkey: token1Program,
// <- 18
isWritable: true,
isSigner: false
}, {
pubkey: _token.ASSOCIATED_PROGRAM_ID,
// <- 19
isWritable: true,
isSigner: false
}, {
pubkey: _system.SYSTEM_PROGRAM_ID,
// <- 20
isWritable: true,
isSigner: false
}, {
pubkey: _raydiumSdkV.RENT_PROGRAM_ID,
// <- 21
isWritable: true,
isSigner: false
}]; // ===================================================================================
instructionSetComputerUnitLimit = _web.ComputeBudgetProgram.setComputeUnitLimit({
units: 500000
}); // or use --compute-unit-limit 400000 to run solana-test-validator
instructionCreateWSOLAta = (0, _splToken.createAssociatedTokenAccountInstruction)(
// Create WSOL for user if don't has
account.publicKey, destinationWsolAta, account.publicKey, _splToken.NATIVE_MINT, _splToken.TOKEN_PROGRAM_ID);
instructionCreateTokenAta = (0, _splToken.createAssociatedTokenAccountInstruction)(
// Create token for user if don't has
account.publicKey, destinationAta, account.publicKey, new _web.PublicKey(mintAccount), _splToken.TOKEN_PROGRAM_ID); // Create versioned transaction with LUT
_context6.next = 63;
return connection.getAccountInfo(lookupTableAddress);
case 63:
accountInfo = _context6.sent;
lookupTable = new _web.AddressLookupTableAccount({
key: lookupTableAddress,
state: _web.AddressLookupTableAccount.deserialize(accountInfo.data)
});
_context6.next = 67;
return program.methods.mintTokens(tokenMetadata.name, tokenMetadata.symbol, codeHash.toBuffer()).accounts(context).remainingAccounts(remainingAccounts).instruction();
case 67:
ix = _context6.sent;
_context6.next = 70;
return connection.getLatestBlockhash("confirmed");
case 70:
latestBlockhash = _context6.sent;
instructions = [instructionSetComputerUnitLimit];
if (destinationAtaInfo === null) instructions.push(instructionCreateTokenAta);
if (destinationWsolInfo === null) instructions.push(instructionCreateWSOLAta);
instructions.push(ix);
versionedTx = new _web.VersionedTransaction(new _web.TransactionMessage({
payerKey: account.publicKey,
recentBlockhash: latestBlockhash.blockhash,
instructions: instructions
}).compileToV0Message([lookupTable]));
_context6.prev = 76;
_context6.next = 79;
return processVersionedTransaction(versionedTx, connection, account, latestBlockhash, 'confirmed');
case 79:
result = _context6.sent;
if (result.success) {
_context6.next = 82;
break;
}
return _context6.abrupt("return", {
success: false,
message: result.message
});
case 82:
return _context6.abrupt("return", {
success: true,
data: {
publicKey: account.publicKey.toBase58(),
tokenAccount: destinationAta.toBase58(),
wsolAccount: destinationWsolAta.toBase58(),
tx: (_result$data = result.data) === null || _result$data === void 0 ? void 0 : _result$data.tx,
tokenUrl: "".concat(_config.NETWORK_CONFIGS[network].frontendUrl, "/token/").concat(mintAccount.toBase58())
}
});
case 85:
_context6.prev = 85;
_context6.t0 = _context6["catch"](76);
return _context6.abrupt("return", {
success: false,
message: _context6.t0.message
});
case 88:
case "end":
return _context6.stop();
}
}, _callee6, null, [[76, 85]]);
}));
return function mintBy(_x13, _x14, _x15, _x16, _x17, _x18, _x19, _x20, _x21, _x22, _x23, _x24, _x25) {
return _ref6.apply(this, arguments);
};
}();
var cleanMetadata = exports.cleanMetadata = function cleanMetadata(metadata) {
var cleaned = _objectSpread({}, metadata);
for (var key in cleaned) {
if (typeof cleaned[key] === 'string') {
// eslint-disable-next-line no-control-regex
cleaned[key] = cleaned[key].replace(/\u0000/g, '');
}
}
return cleaned;
};
var processTransaction = exports.processTransaction = /*#__PURE__*/function () {
var _ref9 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(tx, connection, wallet, successMessage, extraData) {
var latestBlockhash, processingTx, processingTimestamp, now, signedTx, serializedTx, simulation, txHash, confirmation, _txDetails$meta, txDetails, errorMessage;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
_context7.prev = 0;
_context7.next = 3;
return connection.getLatestBlockhash();
case 3:
latestBlockhash = _context7.sent;
// Get processing tx
processingTx = localStorage.getItem('processing_tx');
processingTimestamp = localStorage.getItem('processing_timestamp');
now = Date.now(); // Check if there is a processing transaction (transaction within 2 seconds is considered as processing)
if (!(processingTx && processingTimestamp && now - parseInt(processingTimestamp) < 2000)) {
_context7.next = 9;
break;
}
return _context7.abrupt("return", {
success: false,
message: 'Previous transaction is still processing. Please wait.'
});
case 9:
// Set transaction parameters
tx.recentBlockhash = latestBlockhash.blockhash;
tx.feePayer = wallet.publicKey;
// Sign and serialize
_context7.next = 13;
return wallet.signTransaction(tx);
case 13:
signedTx = _context7.sent;
serializedTx = signedTx.serialize(); // Simulate the transaction
_context7.next = 17;
return connection.simulateTransaction(signedTx);
case 17:
simulation = _context7.sent;
if (!simulation.value.err) {
_context7.next = 20;
break;
}
return _context7.abrupt("return", {
success: false,
message: "Transaction simulation failed: ".concat(simulation.value.logs)
});
case 20:
// Mark the transaction as processing
localStorage.setItem('processing_tx', 'true');
localStorage.setItem('processing_timestamp', now.toString());
// Send the transaction
_context7.next = 24;
return connection.sendRawTransaction(serializedTx, {
skipPreflight: true
});
case 24:
txHash = _context7.sent;
_context7.next = 27;
return connection.confirmTransaction({
signature: txHash,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
}, 'confirmed');
case 27:
confirmation = _context7.sent;
if (!confirmation.value.err) {
_context7.next = 34;
break;
}
_context7.next = 31;
return connection.getTransaction(txHash, {
commitment: "confirmed",
maxSupportedTransactionVersion: 0
});
case 31:
txDetails = _context7.sent;
errorMessage = (txDetails === null || txDetails === void 0 || (_txDetails$meta = txDetails.meta) === null || _txDetails$meta === void 0 ? void 0 : _txDetails$meta.logMessages) || [];
return _context7.abrupt("return", {
success: false,
message: 'Transaction failed: ' + errorMessage
});
case 34:
return _context7.abrupt("return", {
success: true,
message: successMessage,
data: _objectSpread({
tx: txHash
}, extraData)
});
case 37:
_context7.prev = 37;
_context7.t0 = _context7["catch"](0);
if (!_context7.t0.message.includes('Transaction simulation failed: This transaction has already been processed')) {
_context7.next = 41;
break;
}
return _context7.abrupt("return", {
succe