@bluefin-exchange/bluefin-v2-client
Version:
The Bluefin client Library allows traders to sign, create, retrieve and listen to orders on Bluefin Exchange.
433 lines • 22.9 kB
JavaScript
"use strict";
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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContractCalls = void 0;
const library_sui_1 = require("@firefly-exchange/library-sui");
const interpolate_1 = __importDefault(require("interpolate"));
const contractErrorHandling_service_1 = require("./contractErrorHandling.service");
const utils_1 = require("../../utils/utils");
const constants_1 = require("../constants");
const v3_1 = require("@firefly-exchange/library-sui/v3");
const spot_1 = require("@firefly-exchange/library-sui/spot");
class ContractCalls {
constructor(signer, deployment, provider, network, is_zkLogin, zkPayload, walletAddress, is_wallet_extension) {
/**
* Withdraws funds from the margin bank contract
* @param amount the amount to withdraw
* @returns ResponseSchema
* */
this.withdrawFromMarginBankContractCall = (amount, sponsor) => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
const tx = yield this.onChainCalls.withdrawFromBank({
amount: (0, library_sui_1.toBigNumberStr)(amount.toString(), 6),
accountAddress: this.walletAddress,
sponsor,
}, this.signer);
if (tx && !this.marginBankId) {
if (sponsor) {
// TODO: fix marginBankId if sponsor
this.marginBankId = library_sui_1.Transaction.getBankAccountID(tx);
}
else {
this.marginBankId = library_sui_1.Transaction.getBankAccountID(tx);
}
}
return tx;
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.withdrawMargin, { amount }));
});
/**
* Withdraws all funds from the margin bank contract
* @returns ResponseSchema
* */
this.withdrawAllFromMarginBankContractCall = () => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
const r = yield this.onChainCalls.withdrawAllMarginFromBank(this.signer, this.walletAddress);
return r;
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.withdrawMargin, { amount: "all" }));
});
/**
* Deposits funds to the margin bank contract
* @param amount the amount to deposit
* @param coinID the coinID to deposit
* @returns ResponseSchema
* */
this.depositToMarginBankContractCall = (amount, coinID, getPublicAddress, sponsor) => __awaiter(this, void 0, void 0, function* () {
try {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
const tx = yield this.onChainCalls.depositToBank({
amount: (0, library_sui_1.toBigNumberStr)(amount.toString(), 6),
coinID,
bankID: this.onChainCalls.getBankID(),
accountAddress: this.walletAddress || getPublicAddress(),
sponsor,
}, this.signer);
if (tx && !this.marginBankId) {
if (sponsor) {
this.marginBankId = library_sui_1.Transaction.getBankAccountID(tx);
}
else {
this.marginBankId = "";
}
}
return tx;
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.depositToBank, { amount }));
}
catch (error) {
(0, utils_1.throwCustomError)({
error,
code: constants_1.Errors.DEPOSIT_TO_BANK_CONTRACT_CALL_FAILED,
});
}
});
/**
* Deposits funds to the margin bank contract
* @param amount the amount to deposit
* @returns ResponseSchema
* */
this.getUSDCHavingBalance = (amount) => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.getUSDCoinHavingBalance({
amount,
address: this.walletAddress,
}, this.signer);
}
catch (error) {
(0, utils_1.throwCustomError)({
error,
code: constants_1.Errors.FAILED_TO_FETCH_USDC_COIN_HAVING_BALANCE,
});
}
});
/**
* Deposits funds to the margin bank contract
* @param walletAddress user wallet address
* @returns ResponseSchema
* */
this.getUSDCCoins = (walletAddress) => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.getUSDCCoins({ address: walletAddress }, this.signer);
}
catch (error) {
(0, utils_1.throwCustomError)({
error,
code: constants_1.Errors.FAILED_TO_FETCH_USDC_COINS,
});
}
});
/**
* Deposits funds to the margin bank contract
* @param sponsor is the tx sponsored or not
* @returns ResponseSchema
* */
this.mergeAllUSDCCOins = (sponsor) => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.mergeAllUsdcCoins(this.onChainCalls.getCoinType(), this.signer, this.walletAddress, sponsor);
}
catch (error) {
(0, utils_1.throwCustomError)({
error,
code: constants_1.Errors.FAILED_TO_MERGE_USDC_COINS,
});
}
});
/**
* adjusts the leverage of the desiered position
* @param leverage the leverage to set
* @param symbol the position's market symbol
* @returns ResponseSchema
* */
this.adjustLeverageContractCall = (leverage, symbol, parentAddress, sponsorTx) => __awaiter(this, void 0, void 0, function* () {
const perpId = this.onChainCalls.getPerpetualID(symbol);
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
return yield this.onChainCalls.adjustLeverage({
leverage,
perpID: perpId,
account: parentAddress || this.walletAddress,
market: symbol,
sponsor: sponsorTx,
}, this.signer);
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.adjustLeverage, { leverage }), sponsorTx);
});
this.adjustLeverageContractCallRawTransaction = (leverage, symbol, parentAddress) => __awaiter(this, void 0, void 0, function* () {
const perpId = this.onChainCalls.getPerpetualID(symbol);
const signedTx = yield this.onChainCalls.signAdjustLeverage({
leverage,
perpID: perpId,
account: parentAddress || this.walletAddress,
market: symbol,
}, this.signer);
return (0, utils_1.combineAndEncode)({
bytes: signedTx.bytes,
signature: signedTx.signature,
});
});
/**
* This method return the signed Transaction for adding/removing the subaccount(s) on chain
* @param account The sub account address
* @param accountsToRemove The array of sub account addresses that need to be removed on-chain (optional param)
* @param subAccountsMapID The id of the chain object that holds subaccounts mapping (optional param)
* @param gasBudget The gas budget to be passed to execute the on-chain transaction (optional param)
* @returns string
* */
this.upsertSubAccountContractCallRawTransaction = (account, accountsToRemove, subAccountsMapID, gasBudget, sponsor) => __awaiter(this, void 0, void 0, function* () {
try {
const signedTx = yield this.onChainCalls.signUpsertSubAccount({
account,
accountsToRemove,
subAccountsMapID,
gasBudget,
sponsor,
}, this.signer);
if (sponsor) {
return signedTx;
}
return (0, utils_1.combineAndEncode)(signedTx);
}
catch (error) {
(0, utils_1.throwCustomError)({
error,
code: constants_1.Errors.SIGN_UPSERT_SUB_ACCOUNT_CONTRACT_CALLED_FAILED,
});
}
});
/**
* closes the desiered position
* @param publicAddress the sub account's public address
* @param status the status to set for sub account true = add, false = remove
* @returns ResponseSchema
* */
this.setSubAccount = (publicAddress, status, sponsor) => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
return yield this.onChainCalls.setSubAccount({
account: publicAddress,
status,
sponsor,
}, this.signer);
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.setSubAccounts, { address: publicAddress, status: status ? "added" : "removed" }));
});
/**
* adjusts the margin of the desiered position
* @param symbol the position's market symbol
* @operationType the operation type to perform (add or remove)
* @amount the amount to add or remove
* @returns Response Schemea
* */
this.adjustMarginContractCall = (symbol, operationType, amount, sponsorTx) => __awaiter(this, void 0, void 0, function* () {
const perpId = this.onChainCalls.getPerpetualID(symbol);
const msg = operationType === library_sui_1.ADJUST_MARGIN.Add
? (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.adjustMarginAdd, { amount })
: (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.adjustMarginRemove, { amount });
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
if (operationType === library_sui_1.ADJUST_MARGIN.Add) {
if (sponsorTx) {
return this.onChainCalls.addMargin({
amount,
perpID: perpId,
market: symbol,
account: this.walletAddress,
sponsor: true,
}, this.signer);
}
return this.onChainCalls.addMargin({
amount,
perpID: perpId,
market: symbol,
account: this.walletAddress,
}, this.signer);
}
if (sponsorTx) {
return this.onChainCalls.removeMargin({
amount,
perpID: perpId,
market: symbol,
account: this.walletAddress,
sponsor: true,
}, this.signer);
}
return this.onChainCalls.removeMargin({
amount,
perpID: perpId,
market: symbol,
account: this.walletAddress,
}, this.signer);
}), msg, sponsorTx);
});
/**
* Get the margin bank balance
* @returns number
* */
this.getMarginBankBalance = () => __awaiter(this, void 0, void 0, function* () {
if (this.marginBankId) {
return (0, library_sui_1.toBaseNumber)((yield this.onChainCalls.getBankAccountDetailsUsingID(this.marginBankId)).balance);
}
return 0;
});
/**
* transfer coins
* @param to recipient wallet address
* @param balance amount to transfer
* @param coin coin to transfer
* @returns Response Schema
* */
this.transferCoins = (to, balance, coin) => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
return yield this.onChainCalls.transferCoins({
to,
balance,
coin,
}, this.signer);
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.transferCoins, { balance, coin, walletAddress: to }));
});
/**
* transfer coins
* @param to recipient wallet address
* @param balance amount to transfer
* @param coinObject
* @param dryRun
* @returns Response Schema
* */
this.transferCoinObjects = (to_1, balance_1, coinObject_1, ...args_1) => __awaiter(this, [to_1, balance_1, coinObject_1, ...args_1], void 0, function* (to, balance, coinObject, dryRun = false) {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
return this.onChainCalls.transferCoinObjects(to, balance, coinObject, this.signer, dryRun);
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.transferCoins, { balance, coinObject, walletAddress: to }));
});
/**
* estimate gas for sui token transfer
* @param to recipient wallet address
* @param balance SUI amount to transfer
* @returns Response Schema
* */
this.estimateGasForSuiTransfer = (to, balance) => __awaiter(this, void 0, void 0, function* () {
return yield this.onChainCalls.estimateGasForSuiTransfer({
to,
balance,
});
});
/**
* esimate gas for USDC token transfer
* @param to recipient wallet address
* @param balance USDC amount to transfer
* @returns Response Schema
* */
this.estimateGasForUsdcTransfer = (to, balance) => __awaiter(this, void 0, void 0, function* () {
return yield this.onChainCalls.estimateGasForUSDCTransfer({
to,
balance,
});
});
/**
* fetch user sui balance
* @param walletAddress wallet address of the user
* @returns string
* */
this.getSUIBalance = (walletAddress) => __awaiter(this, void 0, void 0, function* () {
return yield this.onChainCalls.getUserSuiBalance(walletAddress);
});
this.closeDelistedPositionContractCall = (symbol, args) => __awaiter(this, void 0, void 0, function* () {
const perpId = this.onChainCalls.getPerpetualID(symbol);
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
try {
return this.onChainCalls.closePosition(Object.assign({ perpID: perpId, accountAddress: this.walletAddress || this.signer.toSuiAddress() }, args));
}
catch (error) {
return error;
}
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.closeDelistedPosition, { symbol }));
});
this.closeAllPositionsAndWithdrawMarginPTB = (delistedMarketPositions, args) => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.closeAllPositionsAndWithdrawMarginPTB(delistedMarketPositions, this.walletAddress || this.signer.toSuiAddress(), args);
}
catch (error) {
return error;
}
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.closedDelistedPositionsAndWithdrawMargin, {
amount: "all",
}), args === null || args === void 0 ? void 0 : args.sponsor);
});
this.closeAllPositionsdWithdrawSwapAndDepositToProPTB = (delistedMarketPositions, args) => __awaiter(this, void 0, void 0, function* () {
const successMessage = delistedMarketPositions.length > 0
? (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.closedDelistedPositionsSwapAndDepositToPro, { amount: "all" })
: (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.withdrawAllSwapAndDepositToPro, {
amount: "all",
});
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.closeAllPositionsWithdrawSwapAndDepositToProPTB(delistedMarketPositions, this.spotOnchain, this.proOnchain, this.walletAddress || this.signer.toSuiAddress(), args);
}
catch (error) {
return error;
}
}), successMessage, args === null || args === void 0 ? void 0 : args.sponsor);
});
this.withdrawAllSwapAndDepositToProPTB = (args) => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.withdrawAllSwapAndDepositToProPTB(this.spotOnchain, this.proOnchain, this.walletAddress || this.signer.toSuiAddress(), args);
}
catch (error) {
return error;
}
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.withdrawAllSwapAndDepositToPro, {
amount: "all",
}), args === null || args === void 0 ? void 0 : args.sponsor);
});
this.swapAndDepositToProPTB = (amount, args) => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.swapAndDepositToProPTB(amount, this.spotOnchain, this.proOnchain, this.walletAddress || this.signer.toSuiAddress(), args);
}
catch (error) {
return error;
}
}), (0, interpolate_1.default)(contractErrorHandling_service_1.SuccessMessages.swapAndDepositToPro, { amount }), args === null || args === void 0 ? void 0 : args.sponsor);
});
this.inspectEstimatedWithdrawalAndSwapAmountFrom7k = (delistedUserPositionsSymbols, args) => __awaiter(this, void 0, void 0, function* () {
return (0, contractErrorHandling_service_1.TransformToResponseSchema)(() => __awaiter(this, void 0, void 0, function* () {
try {
return yield this.onChainCalls.inspectWithdrawAllAndGetEstimatedSwapAmount(delistedUserPositionsSymbols, this.spotOnchain, this.walletAddress || this.signer.toSuiAddress(), args);
}
catch (error) {
return error;
}
}), "Inspected estimated withdrawal and swap amount");
});
this.suiClient = provider;
this.signer = signer;
this.signer.toSuiAddress = this.signer.toSuiAddress
? this.signer.toSuiAddress
: // @ts-ignore
() => this.signer.address;
this.walletAddress = walletAddress || signer.toSuiAddress();
this.is_wallet_extension = is_wallet_extension;
this.onChainCalls = new library_sui_1.OnChainCalls(this.signer, deployment, provider, is_zkLogin, zkPayload, walletAddress, is_wallet_extension);
this.network = network;
// setup pro and spot onchain calls
const isProd = (0, utils_1.isMainnet)(this.network);
const networkName = isProd ? "mainnet" : "testnet";
const spotDeploymentConfig = (0, utils_1.getSpotDeploymentConfig)(this.network);
const proDeploymentConfig = (0, utils_1.getProDeploymentConfig)(this.network);
this.spotOnchain = new spot_1.OnChainCalls(this.suiClient, spotDeploymentConfig, {
signer: this.signer,
address: this.walletAddress,
isUIWallet: this.is_wallet_extension,
isZkLogin: is_zkLogin,
zkPayload,
});
this.proOnchain = new v3_1.UserCalls(networkName, this.suiClient, proDeploymentConfig, this.signer, this.walletAddress);
}
}
exports.ContractCalls = ContractCalls;
//# sourceMappingURL=contractService.js.map