Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eng 1867 simulate hxro printtrade settlement tx to parse usdx #291

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/js/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export const TRANSACTION_PRIORITY_FEE_MAP = {
high: 10,
turbo: 100,
};

export const HXRO_COLLATERAL_LOG_INDEX = 7;
12 changes: 12 additions & 0 deletions packages/js/src/plugins/hxroPrintTradeProviderModule/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ import {
UnlockHxroCollateralByRecordInput,
UnlockHxroCollateralByRecordOutput,
modifyHxroConfigOperation,
GetRequiredHxroCollateralForSettlementInput,
GetRequiredHxroCollateralForSettlementOutput,
getRequiredHxroCollateralForSettlementOperation,
} from './operations';
import { HxroPdasClient } from './pdas';
import { OperationOptions } from '@/types';
Expand Down Expand Up @@ -94,4 +97,13 @@ export class HxroClient {
.operations()
.execute(unlockHxroCollateralByRecordOperation(input), options);
}

getRequiredCollateralForSettlement(
input: GetRequiredHxroCollateralForSettlementInput,
options?: OperationOptions
): Promise<GetRequiredHxroCollateralForSettlementOutput> {
return this.cvg
.operations()
.execute(getRequiredHxroCollateralForSettlementOperation(input), options);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { VersionedTransaction, TransactionMessage } from '@solana/web3.js';

import { Convergence } from '../../../Convergence';
import {
Operation,
OperationHandler,
OperationScope,
useOperation,
} from '../../../types';
import { lockHxroCollateralBuilder } from './lockHxroCollateral';
import {
PrintTradeResponse,
PrintTradeRfq,
getAuthoritySide,
} from '@/plugins/rfqModule';
import { HXRO_COLLATERAL_LOG_INDEX } from '@/constants';

const Key = 'GetRequiredHxroCollateralForSettlementOperation' as const;

/**
* @group Operations
* @category Constructors
*/
export const getRequiredHxroCollateralForSettlementOperation =
useOperation<GetRequiredHxroCollateralForSettlementOperation>(Key);

/**
* @group Operations
* @category Types
*/
export type GetRequiredHxroCollateralForSettlementOperation = Operation<
typeof Key,
GetRequiredHxroCollateralForSettlementInput,
GetRequiredHxroCollateralForSettlementOutput
>;

/**
* @group Operations
* @category Inputs
*/
export type GetRequiredHxroCollateralForSettlementInput = {
/** Rfq Account. */
rfq: PrintTradeRfq;
/** The response to prepare settlement for. */
response: PrintTradeResponse;
};

/**
* @group Operations
* @category Outputs
*/
export type GetRequiredHxroCollateralForSettlementOutput = {
remainingCollateral: number;
};

/**
* @group Operations
* @category Handlers
*/
export const getRequiredHxroCollateralForSettlementOperationHandler: OperationHandler<GetRequiredHxroCollateralForSettlementOperation> =
{
handle: async (
operation: GetRequiredHxroCollateralForSettlementOperation,
convergence: Convergence,
scope: OperationScope
): Promise<GetRequiredHxroCollateralForSettlementOutput> => {
const payer = convergence.identity().publicKey;
const { rfq: rfqModel, response: responseModel } = operation.input;
const { printTrade } = operation.input.rfq;

const caller = convergence.identity();
const side = getAuthoritySide(caller.publicKey, rfqModel, responseModel);
if (!side) {
throw new Error('caller is not authorized to prepare settlement');
}
const hxroContext = await printTrade.getHxroContextHelper(
convergence,
operation.input.response,
side
);
const txBuilder = await lockHxroCollateralBuilder(
convergence,
{
hxroContext,
rfq: operation.input.rfq,
response: operation.input.response,
side,
},
scope
);

const remainingCollateral = 0;

const lastValidBlockHeight = await convergence.rpc().getLatestBlockhash();
const ixs = txBuilder.getInstructions();
const txMessage = new TransactionMessage({
payerKey: payer,
recentBlockhash: lastValidBlockHeight.blockhash,
instructions: ixs,
}).compileToV0Message();

const tx = new VersionedTransaction(txMessage);
const simulateTxResult = await convergence.connection.simulateTransaction(
tx,
{
sigVerify: false,
}
);

if (simulateTxResult.value.err) {
const { logs } = simulateTxResult.value;
if (!logs) {
return { remainingCollateral: 0 };
}
const logToParse = logs[HXRO_COLLATERAL_LOG_INDEX];
const logsSplit = logToParse.split(',');
let totalVariance = Number(logsSplit[0].split(':')[2]);
let openOrdersVariance = Number(logsSplit[1].split(':')[1]);
let positionalValue = Number(logsSplit[2].split(':')[1]);

if (totalVariance < 0 || isNaN(totalVariance)) {
totalVariance = 0;
}
if (openOrdersVariance < 0 || isNaN(openOrdersVariance)) {
openOrdersVariance = 0;
}
if (positionalValue < 0 || isNaN(positionalValue)) {
positionalValue = 0;
}

const remainingCollateralReq =
(Math.sqrt(positionalValue) + Math.sqrt(openOrdersVariance)) * 1.5;
return { remainingCollateral: remainingCollateralReq };
}
scope.throwIfCanceled();
return { remainingCollateral };
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export * from './lockHxroCollateral';
export * from './signHxroPrintTrade';
export * from './fetchUnusedCollateralLockRecords';
export * from './unlockHxroCollateralByRecord';
export * from './getHxroCollateralForSettlement';
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
modifyHxroConfigOperationHandler,
unlockHxroCollateralByRecordOperation,
unlockHxroCollateralByRecordOperationHandler,
getRequiredHxroCollateralForSettlementOperation,
getRequiredHxroCollateralForSettlementOperationHandler,
} from './operations';
import { hxroPrintTradeProviderProgram } from './program';
import { HxroPrintTradeParser } from './printTrade';
Expand Down Expand Up @@ -56,6 +58,11 @@ export const hxroModule = (): ConvergencePlugin => ({
unlockHxroCollateralByRecordOperationHandler
);

op.register(
getRequiredHxroCollateralForSettlementOperation,
getRequiredHxroCollateralForSettlementOperationHandler
);

convergence.hxro = function () {
return new HxroClient(this);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,13 @@ export class HxroPrintTrade implements PrintTrade {
public takerTrg: PublicKey,
protected legsInfo: HxroLegInput[]
) {}

getHxroContextHelper = async (
cvg: Convergence,
response: PrintTradeResponse,
firstToPrepare: AuthoritySide
) => {
return HxroContextHelper.create(cvg, this, response, firstToPrepare);
};
getPrintTradeProviderProgramId = () =>
this.cvg.programs().getHxroPrintTradeProvider().address;
getLegs = () => this.legsInfo.map((legInfo) => new HxroLeg(legInfo));
Expand Down
6 changes: 6 additions & 0 deletions packages/js/src/plugins/printTradeModule/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
PrintTradeResponse,
PrintTradeRfq,
} from '../rfqModule';
import { HxroContextHelper } from '../hxroPrintTradeProviderModule';
import { Convergence } from '@/Convergence';
import { TransactionBuilder, TransactionBuilderOptions } from '@/utils';

Expand All @@ -25,6 +26,11 @@ export interface PrintTrade {
side: AuthoritySide,
options: TransactionBuilderOptions
) => Promise<{ accounts: AccountMeta[]; builders: TransactionBuilder[] }>;
getHxroContextHelper: (
cvg: Convergence,
response: PrintTradeResponse,
firstToPrepare: AuthoritySide
) => Promise<HxroContextHelper>;
getSettlementAccounts: (
rfq: PrintTradeRfq,
response: PrintTradeResponse
Expand Down
Loading