@gmx-io/sdk 1.6.1 → 1.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +270 -0
- package/build/cjs/src/clients/v2/__tests__/testUtil.js +92 -1
- package/build/cjs/src/clients/v2/index.js +34 -57
- package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +8 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +61 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +15 -0
- package/build/cjs/src/configs/markets.js +11 -1
- package/build/cjs/src/configs/tokens.js +11 -0
- package/build/cjs/src/utils/__tests__/markets.spec.js +30 -0
- package/build/cjs/src/utils/markets/utils.js +16 -12
- package/build/cjs/src/utils/positions/utils.js +1 -0
- package/build/cjs/src/utils/subaccount/index.js +11 -1
- package/build/cjs/src/utils/subaccount/sdkClient.js +367 -0
- package/build/cjs/src/utils/subaccount/state.js +76 -0
- package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +271 -1
- package/build/esm/src/clients/v2/__tests__/testUtil.js +87 -0
- package/build/esm/src/clients/v2/index.js +33 -56
- package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +8 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +61 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +15 -0
- package/build/esm/src/configs/markets.js +10 -0
- package/build/esm/src/configs/tokens.js +11 -0
- package/build/esm/src/utils/__tests__/markets.spec.js +30 -0
- package/build/esm/src/utils/markets/utils.js +16 -12
- package/build/esm/src/utils/positions/utils.js +1 -0
- package/build/esm/src/utils/subaccount/index.js +1 -0
- package/build/esm/src/utils/subaccount/sdkClient.js +352 -0
- package/build/esm/src/utils/subaccount/state.js +64 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/clients/v2/__tests__/testUtil.d.ts +37 -1
- package/build/types/src/clients/v2/index.d.ts +8 -2
- package/build/types/src/codegen/prebuilt/index.d.ts +84 -0
- package/build/types/src/configs/markets.d.ts +1 -0
- package/build/types/src/utils/markets/utils.d.ts +4 -3
- package/build/types/src/utils/subaccount/index.d.ts +1 -0
- package/build/types/src/utils/subaccount/sdkClient.d.ts +36 -0
- package/build/types/src/utils/subaccount/state.d.ts +11 -0
- package/build/types/src/utils/subaccount/types.d.ts +18 -0
- package/build/types/src/utils/tokens/types.d.ts +1 -1
- package/package.json +1 -1
|
@@ -8544,6 +8544,67 @@
|
|
|
8544
8544
|
"virtualLongTokenId": "0xaab37f889b9680dda34f58a689de3023cb22f7ae14d32a3c1d45798a973db1f5",
|
|
8545
8545
|
"virtualShortTokenId": "0xd5258cb84f0039be58306488e8df941c05f3cf4f219e92aacb6561c736bbb960"
|
|
8546
8546
|
},
|
|
8547
|
+
"0x470128853D74dab7423904a20eA5AA230e9e561B": {
|
|
8548
|
+
"isDisabled": "0xfe243a54564541c534d5eeae5e63c2d5db84aa8bd25a4a754408efc202e8d6e5",
|
|
8549
|
+
"maxLongPoolAmount": "0x39205af116753605d966898b83c4ec7df6aeb18e02c8380c9369f5d6bbfff636",
|
|
8550
|
+
"maxShortPoolAmount": "0xe069ff8a01ec920ec3918881607fbf87ee82fac4fe4419588bd04ecb25e86c5f",
|
|
8551
|
+
"maxLongPoolUsdForDeposit": "0x5fed054a389bf855aaf752f849f9aec169c13add29412126eb973982caac30dc",
|
|
8552
|
+
"maxShortPoolUsdForDeposit": "0x9874ece30abf39e18219153b11ae45ee25422096f35af32bdeaec681d6ec1522",
|
|
8553
|
+
"reserveFactorLong": "0x8005b75fdbad97e030d8cd27d3e8bc3fa07cb49500876115217e8bec4e8f210d",
|
|
8554
|
+
"reserveFactorShort": "0xa5140d82a4b20acf9ba665b133a8eb3003b8e9339b94bc4a561530da63ea6cfe",
|
|
8555
|
+
"openInterestReserveFactorLong": "0xade22aa01e5e5f10f593163ab9f956e8c43c01c3406ce610c5dad851032503a0",
|
|
8556
|
+
"openInterestReserveFactorShort": "0x9e51713a0dc904a819b3998da79b49709420b7d1796e7d98345113da92641ba7",
|
|
8557
|
+
"maxOpenInterestLong": "0xdb04bf3c179c1a2b89441879b9e6b198c0e29cf99a1195594fedb171e0f848ca",
|
|
8558
|
+
"maxOpenInterestShort": "0x9546febaa71b4e976ef4cf635076cc14f5dc68a4bfb784bd4ae39cfbdc3b9a75",
|
|
8559
|
+
"minPositionImpactPoolAmount": "0xe4262c3a746be3506435094aa18433081dcce819b6eef64578363b89f8af0018",
|
|
8560
|
+
"positionImpactPoolDistributionRate": "0x0e4c6c4ba31a6e94f6df0ee037f7884d369cc59f05698e2be943843b541b3b2f",
|
|
8561
|
+
"borrowingFactorLong": "0x8d0f57b99783d2c5ad53fe6fdc31bbc29a725f843e247b7a72ff3f79f045596b",
|
|
8562
|
+
"borrowingFactorShort": "0xe6c31c713cf022d3d662f04700861119efa2dea5a1691a3eb4cfdf75c28d1f6d",
|
|
8563
|
+
"borrowingExponentFactorLong": "0x53056a4ac567795f4d9885f20706ee74ec6993440a7b43439e72c02379f3e878",
|
|
8564
|
+
"borrowingExponentFactorShort": "0xa2bdcb3141e0770697a392944e1bd583a3c851e2ba72e59d65b99617b38b4fc0",
|
|
8565
|
+
"fundingFactor": "0x2a86348096e5a76bc46ab7286f3012cc403a4da5a63a5a78ccaa4ec24732fedb",
|
|
8566
|
+
"fundingExponentFactor": "0xd4828665a6d6b9ab81d76dd9d7bf38ed221e2d4bcc6f35a851e42f0f48f98e92",
|
|
8567
|
+
"fundingIncreaseFactorPerSecond": "0x7c35ce6e2417fcf8fa19bc8f6862e395aacd0eb546821f8164d046f9224c7dc1",
|
|
8568
|
+
"fundingDecreaseFactorPerSecond": "0x3d5d433151ae449ca355115a730d52ce1c945e36cb340a408329e0fa6fd677b0",
|
|
8569
|
+
"thresholdForStableFunding": "0x3785587cc950cb348063323c282242b14be9421fc64fdfe79cb8c71de2371289",
|
|
8570
|
+
"thresholdForDecreaseFunding": "0xe535526955c78fed5c4dc454eb1a4b931396e4e4a861461e43ba9ca660175338",
|
|
8571
|
+
"minFundingFactorPerSecond": "0x7d9bd63fb8d9db9345f89da4323130937c15142f30c52cf0c2c3f61965554b8c",
|
|
8572
|
+
"maxFundingFactorPerSecond": "0xc3583272b45beb068172fe8b0c428e9ba5a9d90513d11e2e7f9d3f50c4891175",
|
|
8573
|
+
"maxPnlFactorForTradersLong": "0xfc827e8022bb9470e4b6e80625af561298a89a21349a7f28002227d104aaa340",
|
|
8574
|
+
"maxPnlFactorForTradersShort": "0x72cf2f1f4d28a7a7bc591871fb733976b9b5be06131fba40ea272163ee1b4a5b",
|
|
8575
|
+
"maxPnlFactorForDepositsLong": "0xd605366e5a7ff3abd0d76cf57e1788446fae68b7ed21ab3279c430855414e3e7",
|
|
8576
|
+
"maxPnlFactorForDepositsShort": "0xdba9cc56b9ccfff70ce0f5269915cd4a9e3d467f0fbcd1572f245005cb9d0b00",
|
|
8577
|
+
"maxPnlFactorForWithdrawalsLong": "0x3b0c3e6d816414ad07c367167c68c43c4fed6b1190d72db03807bfa4dfae2911",
|
|
8578
|
+
"maxPnlFactorForWithdrawalsShort": "0x735cc2452ca08e74dd09ff1fa52e7ff6ab35da3e14fc103cc8a43d87395b5976",
|
|
8579
|
+
"positionFeeFactorForBalanceWasImproved": "0x087f8ffb10b80b5ac2140d51a16cf6e3b993673569626d8384d899ca1768fb6e",
|
|
8580
|
+
"positionFeeFactorForBalanceWasNotImproved": "0x93db7fe18681e1033baa91aadd2fbed9c821cdd016c8f0e3b2f79c7873cb9592",
|
|
8581
|
+
"positionImpactFactorPositive": "0x297fa7e7b636003945b564c16070b2659d71a80fd6f74165c5ff7a458a9ddcf5",
|
|
8582
|
+
"positionImpactFactorNegative": "0xd373bf8c89b270fe6b011b4cc5aa9f1cd0efe86f67b4a5640c20c07ebb5866f0",
|
|
8583
|
+
"maxPositionImpactFactorPositive": "0xb95147c91cfefc2b5bc56478bc89acc250c96be349117daf81f3c7163c659cb3",
|
|
8584
|
+
"maxPositionImpactFactorNegative": "0xc050b04300e901112d441469127596785a8cf7504117260dc7f7704a1fa36e06",
|
|
8585
|
+
"maxPositionImpactFactorForLiquidations": "0xf131c7d0f04481d0b47003445bc3343174376c0b885c4128b1e4c1b8fd0ce0fb",
|
|
8586
|
+
"maxLendableImpactFactor": "0x8c4ff7114d4241b28aae17fbb4c399f01e86af274560a212dc383e06e9981f1d",
|
|
8587
|
+
"maxLendableImpactFactorForWithdrawals": "0xef5bfd25b3655d058bea6025948abf09ea95b1b3d3b183880f5dc5c077498a1b",
|
|
8588
|
+
"maxLendableImpactUsd": "0x61a580a5e5382029facb4c776a0335d4034130e87e2f788db8151d89918eeb64",
|
|
8589
|
+
"lentPositionImpactPoolAmount": "0x6553c99fe8bc2a2a2ee509acd790a9075a4d6c1bfc29f84ec1aa88e5def086fb",
|
|
8590
|
+
"minCollateralFactor": "0x708f3743ff03fa69e9aa5d4038c8f2984477e2169f30ef2f145c53ca83e33db7",
|
|
8591
|
+
"minCollateralFactorForLiquidation": "0xe47c118c844f1da524087647c205fdca711510edc9768c00187156fbedcb9a4e",
|
|
8592
|
+
"minCollateralFactorForOpenInterestLong": "0x461b23d60d80970a3d0218cfc4530a7e4a2a2531c792d2c2781a546feebefa03",
|
|
8593
|
+
"minCollateralFactorForOpenInterestShort": "0xf087f5a1e94da17538546bbd6bbd1d7cfc938715d5cfad263c16c7065ee7f2a0",
|
|
8594
|
+
"positionImpactExponentFactorPositive": "0xdab3143b127c611e5bdf62e6eceeb69b795d6b3e643c1fca8e25d0176548c6b4",
|
|
8595
|
+
"positionImpactExponentFactorNegative": "0x2347c2bad621059109cbf2f2d0241ac3a3fa717816e749dc2d8b2e666bff4b57",
|
|
8596
|
+
"swapFeeFactorForBalanceWasImproved": "0x956d64be84e25d83f19a191d3115bd426b554b9d884d075625b1998a440c1ac0",
|
|
8597
|
+
"swapFeeFactorForBalanceWasNotImproved": "0x1dbf423caf962d3c39350ae346b277db997d2c140da420b24c0bebd603477593",
|
|
8598
|
+
"atomicSwapFeeFactor": "0xff91ee6de493812a25d525efa1e67ff47d2df0a0f59fda1f8f805cbff6ad884d",
|
|
8599
|
+
"swapImpactFactorPositive": "0x040389937579e93803e4eef90e2e524d1ea01e6890fcc62058801758d67a549f",
|
|
8600
|
+
"swapImpactFactorNegative": "0x31f9bba4c1cfcde524a5a73add46d38d57f362a36cbd5b216b5bb96d34297e22",
|
|
8601
|
+
"swapImpactExponentFactor": "0xf438467b2ca2e25ad577f3ea39caf610ef21d0ee0f1aa3e633044cc6b9fd8d72",
|
|
8602
|
+
"withdrawalFeeFactorBalanceWasImproved": "0x45a9a93feb42de4392939fff459c0ba3a2513a3f750865ed68e8f118d7c20203",
|
|
8603
|
+
"withdrawalFeeFactorBalanceWasNotImproved": "0xd5fea53fb1348b694edc1fe97f87da9923b847a73874774a9d6236e1a9f989f5",
|
|
8604
|
+
"virtualMarketId": "0xced49eb3d9ebb85529707d3b67a0fd9a3c6a749bbb1934f0888f51b564f11c57",
|
|
8605
|
+
"virtualLongTokenId": "0xaab37f889b9680dda34f58a689de3023cb22f7ae14d32a3c1d45798a973db1f5",
|
|
8606
|
+
"virtualShortTokenId": "0xd5258cb84f0039be58306488e8df941c05f3cf4f219e92aacb6561c736bbb960"
|
|
8607
|
+
},
|
|
8547
8608
|
"0xE26E7b91143f367445f1c0a5dCf4f4aC8EaDcDb1": {
|
|
8548
8609
|
"isDisabled": "0x89d68641baa8443dcff05c06834a08f6a7c1edef759f2e89505fe251b6411cb5",
|
|
8549
8610
|
"maxLongPoolAmount": "0x5c7eb3fb9940700a0eb6d0bc4b2efcec205e4bcd85611f2e63a40fb71b48a68b",
|
|
@@ -2104,6 +2104,21 @@
|
|
|
2104
2104
|
"shortInterestInTokensUsingLongToken": "0xccb072d4c5cf74a4a1d0e6f80b7628dba861d6c95037409fc42800e72a935d7c",
|
|
2105
2105
|
"shortInterestInTokensUsingShortToken": "0x3e1a9a944352a0080a281988fbf04a6b9c44a82767c10d16eb11ad80b1fb5d65"
|
|
2106
2106
|
},
|
|
2107
|
+
"0x470128853D74dab7423904a20eA5AA230e9e561B": {
|
|
2108
|
+
"longPoolAmount": "0x42bb5e8d4ca514798b21267763eeb4d3b35a623bd89689ef66ec1f007087b161",
|
|
2109
|
+
"shortPoolAmount": "0x8158632c1d7b805bbf9edba3e15fde98b5cd4d32ed70009ac3f6224ec47fc5ae",
|
|
2110
|
+
"positionImpactPoolAmount": "0xde24f47762b924ccb93b3434c4dec1224b581cae29eb84def00e25707f0598b3",
|
|
2111
|
+
"swapImpactPoolAmountLong": "0x9cce19aabd82c41d0b6b7df7e456057c78870b31379d4a7b1dab5a4e1c4975ff",
|
|
2112
|
+
"swapImpactPoolAmountShort": "0x1c76620a18e8abb145e352f6d7a618510e4da180beeb764f18294a47ff109ff4",
|
|
2113
|
+
"longInterestUsingLongToken": "0x27c74bd1c225f15925642df8ccae6a49d75cddc7d9365133a54ce3af9898876e",
|
|
2114
|
+
"longInterestUsingShortToken": "0xa2d438ebe99ba84f775d7c2c1c8e40a3aafdde88ed68c9d9b5bdf4fdac544b6e",
|
|
2115
|
+
"shortInterestUsingLongToken": "0x7587ab70dd363bcf4c60377a304b9fe072b73aa131f0d195c4f069e95ba1919d",
|
|
2116
|
+
"shortInterestUsingShortToken": "0xed61a26c939934abf69c8688610fe123ecc1b927522671d4056d0c1fb77feb65",
|
|
2117
|
+
"longInterestInTokensUsingLongToken": "0x892c0dd3d5da401bb0dd0822ca5e5acc861ce6842a3c3500512f89102e419529",
|
|
2118
|
+
"longInterestInTokensUsingShortToken": "0x51d2161b7c40b9f680a8d510dedab14fbc49a3415d1b7fce425ce455b8f44e92",
|
|
2119
|
+
"shortInterestInTokensUsingLongToken": "0x2bdcec38c2d0016c12d50e0ac27709d4856c2d27ffe78e58753e58d3f1ce7570",
|
|
2120
|
+
"shortInterestInTokensUsingShortToken": "0x8695147e4efe6f8ad95dee38bd50f33fb632c55e6119ee65d8716e8bf683dacd"
|
|
2121
|
+
},
|
|
2107
2122
|
"0xE26E7b91143f367445f1c0a5dCf4f4aC8EaDcDb1": {
|
|
2108
2123
|
"longPoolAmount": "0x265452d70a411300a2535b1c9c212a3dcea8eb2793c66aec2fcd595776ba2c0b",
|
|
2109
2124
|
"shortPoolAmount": "0x24f88d54e73a74c9c029fff00404272e44a15d9f931be2df1433f43ef5e5e428",
|
|
@@ -6,6 +6,9 @@ import { zeroAddress } from "viem";
|
|
|
6
6
|
import { ARBITRUM, ARBITRUM_SEPOLIA, AVALANCHE, AVALANCHE_FUJI, BOTANIX, MEGAETH } from "./chains";
|
|
7
7
|
import { convertTokenAddress, getToken, getTokenBySymbol } from "./tokens";
|
|
8
8
|
export const SWAP_GRAPH_MAX_MARKETS_PER_TOKEN = 5;
|
|
9
|
+
export const UI_MAX_LEVERAGE_BY_MARKET = {
|
|
10
|
+
"0x470128853D74dab7423904a20eA5AA230e9e561B": 10,
|
|
11
|
+
};
|
|
9
12
|
/*
|
|
10
13
|
ATTENTION
|
|
11
14
|
When adding new markets, please add them also to the end of the list in ./src/configs/static/sortedMarkets.ts
|
|
@@ -936,6 +939,13 @@ export const MARKETS = {
|
|
|
936
939
|
longTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
937
940
|
shortTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
|
|
938
941
|
},
|
|
942
|
+
// SPCX/USD [WETH-USDC]
|
|
943
|
+
"0x470128853D74dab7423904a20eA5AA230e9e561B": {
|
|
944
|
+
marketTokenAddress: "0x470128853D74dab7423904a20eA5AA230e9e561B",
|
|
945
|
+
indexTokenAddress: "0x8CBd0d5d81e7957123E6D8fFaE657a40bDC5691b",
|
|
946
|
+
longTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
947
|
+
shortTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
|
|
948
|
+
},
|
|
939
949
|
// MEGA/USD [WETH-USDC]
|
|
940
950
|
"0xE26E7b91143f367445f1c0a5dCf4f4aC8EaDcDb1": {
|
|
941
951
|
marketTokenAddress: "0xE26E7b91143f367445f1c0a5dCf4f4aC8EaDcDb1",
|
|
@@ -1237,6 +1237,16 @@ export const TOKENS = {
|
|
|
1237
1237
|
imageUrl: "https://s2.coinmarketcap.com/static/img/coins/64x64/39464.png",
|
|
1238
1238
|
explorerUrl: "https://arbiscan.io/token/0x620aC65BE29066Bb9D1E92C65b35B9fD321Fb963",
|
|
1239
1239
|
},
|
|
1240
|
+
{
|
|
1241
|
+
name: "SpaceX",
|
|
1242
|
+
symbol: "SPCX",
|
|
1243
|
+
address: "0x8CBd0d5d81e7957123E6D8fFaE657a40bDC5691b",
|
|
1244
|
+
isSynthetic: true,
|
|
1245
|
+
decimals: 18,
|
|
1246
|
+
categories: ["tradfi", "pre-ipo"],
|
|
1247
|
+
searchAliases: ["Space", "X"],
|
|
1248
|
+
explorerUrl: "https://arbiscan.io/token/0x8CBd0d5d81e7957123E6D8fFaE657a40bDC5691b",
|
|
1249
|
+
},
|
|
1240
1250
|
{
|
|
1241
1251
|
name: "MegaETH",
|
|
1242
1252
|
symbol: "MEGA",
|
|
@@ -2083,6 +2093,7 @@ export const TOKEN_COLOR_MAP = {
|
|
|
2083
2093
|
XAG: "#ADABB8",
|
|
2084
2094
|
GOLD: "#D69A00",
|
|
2085
2095
|
SILVER: "#ADABB8",
|
|
2096
|
+
SPCX: "#1A1E21",
|
|
2086
2097
|
XPT: "#C2B8AB",
|
|
2087
2098
|
XPD: "#A9ACB6",
|
|
2088
2099
|
default: "#6062a6",
|
|
@@ -138,6 +138,12 @@ describe("getMaxLeverageByMinCollateralFactor", () => {
|
|
|
138
138
|
it("returns correct leverage for a given factor", () => {
|
|
139
139
|
expect(getMaxLeverageByMinCollateralFactor(1000000000000000000n)).toBe(10000000000000000);
|
|
140
140
|
});
|
|
141
|
+
it("caps SPCX min-collateral-factor leverage at 10x", () => {
|
|
142
|
+
expect(getMaxLeverageByMinCollateralFactor(1000000000000000000n, "0x470128853D74dab7423904a20eA5AA230e9e561B")).toBe(100000);
|
|
143
|
+
});
|
|
144
|
+
it("caps SPCX default min-collateral-factor leverage at 10x", () => {
|
|
145
|
+
expect(getMaxLeverageByMinCollateralFactor(undefined, "0x470128853D74dab7423904a20eA5AA230e9e561B")).toBe(100000);
|
|
146
|
+
});
|
|
141
147
|
});
|
|
142
148
|
describe("getMaxAllowedLeverage", () => {
|
|
143
149
|
// Factors are expressed in PRECISION units (1e30 == 100%).
|
|
@@ -228,6 +234,30 @@ describe("getMaxAllowedLeverage", () => {
|
|
|
228
234
|
positionFeeFactorForBalanceWasNotImproved: pct(0.05),
|
|
229
235
|
})).toBe(bps(25));
|
|
230
236
|
});
|
|
237
|
+
it("caps SPCX UI max leverage at 10x", () => {
|
|
238
|
+
expect(getMaxAllowedLeverage({
|
|
239
|
+
marketAddress: "0x470128853D74dab7423904a20eA5AA230e9e561B",
|
|
240
|
+
minCollateralFactor: pct(0.5),
|
|
241
|
+
minCollateralFactorForLiquidation: pct(0.5),
|
|
242
|
+
positionFeeFactorForBalanceWasNotImproved: pct(0.05),
|
|
243
|
+
})).toBe(bps(10));
|
|
244
|
+
});
|
|
245
|
+
it("does not cap other markets with matching factors", () => {
|
|
246
|
+
expect(getMaxAllowedLeverage({
|
|
247
|
+
marketAddress: "0x0000000000000000000000000000000000000000",
|
|
248
|
+
minCollateralFactor: pct(0.5),
|
|
249
|
+
minCollateralFactorForLiquidation: pct(0.5),
|
|
250
|
+
positionFeeFactorForBalanceWasNotImproved: pct(0.05),
|
|
251
|
+
})).toBe(bps(100));
|
|
252
|
+
});
|
|
253
|
+
it("keeps lower dynamic max leverage for SPCX when factors require it", () => {
|
|
254
|
+
expect(getMaxAllowedLeverage({
|
|
255
|
+
marketAddress: "0x470128853D74dab7423904a20eA5AA230e9e561B",
|
|
256
|
+
minCollateralFactor: pct(10),
|
|
257
|
+
minCollateralFactorForLiquidation: pct(10),
|
|
258
|
+
positionFeeFactorForBalanceWasNotImproved: pct(0.05),
|
|
259
|
+
})).toBe(bps(5));
|
|
260
|
+
});
|
|
231
261
|
});
|
|
232
262
|
describe("getOppositeCollateral", () => {
|
|
233
263
|
const marketInfo = {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { zeroAddress } from "viem";
|
|
2
2
|
import { BASIS_POINTS_DIVISOR, BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
|
|
3
|
+
import { UI_MAX_LEVERAGE_BY_MARKET } from "../../configs/markets";
|
|
3
4
|
import { convertTokenAddress, getTokenVisualMultiplier, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
|
|
4
5
|
import { bigMath } from "../bigmath";
|
|
5
6
|
import { getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
|
|
@@ -51,12 +52,10 @@ export function getTokenPoolType(marketInfo, tokenAddress) {
|
|
|
51
52
|
if (longToken.address === shortToken.address && tokenAddress === longToken.address) {
|
|
52
53
|
return "long";
|
|
53
54
|
}
|
|
54
|
-
if (tokenAddress === longToken.address ||
|
|
55
|
-
(tokenAddress === NATIVE_TOKEN_ADDRESS && longToken.isWrapped)) {
|
|
55
|
+
if (tokenAddress === longToken.address || (tokenAddress === NATIVE_TOKEN_ADDRESS && longToken.isWrapped)) {
|
|
56
56
|
return "long";
|
|
57
57
|
}
|
|
58
|
-
if (tokenAddress === shortToken.address ||
|
|
59
|
-
(tokenAddress === NATIVE_TOKEN_ADDRESS && shortToken.isWrapped)) {
|
|
58
|
+
if (tokenAddress === shortToken.address || (tokenAddress === NATIVE_TOKEN_ADDRESS && shortToken.isWrapped)) {
|
|
60
59
|
return "short";
|
|
61
60
|
}
|
|
62
61
|
return undefined;
|
|
@@ -91,30 +90,35 @@ export function getCappedPoolPnl(p) {
|
|
|
91
90
|
* user is not opening a new size.
|
|
92
91
|
*/
|
|
93
92
|
const ROUNDING_VALUE = 10000;
|
|
94
|
-
|
|
93
|
+
function capByUiMaxLeverageOverride(value, marketAddress) {
|
|
94
|
+
const uiMaxLeverageOverride = marketAddress ? UI_MAX_LEVERAGE_BY_MARKET[marketAddress] : undefined;
|
|
95
|
+
return uiMaxLeverageOverride === undefined ? value : Math.min(value, uiMaxLeverageOverride * BASIS_POINTS_DIVISOR);
|
|
96
|
+
}
|
|
97
|
+
export function getMaxLeverageByMinCollateralFactor(minCollateralFactor, marketAddress) {
|
|
95
98
|
if (minCollateralFactor === undefined)
|
|
96
|
-
return 100 * BASIS_POINTS_DIVISOR;
|
|
99
|
+
return capByUiMaxLeverageOverride(100 * BASIS_POINTS_DIVISOR, marketAddress);
|
|
97
100
|
if (minCollateralFactor === 0n)
|
|
98
|
-
return 100 * BASIS_POINTS_DIVISOR;
|
|
101
|
+
return capByUiMaxLeverageOverride(100 * BASIS_POINTS_DIVISOR, marketAddress);
|
|
99
102
|
const x = bigMath.mulDiv(PRECISION, BASIS_POINTS_DIVISOR_BIGINT, minCollateralFactor);
|
|
100
103
|
const rounded = Math.round(Number(x) / ROUNDING_VALUE) * ROUNDING_VALUE;
|
|
101
|
-
return rounded;
|
|
104
|
+
return capByUiMaxLeverageOverride(rounded, marketAddress);
|
|
102
105
|
}
|
|
103
106
|
const MAX_ALLOWED_LEVERAGE_STEP_BP = 5 * BASIS_POINTS_DIVISOR;
|
|
104
|
-
export function getMaxAllowedLeverage({ minCollateralFactor, minCollateralFactorForLiquidation, positionFeeFactorForBalanceWasNotImproved, }) {
|
|
107
|
+
export function getMaxAllowedLeverage({ marketAddress, minCollateralFactor, minCollateralFactorForLiquidation, positionFeeFactorForBalanceWasNotImproved, }) {
|
|
105
108
|
if (minCollateralFactor === undefined ||
|
|
106
109
|
minCollateralFactor === 0n ||
|
|
107
110
|
minCollateralFactorForLiquidation === undefined ||
|
|
108
111
|
minCollateralFactorForLiquidation === 0n ||
|
|
109
112
|
positionFeeFactorForBalanceWasNotImproved === undefined) {
|
|
110
|
-
return 100 * BASIS_POINTS_DIVISOR;
|
|
113
|
+
return capByUiMaxLeverageOverride(100 * BASIS_POINTS_DIVISOR, marketAddress);
|
|
111
114
|
}
|
|
112
115
|
const openingDenominator = minCollateralFactor + 2n * positionFeeFactorForBalanceWasNotImproved;
|
|
113
116
|
const openingMaxBp = bigMath.mulDiv(PRECISION, BASIS_POINTS_DIVISOR_BIGINT, openingDenominator);
|
|
114
117
|
const liquidationDenominator = 2n * minCollateralFactorForLiquidation;
|
|
115
118
|
const liquidationMaxBp = bigMath.mulDiv(PRECISION, BASIS_POINTS_DIVISOR_BIGINT, liquidationDenominator);
|
|
116
119
|
const rawMaxBp = bigMath.min(openingMaxBp, liquidationMaxBp);
|
|
117
|
-
|
|
120
|
+
const maxAllowedLeverage = Math.floor(Number(rawMaxBp) / MAX_ALLOWED_LEVERAGE_STEP_BP) * MAX_ALLOWED_LEVERAGE_STEP_BP;
|
|
121
|
+
return capByUiMaxLeverageOverride(maxAllowedLeverage, marketAddress);
|
|
118
122
|
}
|
|
119
123
|
export function getOppositeCollateral(marketInfo, tokenAddress) {
|
|
120
124
|
const poolType = getTokenPoolType(marketInfo, tokenAddress);
|
|
@@ -344,7 +348,7 @@ export function composeFullMarketsInfoData({ chainId, marketsAddresses, rawMarke
|
|
|
344
348
|
return data;
|
|
345
349
|
}
|
|
346
350
|
export function getMarketWithTiers(marketInfo, constants) {
|
|
347
|
-
const maxLeverage = getMaxLeverageByMinCollateralFactor(marketInfo.minCollateralFactor);
|
|
351
|
+
const maxLeverage = getMaxLeverageByMinCollateralFactor(marketInfo.minCollateralFactor, marketInfo.marketTokenAddress);
|
|
348
352
|
const maxLeverageBigint = BigInt(maxLeverage);
|
|
349
353
|
const leverageTiers = [
|
|
350
354
|
{
|
|
@@ -380,6 +380,7 @@ export function getPositionInfo(p) {
|
|
|
380
380
|
pnl: undefined,
|
|
381
381
|
});
|
|
382
382
|
const maxAllowedLeverage = getMaxAllowedLeverage({
|
|
383
|
+
marketAddress: marketInfo.marketTokenAddress,
|
|
383
384
|
minCollateralFactor: marketInfo.minCollateralFactor,
|
|
384
385
|
minCollateralFactorForLiquidation: marketInfo.minCollateralFactorForLiquidation,
|
|
385
386
|
positionFeeFactorForBalanceWasNotImproved: marketInfo.positionFeeFactorForBalanceWasNotImproved,
|
|
@@ -3,4 +3,5 @@ export { generateSubaccount, decryptSubaccountPrivateKey, createSubaccountSigner
|
|
|
3
3
|
export { hashSubaccountApproval } from "./hashSubaccountApproval";
|
|
4
4
|
export { getEmptySubaccountApproval } from "./getEmptySubaccountApproval";
|
|
5
5
|
export { getSubaccountApprovalTypedData } from "./getSubaccountApprovalTypedData";
|
|
6
|
+
export { isEmptySubaccountApproval, isSameSubaccountApproval, isSubaccountApprovalExpired, isSubaccountApprovalNonceExpired, isSubaccountApprovalSynced, isSubaccountStatusUsable, parseSubaccountStatus, shouldRefreshExplicitSubaccountApproval, toSignedSubaccountApproval, } from "./state";
|
|
6
7
|
export { fetchSubaccountStatus, prepareSubaccountApproval, signSubaccountApproval } from "./api";
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { DEFAULT_SUBACCOUNT_EXPIRY_DURATION, DEFAULT_SUBACCOUNT_MAX_ALLOWED_COUNT } from "../../configs/express";
|
|
2
|
+
import { prepareOrder as prepareOrderRaw, signPreparedOrder, submitOrder as submitOrderRaw, } from "../orderTransactions/api";
|
|
3
|
+
import { nowInSeconds } from "../time";
|
|
4
|
+
import { fetchSubaccountStatus, prepareSubaccountApproval, signSubaccountApproval } from "./api";
|
|
5
|
+
import { generateSubaccount } from "./generateSubaccount";
|
|
6
|
+
import { getEmptySubaccountApproval } from "./getEmptySubaccountApproval";
|
|
7
|
+
import { isEmptySubaccountApproval, isSameSubaccountApproval, isSubaccountApprovalExpired, isSubaccountApprovalNonceExpired, isSubaccountApprovalSynced, isSubaccountStatusUsable, parseSubaccountStatus, shouldRefreshExplicitSubaccountApproval, toSignedSubaccountApproval, } from "./state";
|
|
8
|
+
const sdkSubaccountSigners = new WeakMap();
|
|
9
|
+
const MAX_PREPARED_SUBACCOUNT_APPROVALS = 100;
|
|
10
|
+
const SUBACCOUNT_STATUS_CACHE_TTL_MS = 15000;
|
|
11
|
+
const LOW_SUBACCOUNT_ACTIONS_REFRESH_THRESHOLD = 1n;
|
|
12
|
+
const SUBMITTED_ORDER_STATUSES = new Set([
|
|
13
|
+
"relay_accepted",
|
|
14
|
+
"relay_pending",
|
|
15
|
+
"relay_submitted",
|
|
16
|
+
"created",
|
|
17
|
+
"executed",
|
|
18
|
+
]);
|
|
19
|
+
const FINAL_ORDER_STATUSES = new Set(["created", "executed"]);
|
|
20
|
+
function hasSdkSubaccountSigner(owner) {
|
|
21
|
+
return sdkSubaccountSigners.has(owner);
|
|
22
|
+
}
|
|
23
|
+
function getSdkSubaccountSigner(owner) {
|
|
24
|
+
return sdkSubaccountSigners.get(owner);
|
|
25
|
+
}
|
|
26
|
+
function isSameAddress(a, b) {
|
|
27
|
+
return a !== undefined && b !== undefined && a.toLowerCase() === b.toLowerCase();
|
|
28
|
+
}
|
|
29
|
+
function hasDifferentSubaccountAccount(subaccount, account) {
|
|
30
|
+
return subaccount.account !== undefined && !isSameAddress(subaccount.account, account);
|
|
31
|
+
}
|
|
32
|
+
function throwSubaccountAccountMismatch(subaccount, account) {
|
|
33
|
+
throw new Error(`Subaccount ${subaccount.address} belongs to account ${subaccount.account}; requested account is ${account}.`);
|
|
34
|
+
}
|
|
35
|
+
function throwSubaccountAddressMismatch(source, provided, expected) {
|
|
36
|
+
throw new Error(`${source} ${provided} does not match generated subaccount ${expected}.`);
|
|
37
|
+
}
|
|
38
|
+
function resetSdkSubaccount(client) {
|
|
39
|
+
sdkSubaccountSigners.delete(client.owner);
|
|
40
|
+
client.preparedSubaccountApprovals.clear();
|
|
41
|
+
client.setSubaccount(undefined);
|
|
42
|
+
}
|
|
43
|
+
function getUsableSubaccountApproval(client) {
|
|
44
|
+
const subaccount = client.getSubaccount();
|
|
45
|
+
if (!subaccount || !isSubaccountStatusUsable(subaccount.onchainData)) {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
return getEmptySubaccountApproval(client.ctx.chainId, subaccount.address);
|
|
49
|
+
}
|
|
50
|
+
function isSubaccountStatusCacheFresh(subaccount, account) {
|
|
51
|
+
return (isSameAddress(subaccount.account, account) &&
|
|
52
|
+
subaccount.onchainData !== undefined &&
|
|
53
|
+
subaccount.lastStatusFetchedAt !== undefined &&
|
|
54
|
+
Date.now() - subaccount.lastStatusFetchedAt < SUBACCOUNT_STATUS_CACHE_TTL_MS);
|
|
55
|
+
}
|
|
56
|
+
function assertSdkSubaccountRequest(request, subaccount, approval) {
|
|
57
|
+
if (request.subaccountAddress && !isSameAddress(request.subaccountAddress, subaccount.address)) {
|
|
58
|
+
throwSubaccountAddressMismatch("subaccountAddress", request.subaccountAddress, subaccount.address);
|
|
59
|
+
}
|
|
60
|
+
if (approval?.subaccount && !isSameAddress(approval.subaccount, subaccount.address)) {
|
|
61
|
+
throwSubaccountAddressMismatch("subaccountApproval.subaccount", approval.subaccount, subaccount.address);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function shouldRefreshSubaccountApprovalForPrepare(approval, subaccount, account) {
|
|
65
|
+
if (isEmptySubaccountApproval(approval)) {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return (!isSubaccountStatusCacheFresh(subaccount, account) ||
|
|
69
|
+
shouldRefreshExplicitSubaccountApproval(approval, subaccount.onchainData, subaccount.approval));
|
|
70
|
+
}
|
|
71
|
+
function shouldRefreshLowActionSubaccountStatus(status, alreadyRefreshed) {
|
|
72
|
+
return (!alreadyRefreshed && status !== undefined && status.remainingActions <= LOW_SUBACCOUNT_ACTIONS_REFRESH_THRESHOLD);
|
|
73
|
+
}
|
|
74
|
+
function prunePreparedSubaccountApprovals(client) {
|
|
75
|
+
while (client.preparedSubaccountApprovals.size > MAX_PREPARED_SUBACCOUNT_APPROVALS) {
|
|
76
|
+
const oldestRequestId = client.preparedSubaccountApprovals.keys().next().value;
|
|
77
|
+
if (!oldestRequestId) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
client.preparedSubaccountApprovals.delete(oldestRequestId);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function isOrderSubmitAccepted(response) {
|
|
84
|
+
return response.error === undefined && SUBMITTED_ORDER_STATUSES.has(response.status);
|
|
85
|
+
}
|
|
86
|
+
function markSubaccountApprovalSubmitted(subaccount, approval, requestId) {
|
|
87
|
+
if (!approval || !requestId || isEmptySubaccountApproval(approval)) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const pendingApproval = subaccount?.approval;
|
|
91
|
+
if (pendingApproval && isSameSubaccountApproval(pendingApproval.message, approval)) {
|
|
92
|
+
pendingApproval.submittedRequestId = requestId;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function markSubaccountActionSubmitted(subaccount, approval) {
|
|
96
|
+
if (!subaccount?.onchainData || !approval || !isEmptySubaccountApproval(approval)) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
subaccount.onchainData.currentActionsCount += 1n;
|
|
100
|
+
subaccount.onchainData.remainingActions =
|
|
101
|
+
subaccount.onchainData.remainingActions > 0n ? subaccount.onchainData.remainingActions - 1n : 0n;
|
|
102
|
+
}
|
|
103
|
+
export function hasActiveSdkSubaccount(client) {
|
|
104
|
+
const subaccount = client.getSubaccount();
|
|
105
|
+
return (hasSdkSubaccountSigner(client.owner) &&
|
|
106
|
+
(subaccount?.approval !== undefined || isSubaccountStatusUsable(subaccount?.onchainData)));
|
|
107
|
+
}
|
|
108
|
+
export function getSdkSubaccountApprovalMessage(client) {
|
|
109
|
+
const subaccount = client.getSubaccount();
|
|
110
|
+
if (!subaccount) {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
if (subaccount.approval) {
|
|
114
|
+
return subaccount.approval.message;
|
|
115
|
+
}
|
|
116
|
+
return getUsableSubaccountApproval(client);
|
|
117
|
+
}
|
|
118
|
+
export async function generateSdkSubaccount(client, mainSigner) {
|
|
119
|
+
client.preparedSubaccountApprovals.clear();
|
|
120
|
+
const result = await generateSubaccount(mainSigner);
|
|
121
|
+
sdkSubaccountSigners.set(client.owner, result.signer);
|
|
122
|
+
client.setSubaccount({
|
|
123
|
+
account: mainSigner.address,
|
|
124
|
+
address: result.address,
|
|
125
|
+
});
|
|
126
|
+
return result.address;
|
|
127
|
+
}
|
|
128
|
+
export function reconcileSdkSubaccountApproval(subaccount) {
|
|
129
|
+
const approval = subaccount?.approval?.message;
|
|
130
|
+
const status = subaccount?.onchainData;
|
|
131
|
+
if (!subaccount || !approval || !status) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (isSubaccountApprovalSynced(approval, status) ||
|
|
135
|
+
isSubaccountApprovalNonceExpired(approval, status) ||
|
|
136
|
+
isSubaccountApprovalExpired(approval)) {
|
|
137
|
+
subaccount.approval = undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
export async function refreshSdkSubaccountState(client, account) {
|
|
141
|
+
const subaccount = client.getSubaccount();
|
|
142
|
+
if (!subaccount) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
if (hasDifferentSubaccountAccount(subaccount, account)) {
|
|
146
|
+
throwSubaccountAccountMismatch(subaccount, account);
|
|
147
|
+
}
|
|
148
|
+
const status = parseSubaccountStatus(await fetchSubaccountStatus(client.ctx, {
|
|
149
|
+
account,
|
|
150
|
+
subaccountAddress: subaccount.address,
|
|
151
|
+
}));
|
|
152
|
+
subaccount.account = account;
|
|
153
|
+
subaccount.onchainData = status;
|
|
154
|
+
subaccount.lastStatusFetchedAt = Date.now();
|
|
155
|
+
reconcileSdkSubaccountApproval(subaccount);
|
|
156
|
+
return status;
|
|
157
|
+
}
|
|
158
|
+
async function getSdkSubaccountStatus(client, account, options) {
|
|
159
|
+
const subaccount = client.getSubaccount();
|
|
160
|
+
if (!subaccount) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
if (hasDifferentSubaccountAccount(subaccount, account)) {
|
|
164
|
+
throwSubaccountAccountMismatch(subaccount, account);
|
|
165
|
+
}
|
|
166
|
+
if (!options?.force && isSubaccountStatusCacheFresh(subaccount, account)) {
|
|
167
|
+
reconcileSdkSubaccountApproval(subaccount);
|
|
168
|
+
return subaccount.onchainData;
|
|
169
|
+
}
|
|
170
|
+
return refreshSdkSubaccountState(client, account);
|
|
171
|
+
}
|
|
172
|
+
export async function activateSdkSubaccount(client, mainSigner, options, knownStatus) {
|
|
173
|
+
const existingSubaccount = client.getSubaccount();
|
|
174
|
+
if (existingSubaccount && hasDifferentSubaccountAccount(existingSubaccount, mainSigner.address)) {
|
|
175
|
+
resetSdkSubaccount(client);
|
|
176
|
+
}
|
|
177
|
+
if (!client.getSubaccount()) {
|
|
178
|
+
await generateSdkSubaccount(client, mainSigner);
|
|
179
|
+
}
|
|
180
|
+
const status = knownStatus ?? (await getSdkSubaccountStatus(client, mainSigner.address, { force: true }));
|
|
181
|
+
const subaccount = client.getSubaccount();
|
|
182
|
+
const requestedExpiresAt = BigInt(nowInSeconds() + (options?.expiresInSeconds ?? DEFAULT_SUBACCOUNT_EXPIRY_DURATION));
|
|
183
|
+
const expiresAt = status && status.expiresAt > requestedExpiresAt ? status.expiresAt : requestedExpiresAt;
|
|
184
|
+
const requestedMaxAllowedCount = options?.maxAllowedCount !== undefined
|
|
185
|
+
? BigInt(options.maxAllowedCount)
|
|
186
|
+
: (status?.currentActionsCount ?? 0n) + BigInt(DEFAULT_SUBACCOUNT_MAX_ALLOWED_COUNT);
|
|
187
|
+
if (status &&
|
|
188
|
+
isSubaccountStatusUsable(status) &&
|
|
189
|
+
status.maxAllowedCount >= requestedMaxAllowedCount &&
|
|
190
|
+
status.expiresAt >= requestedExpiresAt) {
|
|
191
|
+
subaccount.approval = undefined;
|
|
192
|
+
return subaccount.address;
|
|
193
|
+
}
|
|
194
|
+
const prepared = await prepareSubaccountApproval(client.ctx, {
|
|
195
|
+
account: mainSigner.address,
|
|
196
|
+
subaccountAddress: subaccount.address,
|
|
197
|
+
shouldAdd: status?.active !== true,
|
|
198
|
+
expiresAt: String(expiresAt),
|
|
199
|
+
maxAllowedCount: String(requestedMaxAllowedCount),
|
|
200
|
+
});
|
|
201
|
+
const signature = await signSubaccountApproval(prepared, mainSigner, {
|
|
202
|
+
chainId: client.ctx.chainId,
|
|
203
|
+
expectedSubaccountAddress: subaccount.address,
|
|
204
|
+
});
|
|
205
|
+
const message = toSignedSubaccountApproval(prepared, signature);
|
|
206
|
+
subaccount.approval = {
|
|
207
|
+
message,
|
|
208
|
+
};
|
|
209
|
+
return subaccount.address;
|
|
210
|
+
}
|
|
211
|
+
export async function getSdkSubaccountApprovalForOrder(client, account, mainSigner, options) {
|
|
212
|
+
const subaccount = client.getSubaccount();
|
|
213
|
+
if (!subaccount || !hasSdkSubaccountSigner(client.owner)) {
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
if (hasDifferentSubaccountAccount(subaccount, account)) {
|
|
217
|
+
if (mainSigner && isSameAddress(mainSigner.address, account)) {
|
|
218
|
+
await activateSdkSubaccount(client, mainSigner);
|
|
219
|
+
return client.getSubaccount()?.approval?.message ?? getUsableSubaccountApproval(client);
|
|
220
|
+
}
|
|
221
|
+
throwSubaccountAccountMismatch(subaccount, account);
|
|
222
|
+
}
|
|
223
|
+
const forceStatusRefresh = Boolean(options?.forceRefresh || subaccount.approval?.submittedRequestId !== undefined);
|
|
224
|
+
let status = await getSdkSubaccountStatus(client, account, {
|
|
225
|
+
force: forceStatusRefresh,
|
|
226
|
+
});
|
|
227
|
+
// After forced refresh due to submittedRequestId, clear the flag if approval still exists (relay failed but approval is still valid)
|
|
228
|
+
if (subaccount.approval?.submittedRequestId !== undefined) {
|
|
229
|
+
subaccount.approval.submittedRequestId = undefined;
|
|
230
|
+
}
|
|
231
|
+
const pendingApproval = subaccount.approval;
|
|
232
|
+
if (pendingApproval) {
|
|
233
|
+
if (pendingApproval.submittedRequestId) {
|
|
234
|
+
throw new Error(`Subaccount approval is pending in request ${pendingApproval.submittedRequestId}. ` +
|
|
235
|
+
"Refresh subaccount state after it is submitted on-chain before preparing another subaccount order.");
|
|
236
|
+
}
|
|
237
|
+
if (!isSubaccountApprovalExpired(pendingApproval.message)) {
|
|
238
|
+
return pendingApproval.message;
|
|
239
|
+
}
|
|
240
|
+
subaccount.approval = undefined;
|
|
241
|
+
}
|
|
242
|
+
if (isSubaccountStatusUsable(status)) {
|
|
243
|
+
if (shouldRefreshLowActionSubaccountStatus(status, forceStatusRefresh)) {
|
|
244
|
+
status = await getSdkSubaccountStatus(client, account, { force: true });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (isSubaccountStatusUsable(status)) {
|
|
248
|
+
return getUsableSubaccountApproval(client);
|
|
249
|
+
}
|
|
250
|
+
if (mainSigner) {
|
|
251
|
+
await activateSdkSubaccount(client, mainSigner, undefined, status);
|
|
252
|
+
return client.getSubaccount()?.approval?.message ?? getUsableSubaccountApproval(client);
|
|
253
|
+
}
|
|
254
|
+
throw new Error("Subaccount is not active. Call activateSubaccount(mainSigner) before preparing express orders.");
|
|
255
|
+
}
|
|
256
|
+
export async function prepareWithSubaccount(client, request, prepareFn, mainSigner) {
|
|
257
|
+
let enrichedRequest = request;
|
|
258
|
+
let subaccountApproval;
|
|
259
|
+
const subaccount = client.getSubaccount();
|
|
260
|
+
if (request.mode === "express" && subaccount && hasSdkSubaccountSigner(client.owner)) {
|
|
261
|
+
if (hasDifferentSubaccountAccount(subaccount, request.from)) {
|
|
262
|
+
throwSubaccountAccountMismatch(subaccount, request.from);
|
|
263
|
+
}
|
|
264
|
+
subaccountApproval = request.subaccountApproval;
|
|
265
|
+
assertSdkSubaccountRequest(request, subaccount, subaccountApproval);
|
|
266
|
+
if (subaccountApproval && isEmptySubaccountApproval(subaccountApproval)) {
|
|
267
|
+
subaccountApproval = await getSdkSubaccountApprovalForOrder(client, request.from, mainSigner);
|
|
268
|
+
}
|
|
269
|
+
else if (subaccountApproval &&
|
|
270
|
+
shouldRefreshSubaccountApprovalForPrepare(subaccountApproval, subaccount, request.from)) {
|
|
271
|
+
subaccountApproval = await getSdkSubaccountApprovalForOrder(client, request.from, mainSigner, {
|
|
272
|
+
forceRefresh: true,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
else if (!subaccountApproval) {
|
|
276
|
+
subaccountApproval = await getSdkSubaccountApprovalForOrder(client, request.from, mainSigner);
|
|
277
|
+
}
|
|
278
|
+
else if (isEmptySubaccountApproval(subaccountApproval)) {
|
|
279
|
+
let status = await getSdkSubaccountStatus(client, request.from);
|
|
280
|
+
if (shouldRefreshLowActionSubaccountStatus(status, false)) {
|
|
281
|
+
status = await getSdkSubaccountStatus(client, request.from, { force: true });
|
|
282
|
+
}
|
|
283
|
+
if (!isSubaccountStatusUsable(status)) {
|
|
284
|
+
throw new Error("Subaccount is not active. Call activateSubaccount(mainSigner) before preparing express orders.");
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (subaccountApproval) {
|
|
288
|
+
assertSdkSubaccountRequest(request, client.getSubaccount(), subaccountApproval);
|
|
289
|
+
enrichedRequest = {
|
|
290
|
+
...request,
|
|
291
|
+
subaccountAddress: request.subaccountAddress ?? client.getSubaccount().address,
|
|
292
|
+
subaccountApproval,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const prepared = await prepareFn(client.ctx, enrichedRequest);
|
|
297
|
+
if (prepared.requestId && subaccountApproval) {
|
|
298
|
+
client.preparedSubaccountApprovals.set(prepared.requestId, subaccountApproval);
|
|
299
|
+
prunePreparedSubaccountApprovals(client);
|
|
300
|
+
}
|
|
301
|
+
return prepared;
|
|
302
|
+
}
|
|
303
|
+
export function signOrderWithSubaccount(client, prepared, signer) {
|
|
304
|
+
const subSigner = client.preparedSubaccountApprovals.has(prepared.requestId)
|
|
305
|
+
? getSdkSubaccountSigner(client.owner)
|
|
306
|
+
: undefined;
|
|
307
|
+
const effectiveSigner = subSigner ?? signer;
|
|
308
|
+
const accountAddress = subSigner ? signer.address : undefined;
|
|
309
|
+
return signPreparedOrder(prepared, effectiveSigner, client.ctx.chainId, accountAddress);
|
|
310
|
+
}
|
|
311
|
+
export async function submitOrderWithSubaccount(client, request) {
|
|
312
|
+
const subaccountApproval = request.requestId ? client.preparedSubaccountApprovals.get(request.requestId) : undefined;
|
|
313
|
+
const enrichedRequest = subaccountApproval && request.eip712Data
|
|
314
|
+
? {
|
|
315
|
+
...request,
|
|
316
|
+
eip712Data: {
|
|
317
|
+
...request.eip712Data,
|
|
318
|
+
subaccountApproval,
|
|
319
|
+
},
|
|
320
|
+
}
|
|
321
|
+
: request;
|
|
322
|
+
const response = await submitOrderRaw(client.ctx, enrichedRequest);
|
|
323
|
+
if (isOrderSubmitAccepted(response)) {
|
|
324
|
+
markSubaccountApprovalSubmitted(client.getSubaccount(), subaccountApproval, request.requestId ?? response.requestId);
|
|
325
|
+
if (FINAL_ORDER_STATUSES.has(response.status)) {
|
|
326
|
+
markSubaccountActionSubmitted(client.getSubaccount(), subaccountApproval);
|
|
327
|
+
}
|
|
328
|
+
if (request.requestId) {
|
|
329
|
+
client.preparedSubaccountApprovals.delete(request.requestId);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return response;
|
|
333
|
+
}
|
|
334
|
+
export async function executeExpressOrderWithSubaccount(client, request, signer) {
|
|
335
|
+
const prepared = await prepareWithSubaccount(client, request, prepareOrderRaw, signer);
|
|
336
|
+
const signature = await signOrderWithSubaccount(client, prepared, signer);
|
|
337
|
+
const isSubaccountOrder = client.preparedSubaccountApprovals.has(prepared.requestId);
|
|
338
|
+
return submitOrderWithSubaccount(client, {
|
|
339
|
+
mode: prepared.mode,
|
|
340
|
+
requestId: prepared.requestId,
|
|
341
|
+
signature,
|
|
342
|
+
from: isSubaccountOrder ? request.from : signer.address,
|
|
343
|
+
idempotencyKey: prepared.idempotencyKey,
|
|
344
|
+
eip712Data: {
|
|
345
|
+
batchParams: prepared.payload.batchParams,
|
|
346
|
+
relayParams: prepared.payload.relayParams,
|
|
347
|
+
},
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
export function clearSdkSubaccount(client) {
|
|
351
|
+
resetSdkSubaccount(client);
|
|
352
|
+
}
|