hadeswap-sdk
Version:
HadeSwap SDK for interacting with protocol
216 lines (215 loc) • 10.8 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.findRuleSetPDA = exports.findTokenRecordPda = exports.getMetaplexMetadata = exports.calculatePricesArray = exports.getSumOfOrdersSeries = exports.deriveXykBaseSpotPriceFromCurrentSpotPrice = exports.calculateNextSpotPrice = exports.enumToAnchorEnum = exports.anchorRawBNsAndPubkeysToNumsAndStrings = exports.getMetaplexMetadataPda = exports.getMetaplexEditionPda = exports.returnAnchorProgram = exports.AUTHORIZATION_RULES_PROGRAM = void 0;
const anchor_1 = require("@project-serum/anchor");
const hadeswap_1 = require("./idl/hadeswap");
const common_1 = require("../common");
const constants_1 = require("./constants");
const types_1 = require("./types");
exports.AUTHORIZATION_RULES_PROGRAM = new anchor_1.web3.PublicKey('auth9SigNpDKz4sJJ1DfCTuZrZNSAgh9sFD3rboVmgg');
const returnAnchorProgram = (programId, connection) => new anchor_1.Program(hadeswap_1.IDL, programId, new anchor_1.AnchorProvider(connection, (0, common_1.createFakeWallet)(), anchor_1.AnchorProvider.defaultOptions()));
exports.returnAnchorProgram = returnAnchorProgram;
const getMetaplexEditionPda = (mintPubkey) => {
const editionPda = anchor_1.utils.publicKey.findProgramAddressSync([
Buffer.from(constants_1.METADATA_PREFIX),
constants_1.METADATA_PROGRAM_PUBKEY.toBuffer(),
new anchor_1.web3.PublicKey(mintPubkey).toBuffer(),
Buffer.from(constants_1.EDITION_PREFIX),
], constants_1.METADATA_PROGRAM_PUBKEY);
return editionPda[0];
};
exports.getMetaplexEditionPda = getMetaplexEditionPda;
const getMetaplexMetadataPda = (mintPubkey) => {
const metaPda = anchor_1.utils.publicKey.findProgramAddressSync([Buffer.from(constants_1.METADATA_PREFIX), constants_1.METADATA_PROGRAM_PUBKEY.toBuffer(), new anchor_1.web3.PublicKey(mintPubkey).toBuffer()], constants_1.METADATA_PROGRAM_PUBKEY);
return metaPda[0];
};
exports.getMetaplexMetadataPda = getMetaplexMetadataPda;
const anchorRawBNsAndPubkeysToNumsAndStrings = (rawAccount) => {
const copyRawAccount = Object.assign({}, rawAccount);
const newAccount = parseRawAccount(rawAccount.account);
return Object.assign(Object.assign({}, newAccount), { publicKey: copyRawAccount.publicKey.toBase58() });
};
exports.anchorRawBNsAndPubkeysToNumsAndStrings = anchorRawBNsAndPubkeysToNumsAndStrings;
const parseRawAccount = (rawAccount) => {
const copyRawAccount = Object.assign({}, rawAccount);
for (let key in copyRawAccount) {
if (copyRawAccount[key] === null || copyRawAccount[key] === undefined)
continue;
if (copyRawAccount[key].toNumber) {
copyRawAccount[key] = copyRawAccount[key].toNumber();
}
if (copyRawAccount[key].toBase58) {
copyRawAccount[key] = copyRawAccount[key].toBase58();
}
if (typeof copyRawAccount[key] === 'object' && Object.keys(copyRawAccount[key]).length === 1) {
copyRawAccount[key] = Object.keys(copyRawAccount[key])[0];
}
else if (typeof copyRawAccount[key] === 'object') {
copyRawAccount[key] = parseRawAccount(copyRawAccount[key]);
}
}
return copyRawAccount;
};
const enumToAnchorEnum = (anyEnum) => ({ [anyEnum]: {} });
exports.enumToAnchorEnum = enumToAnchorEnum;
const calculateNextSpotPrice = ({ orderType, spotPrice, delta, bondingCurveType, counter, }) => {
if (bondingCurveType === types_1.BondingCurveType.Linear) {
let current_price = spotPrice; // 1
const targetCounter = counter + (orderType === types_1.OrderType.Buy ? 1 : -1);
if (targetCounter >= 0) {
// 0
for (let i = 0; i < Math.abs(targetCounter); i++) {
current_price += delta;
}
}
else {
for (let i = 0; i < Math.abs(targetCounter); i++) {
current_price -= delta;
}
}
return current_price;
}
else if (bondingCurveType === types_1.BondingCurveType.Exponential) {
const newCounter = orderType === types_1.OrderType.Buy ? counter + 1 : counter - 1;
let newDelta = newCounter > 0 ? (delta + 1e4) / 1e4 : 1 / ((delta + 1e4) / 1e4);
return spotPrice * Math.pow(newDelta, Math.abs(newCounter));
}
else if (bondingCurveType === types_1.BondingCurveType.XYK) {
// const deltaCorrected = delta - counter;
const nftTokensBalance = delta * spotPrice;
const counterUpdated = orderType === types_1.OrderType.Buy ? counter : counter - 1;
const currentDelta = delta + 1 - counterUpdated;
const diffAmount = (counterUpdated * nftTokensBalance) / currentDelta;
const newNftTokensBalance = nftTokensBalance + diffAmount;
return orderType === types_1.OrderType.Buy
? newNftTokensBalance / (currentDelta - 1)
: newNftTokensBalance / (currentDelta + 1);
}
return 0;
};
exports.calculateNextSpotPrice = calculateNextSpotPrice;
const deriveXykBaseSpotPriceFromCurrentSpotPrice = ({ currentSpotPrice, delta, counter, }) => {
if (delta === 0) {
return currentSpotPrice;
}
const correctedCounter = counter - 1;
const deltaCorrected = delta - correctedCounter;
return (currentSpotPrice * deltaCorrected) / (delta + (correctedCounter * delta) / (deltaCorrected + 1));
};
exports.deriveXykBaseSpotPriceFromCurrentSpotPrice = deriveXykBaseSpotPriceFromCurrentSpotPrice;
// export const deriveXykBaseSpotPriceFromCurrentSpotPrice = ({
// orderType,
// currentSpotPrice,
// delta,
// counter,
// }: {
// orderType: OrderType;
// currentSpotPrice: number;
// delta: number;
// counter: number;
// }) => {
// // const counterUpdated = counter;
// // const currentDelta = delta + 1 - counterUpdated; // const nftTokensBalance = delta * spotPrice;
// // const newNftTokensBalance = currentSpotPrice * (currentDelta - 1);
// //-->
// // const nftTokensBalance = currentSpotPrice / delta;
// // const counterUpdated = counter;
// // const currentDelta = delta + counterUpdated;
// // const diffAmount = (counterUpdated / nftTokensBalance) * currentDelta;
// // const newNftTokensBalance = nftTokensBalance - diffAmount;
// // console.log({ newNftTokensBalance, diffAmount, currentDelta, counterUpdated, nftTokensBalance });
// // return newNftTokensBalance * (currentDelta + 2);
// // -->
// const nftTokensBalance = currentSpotPrice / delta;
// const counterUpdated = orderType === OrderType.Buy ? counter : counter - 1;
// const currentDelta = delta - 1 + counterUpdated;
// const diffAmount = (counterUpdated / nftTokensBalance) * currentDelta;
// const newNftTokensBalance = nftTokensBalance - diffAmount;
// console.log({ newNftTokensBalance, diffAmount, currentDelta, counterUpdated, nftTokensBalance });
// return orderType === OrderType.Buy
// ? newNftTokensBalance * (currentDelta + 1)
// : newNftTokensBalance * (currentDelta - 1);
// };
const getSumOfOrdersSeries = ({ amountOfOrders, orderType, spotPrice, delta, bondingCurveType, counter, }) => {
let series_sum = 0;
let currentSpotPrice = spotPrice;
let newCounter = counter;
for (let i = 0; i < amountOfOrders; i++) {
series_sum += currentSpotPrice;
currentSpotPrice = (0, exports.calculateNextSpotPrice)({
orderType,
spotPrice: currentSpotPrice,
delta,
bondingCurveType,
counter: newCounter,
});
newCounter = orderType === types_1.OrderType.Buy ? newCounter + 1 : newCounter - 1;
}
return series_sum;
};
exports.getSumOfOrdersSeries = getSumOfOrdersSeries;
// if quantity_of_orders == 0 {
// return 0;
// }
// counter = counter.checked_add(1).unwrap();
// let mut starting_spot_price = spot_price; // 1
// let mut next_smallest_buy_order_price = spot_price; //1
// let mut sum: u64 = 0; //1
// for _ in 0..(quantity_of_orders) {
// next_smallest_buy_order_price = BondingCurve::calculate_next_spot_price(
// bonding_type,
// delta,
// starting_spot_price,
// false,
// counter,
// );
// sum = sum.checked_add(next_smallest_buy_order_price).unwrap();
// counter = counter.checked_sub(1).unwrap();
// }
// sum
const calculatePricesArray = ({ starting_spot_price, delta, amount, bondingCurveType, orderType, counter, }) => {
const array = [];
let newCounter = orderType === types_1.OrderType.Sell ? counter + 1 : counter;
for (let i = 0; i < amount; i++) {
const next_price = (0, exports.calculateNextSpotPrice)({
orderType,
delta,
bondingCurveType,
spotPrice: starting_spot_price,
counter: newCounter,
});
array.push(next_price);
newCounter = orderType === types_1.OrderType.Buy ? newCounter + 1 : newCounter - 1;
}
const total = array.reduce((acc, price) => acc + price, 0);
return { array, total };
};
exports.calculatePricesArray = calculatePricesArray;
const getMetaplexMetadata = (mintPubkey) => {
const [metadata] = anchor_1.web3.PublicKey.findProgramAddressSync([Buffer.from(constants_1.METADATA_PREFIX), constants_1.METADATA_PROGRAM_PUBKEY.toBuffer(), mintPubkey.toBuffer()], constants_1.METADATA_PROGRAM_PUBKEY);
return metadata;
};
exports.getMetaplexMetadata = getMetaplexMetadata;
const findTokenRecordPda = (mint, token) => {
return anchor_1.web3.PublicKey.findProgramAddressSync([
Buffer.from(constants_1.METADATA_PREFIX),
constants_1.METADATA_PROGRAM_PUBKEY.toBuffer(),
mint.toBuffer(),
Buffer.from(constants_1.TOKEN_RECORD),
token.toBuffer(),
], constants_1.METADATA_PROGRAM_PUBKEY)[0];
};
exports.findTokenRecordPda = findTokenRecordPda;
const findRuleSetPDA = (payer, name) => __awaiter(void 0, void 0, void 0, function* () {
return (yield anchor_1.web3.PublicKey.findProgramAddress([Buffer.from('rule_set'), payer.toBuffer(), Buffer.from(name)], exports.AUTHORIZATION_RULES_PROGRAM))[0];
});
exports.findRuleSetPDA = findRuleSetPDA;