Skip to content

Commit

Permalink
add simulate order execution tx
Browse files Browse the repository at this point in the history
  • Loading branch information
hubert-de-lalye committed Oct 31, 2024
1 parent 93915f8 commit d748a5e
Show file tree
Hide file tree
Showing 10 changed files with 332 additions and 35 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/publish-sdk.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ jobs:
node-version: "20"
registry-url: "https://registry.npmjs.org/"
always-auth: true
scope: "@gmx"
auth-token: ${{ secrets.NPM_TOKEN }}
cache: "yarn"

Expand Down Expand Up @@ -68,9 +69,7 @@ jobs:
git add package.json
git commit -m "Bump SDK version to $(jq -r .version package.json)"
- run: |
npm login --registry=https://registry.npmjs.org/ --scope=@gmx
npm publish --access public
- run: npm publish --access public
working-directory: ./sdk
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
Expand Down
72 changes: 72 additions & 0 deletions sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,75 @@
```bash
yarn add @gmx/sdk
```

## Usage

```javascript
import { GmxSdk } from "@gmx/sdk";
import { useWallet } from "wagmi";

const sdk = new GmxSdk({
chainId: 42161,
rpcUrl: "https://arb1.arbitrum.io/rpc",
oracleUrl: "https://arbitrum-api.gmxinfra.io",
walletClient: useWallet().walletClient,
});

const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();

sdk.setAccount("0x1234567890abcdef1234567890abcdef12345678");

sdk.positions.getPositions().then((positions) => {
console.log(positions);
});
```

## Documentation

### Read methods

### Markets

- `getMarkets(offset?: number, limit?: number): Promise<Market[]>` - returns a list of markets
- `getMarketsInfo(): Promise<{ marketsInfoData: MarketInfoData[], tokensData: TokenData[] }>` - returns a list of markets info and tokens data
- `getDailyVolumes(): Promise<{market: string; volume: bigint}[]>` - returns markets' daily volume data

### Positions

- `getPositions(): Promise<Position[]>` - returns a list of positions

### Tokens

- `getTokensData(): Promise<TokenData[]>` - returns a list of tokens data

### Orders

- `getOrders(): Promise<Order[]>` - returns a list of orders

### Trades

- `getTradeHistory(p: Parameters): Promise<TradeAction[]>` - returns a list of trades

#### Parameters:

```typescript
forAllAccounts?: boolean;
pageSize: number;
fromTxTimestamp?: number;
toTxTimestamp?: number;
marketsInfoData: MarketsInfoData | undefined;
tokensData: TokensData | undefined;
pageIndex: number;
marketsDirectionsFilter?: MarketFilterLongShortItemData[];
orderEventCombinations?: {
eventName?: TradeActionType;
orderType?: OrderType;
isDepositOrWithdraw?: boolean;
}[];
```

### Write methods

### Orders

- `cancelOrders(orderKeys: string[])` - creates an order
4 changes: 4 additions & 0 deletions sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ export class GmxSdk {
});
}

setAccount(account: Address) {
this.config.account = account;
}

async executeMulticall<T = any>(request: MulticallRequestConfig<any>) {
const multicall = await Multicall.getInstance(this);
const promise: Promise<T> & { request?: MulticallRequestConfig<any> } = multicall?.call(
Expand Down
4 changes: 4 additions & 0 deletions sdk/src/modules/markets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ export class Markets extends Module {
const chainId = this.chainId;
const account = this.account;

if (!account) {
return {};
}

const { marketsAddresses, marketsData } = await this.getMarkets();

return this.sdk
Expand Down
29 changes: 23 additions & 6 deletions sdk/src/modules/orders/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ export class Orders extends Module {
orderTypesFilter?: OrderType[];
marketsDirectionsFilter?: MarketFilterLongShortItemData[];
}) {
if (!this.account) {
return {
count: 0,
ordersInfoData: {},
};
}

const nonSwapRelevantDefinedFiltersLowercased: MarketFilterLongShortItemData[] = marketsDirectionsFilter
.filter((filter) => filter.direction !== "swap" && filter.marketAddress !== "any")
.map((filter) => ({
Expand Down Expand Up @@ -114,7 +121,6 @@ export class Orders extends Module {
return {
count: orders.count,
ordersInfoData,
isLoading: false,
};
}

Expand Down Expand Up @@ -157,6 +163,12 @@ export class Orders extends Module {
indexToken: TokenData;
increaseAmounts: IncreasePositionAmounts;
}) {
const account = this.account;

if (!account) {
throw new Error("Account is not defined");
}

const gasLimits = await this.sdk.getGasLimits();
const gasPrice = await this.sdk.getGasPrice();
const executionFee = await this.sdk.getExecutionFee("increase", {
Expand All @@ -176,7 +188,7 @@ export class Orders extends Module {
isOrderForPositionByData(order, {
isLong,
marketAddress,
account: this.account,
account,
collateralAddress: collateralToken.address,
})
) as PositionOrderInfo[];
Expand All @@ -186,7 +198,7 @@ export class Orders extends Module {
});

const commonSecondaryOrderParams = {
account: this.account,
account,
marketAddress,
swapPath: [],
allowedSlippage,
Expand All @@ -199,7 +211,7 @@ export class Orders extends Module {
return createIncreaseOrderTxn({
sdk: this.sdk,
createIncreaseOrderParams: {
account: this.account,
account,
marketAddress: marketInfo.marketTokenAddress,
initialCollateralAddress: fromToken?.address,
initialCollateralAmount: increaseAmounts.initialCollateralAmount,
Expand Down Expand Up @@ -282,6 +294,11 @@ export class Orders extends Module {
collateralToken: TokenData;
referralCode?: string;
}) {
const account = this.account;
if (!account) {
throw new Error("Account is not defined");
}

const executionFee = await this.sdk.getExecutionFee("decrease", {
decreaseAmounts,
});
Expand All @@ -303,7 +320,7 @@ export class Orders extends Module {
isOrderForPositionByData(order, {
isLong,
marketAddress: marketInfo.marketTokenAddress,
account: this.account,
account,
collateralAddress: collateralToken.address,
})
) as PositionOrderInfo[];
Expand All @@ -313,7 +330,7 @@ export class Orders extends Module {
});

return createDecreaseOrderTxn(this.sdk, {
account: this.sdk.config.account,
account,
marketAddress: marketInfo.marketTokenAddress,
swapPath: [],
initialCollateralDeltaAmount: decreaseAmounts.collateralDeltaAmount,
Expand Down
26 changes: 13 additions & 13 deletions sdk/src/modules/orders/transactions/createDecreaseOrderTxn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { isMarketOrderType } from "utils/orders";
import { convertToContractPrice } from "utils/tokens";
import { applySlippageToMinOut, applySlippageToPrice } from "utils/trade";
import { Abi, encodeFunctionData, zeroAddress, zeroHash } from "viem";
import { simulateExecuteOrder } from "utils/simulateExecuteOrder";

export type DecreaseOrderParams = {
account: string;
Expand Down Expand Up @@ -41,18 +42,18 @@ export async function createDecreaseOrderTxn(sdk: GmxSdk, params: DecreaseOrderP
const ps = Array.isArray(params) ? params : [params];
const orderVaultAddress = getContract(chainId, "OrderVault");
const totalWntAmount = ps.reduce((acc, p) => acc + p.executionFee, 0n);
// const account = ps[0].account;

const encodedPayload = createDecreaseEncodedPayload({
sdk,
orderVaultAddress,
ps,
});

// const simulationEncodedPayload = createDecreaseEncodedPayload({
// sdk,
// orderVaultAddress,
// ps,
// });
const simulationEncodedPayload = createDecreaseEncodedPayload({
sdk,
orderVaultAddress,
ps,
});

await Promise.all(
ps.map(async (p) => {
Expand All @@ -64,13 +65,12 @@ export async function createDecreaseOrderTxn(sdk: GmxSdk, params: DecreaseOrderP
maxPrice: p.triggerPrice,
};
}
// await simulateExecuteTxn(chainId, {
// account,
// primaryPriceOverrides,
// createMulticallPayload: simulationEncodedPayload,
// value: totalWntAmount,
// tokensData: p.tokensData,
// });
await simulateExecuteOrder(sdk, {
primaryPriceOverrides,
createMulticallPayload: simulationEncodedPayload,
value: totalWntAmount,
tokensData: p.tokensData,
});
}
})
);
Expand Down
23 changes: 11 additions & 12 deletions sdk/src/modules/orders/transactions/createIncreaseOrderTxn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ import ExchangeRouter from "abis/ExchangeRouter.json";
import { getContract } from "configs/contracts";
import { convertTokenAddress, NATIVE_TOKEN_ADDRESS } from "configs/tokens";

import type { GmxSdk } from "index";
import concat from "lodash/concat";
import { DecreasePositionSwapType, OrderTxnType, OrderType } from "types/orders";
import { TokenData, TokenPrices, TokensData } from "types/tokens";
import { isMarketOrderType } from "utils/orders";
import { convertToContractPrice } from "utils/tokens";
import { applySlippageToMinOut, applySlippageToPrice } from "utils/trade";
import { Abi, encodeFunctionData, zeroAddress, zeroHash } from "viem";
import { createDecreaseEncodedPayload, DecreaseOrderParams } from "./createDecreaseOrderTxn";
import type { GmxSdk } from "index";
import { createCancelEncodedPayload } from "./cancelOrdersTxn";
import { createDecreaseEncodedPayload, DecreaseOrderParams } from "./createDecreaseOrderTxn";
import { createUpdateEncodedPayload } from "./updateOrderTxn";
import { simulateExecuteOrder } from "utils/simulateExecuteOrder";

export type PriceOverrides = {
[address: string]: TokenPrices | undefined;
Expand Down Expand Up @@ -166,16 +167,14 @@ export async function createIncreaseOrderTxn({
};
}

// if (!p.skipSimulation) {
// await simulateExecuteTxn(chainId, {
// account: p.account,
// tokensData: p.tokensData,
// primaryPriceOverrides,
// createMulticallPayload: simulationEncodedPayload,
// value: totalWntAmount,
// errorTitle: t`Order error.`,
// });
// }
if (!p.skipSimulation) {
await simulateExecuteOrder(sdk, {
tokensData: p.tokensData,
primaryPriceOverrides,
createMulticallPayload: simulationEncodedPayload,
value: totalWntAmount,
});
}

const finalPayload = [...encodedPayload, ...decreaseEncodedPayload, ...cancelEncodedPayload, ...updateEncodedPayload];

Expand Down
4 changes: 4 additions & 0 deletions sdk/src/modules/positions/positions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,10 @@ export class Positions extends Module {
}

private getUiFeeFactorRequest(): Promise<bigint> {
if (!this.account) {
return Promise.resolve(0n);
}

return this.sdk
.executeMulticall({
dataStore: {
Expand Down
2 changes: 1 addition & 1 deletion sdk/src/types/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Token } from "./tokens";

export interface GmxSdkConfig {
chainId: number;
account: string;
account?: string;
oracleUrl: string;
rpcUrl: string;
subgraph: {
Expand Down
Loading

0 comments on commit d748a5e

Please sign in to comment.