@pear-protocol/symmio-client 0.2.4 → 0.2.5

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/dist/index.mjs CHANGED
@@ -6,294 +6,72 @@ var __export = (target, all) => {
6
6
  __defProp(target, name, { get: all[name], enumerable: true });
7
7
  };
8
8
 
9
- // src/constants/chains.ts
10
- var SupportedChainId = /* @__PURE__ */ ((SupportedChainId2) => {
11
- SupportedChainId2[SupportedChainId2["ARBITRUM"] = 42161] = "ARBITRUM";
12
- SupportedChainId2[SupportedChainId2["BASE"] = 8453] = "BASE";
13
- SupportedChainId2[SupportedChainId2["BSC"] = 56] = "BSC";
14
- SupportedChainId2[SupportedChainId2["POLYGON"] = 137] = "POLYGON";
15
- SupportedChainId2[SupportedChainId2["MAINNET"] = 1] = "MAINNET";
16
- return SupportedChainId2;
17
- })(SupportedChainId || {});
18
- var V3_CHAIN_IDS = [
19
- 42161 /* ARBITRUM */,
20
- 8453 /* BASE */
21
- ];
22
- var FALLBACK_CHAIN_ID = 42161 /* ARBITRUM */;
23
- var CHAIN_NAMES = {
24
- [42161 /* ARBITRUM */]: "Arbitrum One",
25
- [8453 /* BASE */]: "Base",
26
- [56 /* BSC */]: "BNB Chain",
27
- [137 /* POLYGON */]: "Polygon",
28
- [1 /* MAINNET */]: "Ethereum"
29
- };
9
+ // src/types/common.ts
10
+ var PositionType = /* @__PURE__ */ ((PositionType2) => {
11
+ PositionType2[PositionType2["LONG"] = 0] = "LONG";
12
+ PositionType2[PositionType2["SHORT"] = 1] = "SHORT";
13
+ return PositionType2;
14
+ })(PositionType || {});
15
+ var OrderType = /* @__PURE__ */ ((OrderType2) => {
16
+ OrderType2[OrderType2["LIMIT"] = 0] = "LIMIT";
17
+ OrderType2[OrderType2["MARKET"] = 1] = "MARKET";
18
+ return OrderType2;
19
+ })(OrderType || {});
20
+ var QuoteStatus = /* @__PURE__ */ ((QuoteStatus2) => {
21
+ QuoteStatus2[QuoteStatus2["PENDING"] = 0] = "PENDING";
22
+ QuoteStatus2[QuoteStatus2["LOCKED"] = 1] = "LOCKED";
23
+ QuoteStatus2[QuoteStatus2["CANCEL_PENDING"] = 2] = "CANCEL_PENDING";
24
+ QuoteStatus2[QuoteStatus2["CANCELED"] = 3] = "CANCELED";
25
+ QuoteStatus2[QuoteStatus2["OPENED"] = 4] = "OPENED";
26
+ QuoteStatus2[QuoteStatus2["CLOSE_PENDING"] = 5] = "CLOSE_PENDING";
27
+ QuoteStatus2[QuoteStatus2["CANCEL_CLOSE_PENDING"] = 6] = "CANCEL_CLOSE_PENDING";
28
+ QuoteStatus2[QuoteStatus2["CLOSED"] = 7] = "CLOSED";
29
+ QuoteStatus2[QuoteStatus2["LIQUIDATED"] = 8] = "LIQUIDATED";
30
+ QuoteStatus2[QuoteStatus2["EXPIRED"] = 9] = "EXPIRED";
31
+ return QuoteStatus2;
32
+ })(QuoteStatus || {});
33
+ var LiquidationStatus = /* @__PURE__ */ ((LiquidationStatus2) => {
34
+ LiquidationStatus2[LiquidationStatus2["NONE"] = 0] = "NONE";
35
+ LiquidationStatus2[LiquidationStatus2["PENDING"] = 1] = "PENDING";
36
+ LiquidationStatus2[LiquidationStatus2["ACTIVE"] = 2] = "ACTIVE";
37
+ LiquidationStatus2[LiquidationStatus2["COMPLETED"] = 3] = "COMPLETED";
38
+ return LiquidationStatus2;
39
+ })(LiquidationStatus || {});
40
+ var SoftLiquidationLevel = /* @__PURE__ */ ((SoftLiquidationLevel2) => {
41
+ SoftLiquidationLevel2[SoftLiquidationLevel2["NONE"] = 0] = "NONE";
42
+ SoftLiquidationLevel2[SoftLiquidationLevel2["WARNING"] = 1] = "WARNING";
43
+ SoftLiquidationLevel2[SoftLiquidationLevel2["CRITICAL"] = 2] = "CRITICAL";
44
+ SoftLiquidationLevel2[SoftLiquidationLevel2["EMERGENCY"] = 3] = "EMERGENCY";
45
+ return SoftLiquidationLevel2;
46
+ })(SoftLiquidationLevel || {});
30
47
 
31
- // src/constants/addresses.ts
32
- var MULTI_ACCOUNT_ADDRESS = {
33
- [42161 /* ARBITRUM */]: "0x6273242a7E88b3De90822b31648C212215caaFE4",
34
- [8453 /* BASE */]: "0xE43166cE17d3511B09438a359dAa53513225101D"
35
- };
36
- var SYMMIO_DIAMOND_ADDRESS = {
37
- [42161 /* ARBITRUM */]: "0x8F06459f184553e5d04F07F868720BDaCAB39395",
38
- [8453 /* BASE */]: "0x91Cf2D8Ed503EC52768999aA6D8DBeA6e52dbe43"
39
- };
40
- var COLLATERAL_ADDRESS = {
41
- [42161 /* ARBITRUM */]: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
42
- [8453 /* BASE */]: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
43
- };
44
- var CLEARING_HOUSE_ADDRESS = {
45
- [42161 /* ARBITRUM */]: "0x0000000000000000000000000000000000000000",
46
- [8453 /* BASE */]: "0x0000000000000000000000000000000000000000"
47
- };
48
- var SIGNATURE_STORE_ADDRESS = {
49
- [42161 /* ARBITRUM */]: "0x94eEa58De1C8945c342dB4bE9670301638E403e2"
50
- };
51
- var DEFAULT_PARTY_B_ADDRESS = {
52
- [42161 /* ARBITRUM */]: "0x00c069d68bc7420740460DBC3cc3fFF9b3742421",
53
- [8453 /* BASE */]: "0x1EcAbF0Eba136920677C9575FAccee36f30592cf"
54
- };
55
- var COLLATERAL_DECIMALS = {
56
- [42161 /* ARBITRUM */]: 6,
57
- [8453 /* BASE */]: 6
58
- };
59
- function getAddress(addressMap, chainId, name) {
60
- const addr = addressMap[chainId];
61
- if (!addr || addr === "0x0000000000000000000000000000000000000000") {
62
- throw new Error(`${name} address not configured for chain ${chainId}`);
63
- }
64
- return addr;
65
- }
48
+ // src/types/affiliate.ts
49
+ var AffiliateFeeLevel = /* @__PURE__ */ ((AffiliateFeeLevel2) => {
50
+ AffiliateFeeLevel2[AffiliateFeeLevel2["USER_SYMBOL"] = 0] = "USER_SYMBOL";
51
+ AffiliateFeeLevel2[AffiliateFeeLevel2["USER_DEFAULT"] = 1] = "USER_DEFAULT";
52
+ AffiliateFeeLevel2[AffiliateFeeLevel2["SYMBOL"] = 2] = "SYMBOL";
53
+ AffiliateFeeLevel2[AffiliateFeeLevel2["AFFILIATE_DEFAULT"] = 3] = "AFFILIATE_DEFAULT";
54
+ return AffiliateFeeLevel2;
55
+ })(AffiliateFeeLevel || {});
66
56
 
67
- // src/constants/defaults.ts
68
- var MARKET_ORDER_DEADLINE = 300n;
69
- var LIMIT_ORDER_DEADLINE = 311040120n;
70
- var MARKET_PRICE_COEFFICIENT = 1.01;
71
- var MAX_LEVERAGE = 50;
72
- var DEFAULT_PRECISION = 2;
73
- var GAS_MARGIN_PERCENTAGE = 20n;
74
- var STANDARD_WITHDRAW_COOLDOWN = 43200;
75
- var MUON_BASE_URLS = [
76
- "https://muon-oracle1.rasa.capital/v1/",
77
- "https://muon-oracle2.rasa.capital/v1/",
78
- "https://muon-oracle3.rasa.capital/v1/",
79
- "https://muon-oracle4.rasa.capital/v1/"
80
- ];
81
- var MUON_APP_NAME = "symmio";
82
- var MUON_REQUEST_TIMEOUT = 15e3;
83
- var HEDGER_BASE_URLS = {
84
- [42161 /* ARBITRUM */]: "https://www.perps-streaming.com/v1/42161a/0x6273242a7E88b3De90822b31648C212215caaFE4",
85
- [8453 /* BASE */]: "https://www.perps-streaming.com/v1/8453a/0x6273242a7E88b3De90822b31648C212215caaFE4"
86
- };
87
- var SymmioSDKError = class extends Error {
88
- constructor(message, code) {
89
- super(message);
90
- this.code = code;
91
- this.name = "SymmioSDKError";
92
- }
93
- };
94
- function validateAddress(address, name) {
95
- if (!isAddress(address)) {
96
- throw new SymmioSDKError(
97
- `Invalid ${name} address: ${address}`,
98
- "INVALID_ADDRESS"
99
- );
100
- }
101
- return address;
102
- }
103
- function validateAmount(amount, name) {
104
- if (amount <= 0n) {
105
- throw new SymmioSDKError(
106
- `${name} must be a positive amount, got ${amount}`,
107
- "INVALID_AMOUNT"
108
- );
109
- }
110
- }
111
- function validateChainId(chainId, supportedChains) {
112
- if (!supportedChains.includes(chainId)) {
113
- throw new SymmioSDKError(
114
- `Chain ${chainId} is not supported. Supported: ${supportedChains.join(", ")}`,
115
- "UNSUPPORTED_CHAIN"
116
- );
117
- }
118
- }
119
- function validateDeadline(deadline) {
120
- const now = BigInt(Math.floor(Date.now() / 1e3));
121
- if (deadline <= now) {
122
- throw new SymmioSDKError(
123
- `Deadline ${deadline} is in the past (current: ${now})`,
124
- "EXPIRED_DEADLINE"
125
- );
126
- }
127
- }
128
- function validateQuantity(quantity) {
129
- if (quantity <= 0n) {
130
- throw new SymmioSDKError(
131
- `Quantity must be positive, got ${quantity}`,
132
- "INVALID_QUANTITY"
133
- );
134
- }
135
- }
57
+ // src/types/clearingHouse.ts
58
+ var ClearingHouseLiquidationStatus = /* @__PURE__ */ ((ClearingHouseLiquidationStatus2) => {
59
+ ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["INITIATED"] = 0] = "INITIATED";
60
+ ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["DEALLOCATED"] = 1] = "DEALLOCATED";
61
+ ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["POSITIONS_CLOSED"] = 2] = "POSITIONS_CLOSED";
62
+ ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["SETTLED"] = 3] = "SETTLED";
63
+ ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["COMPLETED"] = 4] = "COMPLETED";
64
+ return ClearingHouseLiquidationStatus2;
65
+ })(ClearingHouseLiquidationStatus || {});
136
66
 
137
- // src/clients/muon.ts
138
- function parseSchnorrSign(sigs) {
139
- return {
140
- signature: BigInt(sigs.signature),
141
- owner: sigs.owner,
142
- nonce: sigs.nonce
143
- };
144
- }
145
- function parseSingleUpnlSig(result) {
146
- const data = result["result"];
147
- if (!data) {
148
- throw new SymmioSDKError("Invalid Muon response: missing result", "MUON_PARSE_ERROR");
149
- }
150
- const sigData = data["data"];
151
- const signParams = sigData?.["signParams"] ?? data["signParams"];
152
- const signatures = sigData?.["signatures"] ?? data["signatures"];
153
- return {
154
- reqId: signParams["reqId"],
155
- timestamp: BigInt(signParams["timestamp"]),
156
- upnl: BigInt(signParams["upnl"]),
157
- gatewaySignature: signatures?.[0]?.["signature"] ?? "0x",
158
- sigs: parseSchnorrSign(
159
- signParams["sigs"] ?? signatures?.[1]
160
- )
161
- };
162
- }
163
- function parseSingleUpnlAndPriceSig(result) {
164
- const data = result["result"];
165
- if (!data) {
166
- throw new SymmioSDKError("Invalid Muon response: missing result", "MUON_PARSE_ERROR");
167
- }
168
- const sigData = data["data"];
169
- const signParams = sigData?.["signParams"] ?? data["signParams"];
170
- const signatures = sigData?.["signatures"] ?? data["signatures"];
171
- return {
172
- reqId: signParams["reqId"],
173
- timestamp: BigInt(signParams["timestamp"]),
174
- upnl: BigInt(signParams["upnl"]),
175
- price: BigInt(signParams["price"]),
176
- gatewaySignature: signatures?.[0]?.["signature"] ?? "0x",
177
- sigs: parseSchnorrSign(
178
- signParams["sigs"] ?? signatures?.[1]
179
- )
180
- };
181
- }
182
- function parseBatchSig(result) {
183
- const data = result["result"];
184
- if (!data) {
185
- throw new SymmioSDKError("Invalid Muon response: missing result", "MUON_PARSE_ERROR");
186
- }
187
- const sigData = data["data"];
188
- const signParams = sigData?.["signParams"] ?? data["signParams"];
189
- const signatures = sigData?.["signatures"] ?? data["signatures"];
190
- return {
191
- reqId: signParams["reqId"],
192
- timestamp: BigInt(signParams["timestamp"]),
193
- upnl: BigInt(signParams["upnl"]),
194
- prices: signParams["prices"].map((p) => BigInt(p)),
195
- symbolIds: signParams["symbolIds"].map((s) => BigInt(s)),
196
- gatewaySignature: signatures?.[0]?.["signature"] ?? "0x",
197
- sigs: parseSchnorrSign(
198
- signParams["sigs"] ?? signatures?.[1]
199
- )
200
- };
201
- }
202
- var MuonClient = class {
203
- baseUrls;
204
- appName;
205
- timeout;
206
- constructor(config) {
207
- this.baseUrls = config?.baseUrls ?? MUON_BASE_URLS;
208
- this.appName = config?.appName ?? MUON_APP_NAME;
209
- this.timeout = config?.timeout ?? MUON_REQUEST_TIMEOUT;
210
- }
211
- /**
212
- * Sends a request to Muon, trying each base URL in order until one succeeds.
213
- */
214
- async sendRequest(method, params) {
215
- let lastError = null;
216
- for (const baseUrl of this.baseUrls) {
217
- try {
218
- const searchParams = new URLSearchParams({
219
- app: this.appName,
220
- method
221
- });
222
- for (const [key, value] of Object.entries(params)) {
223
- searchParams.set(`params[${key}]`, value);
224
- }
225
- const url = `${baseUrl}?${searchParams.toString()}`;
226
- const controller = new AbortController();
227
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
228
- const response = await fetch(url, { signal: controller.signal });
229
- clearTimeout(timeoutId);
230
- if (!response.ok) {
231
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
232
- }
233
- const json = await response.json();
234
- if (json["error"]) {
235
- throw new Error(`Muon error: ${JSON.stringify(json["error"])}`);
236
- }
237
- return json;
238
- } catch (err) {
239
- lastError = err instanceof Error ? err : new Error(String(err));
240
- }
241
- }
242
- throw new SymmioSDKError(
243
- `All Muon nodes failed. Last error: ${lastError?.message}`,
244
- "MUON_REQUEST_FAILED"
245
- );
246
- }
247
- /**
248
- * Gets a UPnL + Price signature for opening a position (sendQuote).
249
- */
250
- async getQuoteSig(params) {
251
- const result = await this.sendRequest("uPnl_A_withSymbolPrice", {
252
- partyA: params.partyA,
253
- chainId: params.chainId.toString(),
254
- symmio: params.symmioAddress,
255
- symbolId: params.symbolId.toString()
256
- });
257
- return parseSingleUpnlAndPriceSig(result);
258
- }
259
- /**
260
- * Gets a UPnL signature for deallocating funds.
261
- * v0.8.5: Now includes pendingBalance for safe deallocate.
262
- */
263
- async getDeallocateSig(params) {
264
- const result = await this.sendRequest("uPnl_A", {
265
- partyA: params.partyA,
266
- chainId: params.chainId.toString(),
267
- symmio: params.symmioAddress
268
- });
269
- return parseSingleUpnlSig(result);
270
- }
271
- /**
272
- * Gets a batch signature for multiple positions (v0.8.5).
273
- * Single signature covers multiple symbol prices for batch open/close.
274
- */
275
- async getBatchSig(params) {
276
- const result = await this.sendRequest("uPnl_A_withSymbolPrices", {
277
- partyA: params.partyA,
278
- chainId: params.chainId.toString(),
279
- symmio: params.symmioAddress,
280
- symbolIds: params.symbolIds.join(",")
281
- });
282
- return parseBatchSig(result);
283
- }
284
- };
285
-
286
- // src/actions/account.ts
287
- var account_exports = {};
288
- __export(account_exports, {
289
- addAccount: () => addAccount,
290
- editAccountName: () => editAccountName,
291
- getAccounts: () => getAccounts,
292
- getAccountsLength: () => getAccountsLength,
293
- getOwner: () => getOwner,
294
- prepareAddAccount: () => prepareAddAccount,
295
- prepareEditAccountName: () => prepareEditAccountName
296
- });
67
+ // src/types/instant.ts
68
+ var InstantCloseStatus = /* @__PURE__ */ ((InstantCloseStatus2) => {
69
+ InstantCloseStatus2[InstantCloseStatus2["STARTED"] = 0] = "STARTED";
70
+ InstantCloseStatus2[InstantCloseStatus2["PROCESSING"] = 1] = "PROCESSING";
71
+ InstantCloseStatus2[InstantCloseStatus2["FAILED"] = 2] = "FAILED";
72
+ InstantCloseStatus2[InstantCloseStatus2["FINISHED"] = 3] = "FINISHED";
73
+ return InstantCloseStatus2;
74
+ })(InstantCloseStatus || {});
297
75
 
298
76
  // src/abis/MultiAccount.ts
299
77
  var MultiAccountABI = [
@@ -700,188 +478,6 @@ var MultiAccountABI = [
700
478
  { name: "RoleRevoked", type: "event", inputs: [{ name: "role", type: "bytes32", indexed: true }, { name: "account", type: "address", indexed: true }, { name: "sender", type: "address", indexed: true }] }
701
479
  ];
702
480
 
703
- // src/utils/gas.ts
704
- function calculateGasMargin(estimatedGas) {
705
- return estimatedGas * (100n + GAS_MARGIN_PERCENTAGE) / 100n;
706
- }
707
-
708
- // src/actions/account.ts
709
- function prepareAddAccount(multiAccount, account, name) {
710
- const data = encodeFunctionData({
711
- abi: MultiAccountABI,
712
- functionName: "addAccount",
713
- args: [name]
714
- });
715
- return {
716
- functionName: "addAccount",
717
- args: [name],
718
- config: { account, to: multiAccount, data, value: 0n }
719
- };
720
- }
721
- function prepareEditAccountName(multiAccount, account, accountAddress, name) {
722
- const data = encodeFunctionData({
723
- abi: MultiAccountABI,
724
- functionName: "editAccountName",
725
- args: [accountAddress, name]
726
- });
727
- return {
728
- functionName: "editAccountName",
729
- args: [accountAddress, name],
730
- config: { account, to: multiAccount, data, value: 0n }
731
- };
732
- }
733
- async function addAccount(walletClient, publicClient, multiAccount, name) {
734
- const account = walletClient.account?.address;
735
- if (!account) throw new Error("Wallet client has no account");
736
- const prepared = prepareAddAccount(multiAccount, account, name);
737
- const gas = await publicClient.estimateGas(prepared.config);
738
- return walletClient.sendTransaction({
739
- ...prepared.config,
740
- gas: calculateGasMargin(gas),
741
- chain: walletClient.chain
742
- });
743
- }
744
- async function editAccountName(walletClient, publicClient, multiAccount, accountAddress, name) {
745
- const account = walletClient.account?.address;
746
- if (!account) throw new Error("Wallet client has no account");
747
- const prepared = prepareEditAccountName(multiAccount, account, accountAddress, name);
748
- const gas = await publicClient.estimateGas(prepared.config);
749
- return walletClient.sendTransaction({
750
- ...prepared.config,
751
- gas: calculateGasMargin(gas),
752
- chain: walletClient.chain
753
- });
754
- }
755
- async function getAccounts(publicClient, multiAccount, user, start = 0, size = 100) {
756
- const result = await publicClient.readContract({
757
- address: multiAccount,
758
- abi: MultiAccountABI,
759
- functionName: "getAccounts",
760
- args: [user, BigInt(start), BigInt(size)]
761
- });
762
- return result;
763
- }
764
- async function getAccountsLength(publicClient, multiAccount, user) {
765
- const result = await publicClient.readContract({
766
- address: multiAccount,
767
- abi: MultiAccountABI,
768
- functionName: "getAccountsLength",
769
- args: [user]
770
- });
771
- return Number(result);
772
- }
773
- async function getOwner(publicClient, multiAccount, accountAddress) {
774
- const result = await publicClient.readContract({
775
- address: multiAccount,
776
- abi: MultiAccountABI,
777
- functionName: "owners",
778
- args: [accountAddress]
779
- });
780
- return result;
781
- }
782
-
783
- // src/actions/deposit.ts
784
- var deposit_exports = {};
785
- __export(deposit_exports, {
786
- deposit: () => deposit,
787
- depositAndAllocate: () => depositAndAllocate,
788
- prepareDeposit: () => prepareDeposit,
789
- prepareDepositAndAllocate: () => prepareDepositAndAllocate
790
- });
791
- function prepareDeposit(multiAccount, account, params) {
792
- validateAmount(params.amount, "deposit amount");
793
- validateAddress(params.account, "account");
794
- const data = encodeFunctionData({
795
- abi: MultiAccountABI,
796
- functionName: "depositForAccount",
797
- args: [params.account, params.amount]
798
- });
799
- return {
800
- functionName: "depositForAccount",
801
- args: [params.account, params.amount],
802
- config: { account, to: multiAccount, data, value: 0n }
803
- };
804
- }
805
- function prepareDepositAndAllocate(multiAccount, account, params) {
806
- validateAmount(params.amount, "deposit amount");
807
- validateAddress(params.account, "account");
808
- const data = encodeFunctionData({
809
- abi: MultiAccountABI,
810
- functionName: "depositAndAllocateForAccount",
811
- args: [params.account, params.amount]
812
- });
813
- return {
814
- functionName: "depositAndAllocateForAccount",
815
- args: [params.account, params.amount],
816
- config: { account, to: multiAccount, data, value: 0n }
817
- };
818
- }
819
- async function deposit(walletClient, publicClient, multiAccount, params) {
820
- const account = walletClient.account?.address;
821
- if (!account) throw new Error("Wallet client has no account");
822
- const prepared = prepareDeposit(multiAccount, account, params);
823
- const gas = await publicClient.estimateGas(prepared.config);
824
- return walletClient.sendTransaction({
825
- ...prepared.config,
826
- gas: calculateGasMargin(gas),
827
- chain: walletClient.chain
828
- });
829
- }
830
- async function depositAndAllocate(walletClient, publicClient, multiAccount, params) {
831
- const account = walletClient.account?.address;
832
- if (!account) throw new Error("Wallet client has no account");
833
- const prepared = prepareDepositAndAllocate(multiAccount, account, params);
834
- const gas = await publicClient.estimateGas(prepared.config);
835
- return walletClient.sendTransaction({
836
- ...prepared.config,
837
- gas: calculateGasMargin(gas),
838
- chain: walletClient.chain
839
- });
840
- }
841
-
842
- // src/actions/withdraw.ts
843
- var withdraw_exports = {};
844
- __export(withdraw_exports, {
845
- prepareWithdraw: () => prepareWithdraw,
846
- withdraw: () => withdraw
847
- });
848
- function prepareWithdraw(multiAccount, account, params) {
849
- validateAmount(params.amount, "withdraw amount");
850
- validateAddress(params.account, "account");
851
- const data = encodeFunctionData({
852
- abi: MultiAccountABI,
853
- functionName: "withdrawFromAccount",
854
- args: [params.account, params.amount]
855
- });
856
- return {
857
- functionName: "withdrawFromAccount",
858
- args: [params.account, params.amount],
859
- config: { account, to: multiAccount, data, value: 0n }
860
- };
861
- }
862
- async function withdraw(walletClient, publicClient, multiAccount, params) {
863
- const account = walletClient.account?.address;
864
- if (!account) throw new Error("Wallet client has no account");
865
- const prepared = prepareWithdraw(multiAccount, account, params);
866
- const gas = await publicClient.estimateGas(prepared.config);
867
- return walletClient.sendTransaction({
868
- ...prepared.config,
869
- gas: calculateGasMargin(gas),
870
- chain: walletClient.chain
871
- });
872
- }
873
-
874
- // src/actions/allocate.ts
875
- var allocate_exports = {};
876
- __export(allocate_exports, {
877
- allocate: () => allocate,
878
- deallocate: () => deallocate,
879
- internalTransfer: () => internalTransfer,
880
- prepareAllocate: () => prepareAllocate,
881
- prepareDeallocate: () => prepareDeallocate,
882
- prepareInternalTransfer: () => prepareInternalTransfer
883
- });
884
-
885
481
  // src/abis/SymmioDiamond.ts
886
482
  var SymmioDiamondABI = [
887
483
  {
@@ -23266,1687 +22862,1754 @@ var SymmioDiamondABI = [
23266
22862
  type: "function"
23267
22863
  }
23268
22864
  ];
23269
- function encodeCall(abi, functionName, args) {
23270
- return encodeFunctionData({
23271
- abi,
23272
- functionName,
23273
- args
23274
- });
23275
- }
23276
- function wrapInProxyCall(accountDiamondAbi, subAccount, callDatas) {
23277
- const data = encodeFunctionData({
23278
- abi: accountDiamondAbi,
23279
- functionName: "_call",
23280
- args: [subAccount, callDatas]
23281
- });
23282
- return {
23283
- functionName: "_call",
23284
- args: [subAccount, callDatas],
23285
- data
23286
- };
23287
- }
23288
-
23289
- // src/actions/allocate.ts
23290
- function prepareAllocate(multiAccount, account, subAccount, params) {
23291
- validateAmount(params.amount, "allocate amount");
23292
- const innerData = encodeFunctionData({
23293
- abi: SymmioDiamondABI,
23294
- functionName: "allocate",
23295
- args: [params.amount]
23296
- });
23297
- const proxy = wrapInProxyCall(
23298
- MultiAccountABI,
23299
- subAccount,
23300
- [innerData]
23301
- );
23302
- return {
23303
- functionName: "_call",
23304
- args: proxy.args,
23305
- config: { account, to: multiAccount, data: proxy.data, value: 0n }
23306
- };
23307
- }
23308
- function prepareDeallocate(multiAccount, account, subAccount, params) {
23309
- validateAmount(params.amount, "deallocate amount");
23310
- const muonSig = {
23311
- reqId: params.upnlSig.reqId,
23312
- timestamp: params.upnlSig.timestamp,
23313
- upnl: params.upnlSig.upnl,
23314
- gatewaySignature: params.upnlSig.gatewaySignature,
23315
- sigs: {
23316
- signature: params.upnlSig.sigs.signature,
23317
- owner: params.upnlSig.sigs.owner,
23318
- nonce: params.upnlSig.sigs.nonce
23319
- }
23320
- };
23321
- const innerData = encodeFunctionData({
23322
- abi: SymmioDiamondABI,
23323
- functionName: "deallocate",
23324
- args: [params.amount, muonSig]
23325
- });
23326
- const proxy = wrapInProxyCall(
23327
- MultiAccountABI,
23328
- subAccount,
23329
- [innerData]
23330
- );
23331
- return {
23332
- functionName: "_call",
23333
- args: proxy.args,
23334
- config: { account, to: multiAccount, data: proxy.data, value: 0n }
23335
- };
23336
- }
23337
- function prepareInternalTransfer(multiAccount, account, subAccount, params) {
23338
- validateAmount(params.amount, "transfer amount");
23339
- validateAddress(params.recipient, "recipient");
23340
- const innerData = encodeFunctionData({
23341
- abi: SymmioDiamondABI,
23342
- functionName: "internalTransfer",
23343
- args: [params.recipient, params.amount]
23344
- });
23345
- const proxy = wrapInProxyCall(
23346
- MultiAccountABI,
23347
- subAccount,
23348
- [innerData]
23349
- );
23350
- return {
23351
- functionName: "_call",
23352
- args: proxy.args,
23353
- config: { account, to: multiAccount, data: proxy.data, value: 0n }
23354
- };
23355
- }
23356
- async function allocate(walletClient, publicClient, multiAccount, subAccount, params) {
23357
- const account = walletClient.account?.address;
23358
- if (!account) throw new Error("Wallet client has no account");
23359
- const prepared = prepareAllocate(multiAccount, account, subAccount, params);
23360
- const gas = await publicClient.estimateGas(prepared.config);
23361
- return walletClient.sendTransaction({
23362
- ...prepared.config,
23363
- gas: calculateGasMargin(gas),
23364
- chain: walletClient.chain
23365
- });
23366
- }
23367
- async function deallocate(walletClient, publicClient, multiAccount, subAccount, params) {
23368
- const account = walletClient.account?.address;
23369
- if (!account) throw new Error("Wallet client has no account");
23370
- const prepared = prepareDeallocate(multiAccount, account, subAccount, params);
23371
- const gas = await publicClient.estimateGas(prepared.config);
23372
- return walletClient.sendTransaction({
23373
- ...prepared.config,
23374
- gas: calculateGasMargin(gas),
23375
- chain: walletClient.chain
23376
- });
23377
- }
23378
- async function internalTransfer(walletClient, publicClient, multiAccount, subAccount, params) {
23379
- const account = walletClient.account?.address;
23380
- if (!account) throw new Error("Wallet client has no account");
23381
- const prepared = prepareInternalTransfer(multiAccount, account, subAccount, params);
23382
- const gas = await publicClient.estimateGas(prepared.config);
23383
- return walletClient.sendTransaction({
23384
- ...prepared.config,
23385
- gas: calculateGasMargin(gas),
23386
- chain: walletClient.chain
23387
- });
23388
- }
23389
-
23390
- // src/actions/trade.ts
23391
- var trade_exports = {};
23392
- __export(trade_exports, {
23393
- preparePairTrade: () => preparePairTrade,
23394
- prepareSendQuote: () => prepareSendQuote,
23395
- sendQuote: () => sendQuote
23396
- });
23397
- function buildUpnlSigTuple(sig) {
23398
- return {
23399
- reqId: sig.reqId,
23400
- timestamp: sig.timestamp,
23401
- upnl: sig.upnl,
23402
- price: sig.price,
23403
- gatewaySignature: sig.gatewaySignature,
23404
- sigs: {
23405
- signature: sig.sigs.signature,
23406
- owner: sig.sigs.owner,
23407
- nonce: sig.sigs.nonce
23408
- }
23409
- };
23410
- }
23411
- function prepareSendQuote(multiAccount, account, subAccount, params) {
23412
- validateQuantity(params.quantity);
23413
- const innerData = encodeFunctionData({
23414
- abi: SymmioDiamondABI,
23415
- functionName: "sendQuoteWithAffiliate",
23416
- args: [
23417
- params.partyBsWhiteList,
23418
- BigInt(params.symbolId),
23419
- params.positionType,
23420
- params.orderType,
23421
- params.price,
23422
- params.quantity,
23423
- params.cva,
23424
- params.lf,
23425
- params.partyAmm,
23426
- params.partyBmm,
23427
- params.maxFundingRate,
23428
- params.deadline,
23429
- params.affiliate,
23430
- buildUpnlSigTuple(params.upnlSig)
23431
- ]
23432
- });
23433
- const proxy = wrapInProxyCall(
23434
- MultiAccountABI,
23435
- subAccount,
23436
- [innerData]
23437
- );
23438
- return {
23439
- functionName: "_call",
23440
- args: proxy.args,
23441
- config: { account, to: multiAccount, data: proxy.data, value: 0n }
23442
- };
23443
- }
23444
- function preparePairTrade(multiAccount, account, subAccount, longParams, shortParams) {
23445
- const longData = encodeFunctionData({
23446
- abi: SymmioDiamondABI,
23447
- functionName: "sendQuoteWithAffiliate",
23448
- args: [
23449
- longParams.partyBsWhiteList,
23450
- BigInt(longParams.symbolId),
23451
- longParams.positionType,
23452
- longParams.orderType,
23453
- longParams.price,
23454
- longParams.quantity,
23455
- longParams.cva,
23456
- longParams.lf,
23457
- longParams.partyAmm,
23458
- longParams.partyBmm,
23459
- longParams.maxFundingRate,
23460
- longParams.deadline,
23461
- longParams.affiliate,
23462
- buildUpnlSigTuple(longParams.upnlSig)
23463
- ]
23464
- });
23465
- const shortData = encodeFunctionData({
23466
- abi: SymmioDiamondABI,
23467
- functionName: "sendQuoteWithAffiliate",
23468
- args: [
23469
- shortParams.partyBsWhiteList,
23470
- BigInt(shortParams.symbolId),
23471
- shortParams.positionType,
23472
- shortParams.orderType,
23473
- shortParams.price,
23474
- shortParams.quantity,
23475
- shortParams.cva,
23476
- shortParams.lf,
23477
- shortParams.partyAmm,
23478
- shortParams.partyBmm,
23479
- shortParams.maxFundingRate,
23480
- shortParams.deadline,
23481
- shortParams.affiliate,
23482
- buildUpnlSigTuple(shortParams.upnlSig)
23483
- ]
23484
- });
23485
- const proxy = wrapInProxyCall(
23486
- MultiAccountABI,
23487
- subAccount,
23488
- [longData, shortData]
23489
- );
23490
- return {
23491
- functionName: "_call",
23492
- args: proxy.args,
23493
- config: { account, to: multiAccount, data: proxy.data, value: 0n }
23494
- };
23495
- }
23496
- async function sendQuote(walletClient, publicClient, multiAccount, subAccount, params) {
23497
- const account = walletClient.account?.address;
23498
- if (!account) throw new Error("Wallet client has no account");
23499
- const prepared = prepareSendQuote(multiAccount, account, subAccount, params);
23500
- const gas = await publicClient.estimateGas(prepared.config);
23501
- return walletClient.sendTransaction({
23502
- ...prepared.config,
23503
- gas: calculateGasMargin(gas),
23504
- chain: walletClient.chain
23505
- });
23506
- }
23507
22865
 
23508
- // src/actions/close.ts
23509
- var close_exports = {};
23510
- __export(close_exports, {
23511
- closePosition: () => closePosition,
23512
- prepareClosePosition: () => prepareClosePosition,
23513
- preparePairClose: () => preparePairClose
23514
- });
23515
- function prepareClosePosition(multiAccount, account, subAccount, params) {
23516
- const innerData = encodeFunctionData({
23517
- abi: SymmioDiamondABI,
23518
- functionName: "requestToClosePosition",
23519
- args: [
23520
- params.quoteId,
23521
- params.closePrice,
23522
- params.quantityToClose,
23523
- params.orderType,
23524
- params.deadline
23525
- ]
23526
- });
23527
- const proxy = wrapInProxyCall(
23528
- MultiAccountABI,
23529
- subAccount,
23530
- [innerData]
23531
- );
23532
- return {
23533
- functionName: "_call",
23534
- args: proxy.args,
23535
- config: { account, to: multiAccount, data: proxy.data, value: 0n }
23536
- };
23537
- }
23538
- function preparePairClose(multiAccount, account, subAccount, longClose, shortClose) {
23539
- const longData = encodeFunctionData({
23540
- abi: SymmioDiamondABI,
23541
- functionName: "requestToClosePosition",
23542
- args: [
23543
- longClose.quoteId,
23544
- longClose.closePrice,
23545
- longClose.quantityToClose,
23546
- longClose.orderType,
23547
- longClose.deadline
23548
- ]
23549
- });
23550
- const shortData = encodeFunctionData({
23551
- abi: SymmioDiamondABI,
23552
- functionName: "requestToClosePosition",
23553
- args: [
23554
- shortClose.quoteId,
23555
- shortClose.closePrice,
23556
- shortClose.quantityToClose,
23557
- shortClose.orderType,
23558
- shortClose.deadline
23559
- ]
23560
- });
23561
- const proxy = wrapInProxyCall(
23562
- MultiAccountABI,
23563
- subAccount,
23564
- [longData, shortData]
23565
- );
23566
- return {
23567
- functionName: "_call",
23568
- args: proxy.args,
23569
- config: { account, to: multiAccount, data: proxy.data, value: 0n }
23570
- };
23571
- }
23572
- async function closePosition(walletClient, publicClient, multiAccount, subAccount, params) {
23573
- const account = walletClient.account?.address;
23574
- if (!account) throw new Error("Wallet client has no account");
23575
- const prepared = prepareClosePosition(multiAccount, account, subAccount, params);
23576
- const gas = await publicClient.estimateGas(prepared.config);
23577
- return walletClient.sendTransaction({
23578
- ...prepared.config,
23579
- gas: calculateGasMargin(gas),
23580
- chain: walletClient.chain
23581
- });
23582
- }
23583
-
23584
- // src/actions/cancel.ts
23585
- var cancel_exports = {};
23586
- __export(cancel_exports, {
23587
- cancelCloseRequest: () => cancelCloseRequest,
23588
- cancelQuote: () => cancelQuote,
23589
- forceCancelCloseRequest: () => forceCancelCloseRequest,
23590
- forceCancelQuote: () => forceCancelQuote,
23591
- prepareCancelCloseRequest: () => prepareCancelCloseRequest,
23592
- prepareCancelQuote: () => prepareCancelQuote,
23593
- prepareForceCancelCloseRequest: () => prepareForceCancelCloseRequest,
23594
- prepareForceCancelQuote: () => prepareForceCancelQuote
23595
- });
23596
- function prepareCancelAction(accountDiamond, account, subAccount, functionName, quoteId) {
23597
- const innerData = encodeFunctionData({
23598
- abi: SymmioDiamondABI,
23599
- functionName,
23600
- args: [quoteId]
23601
- });
23602
- const proxy = wrapInProxyCall(
23603
- MultiAccountABI,
23604
- subAccount,
23605
- [innerData]
23606
- );
23607
- return {
23608
- functionName: "_call",
23609
- args: proxy.args,
23610
- config: { account, to: accountDiamond, data: proxy.data, value: 0n }
23611
- };
23612
- }
23613
- async function executeCancelAction(walletClient, publicClient, accountDiamond, subAccount, functionName, quoteId) {
23614
- const account = walletClient.account?.address;
23615
- if (!account) throw new Error("Wallet client has no account");
23616
- const prepared = prepareCancelAction(
23617
- accountDiamond,
23618
- account,
23619
- subAccount,
23620
- functionName,
23621
- quoteId
23622
- );
23623
- const gas = await publicClient.estimateGas(prepared.config);
23624
- return walletClient.sendTransaction({
23625
- ...prepared.config,
23626
- gas: calculateGasMargin(gas),
23627
- chain: walletClient.chain
23628
- });
23629
- }
23630
- function prepareCancelQuote(accountDiamond, account, subAccount, quoteId) {
23631
- return prepareCancelAction(
23632
- accountDiamond,
23633
- account,
23634
- subAccount,
23635
- "requestToCancelQuote",
23636
- quoteId
23637
- );
23638
- }
23639
- function prepareCancelCloseRequest(accountDiamond, account, subAccount, quoteId) {
23640
- return prepareCancelAction(
23641
- accountDiamond,
23642
- account,
23643
- subAccount,
23644
- "requestToCancelCloseRequest",
23645
- quoteId
23646
- );
23647
- }
23648
- function prepareForceCancelQuote(accountDiamond, account, subAccount, quoteId) {
23649
- return prepareCancelAction(
23650
- accountDiamond,
23651
- account,
23652
- subAccount,
23653
- "forceCancelQuote",
23654
- quoteId
23655
- );
23656
- }
23657
- function prepareForceCancelCloseRequest(accountDiamond, account, subAccount, quoteId) {
23658
- return prepareCancelAction(
23659
- accountDiamond,
23660
- account,
23661
- subAccount,
23662
- "forceCancelCloseRequest",
23663
- quoteId
23664
- );
23665
- }
23666
- async function cancelQuote(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
23667
- return executeCancelAction(
23668
- walletClient,
23669
- publicClient,
23670
- accountDiamond,
23671
- subAccount,
23672
- "requestToCancelQuote",
23673
- quoteId
23674
- );
23675
- }
23676
- async function cancelCloseRequest(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
23677
- return executeCancelAction(
23678
- walletClient,
23679
- publicClient,
23680
- accountDiamond,
23681
- subAccount,
23682
- "requestToCancelCloseRequest",
23683
- quoteId
23684
- );
23685
- }
23686
- async function forceCancelQuote(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
23687
- return executeCancelAction(
23688
- walletClient,
23689
- publicClient,
23690
- accountDiamond,
23691
- subAccount,
23692
- "forceCancelQuote",
23693
- quoteId
23694
- );
23695
- }
23696
- async function forceCancelCloseRequest(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
23697
- return executeCancelAction(
23698
- walletClient,
23699
- publicClient,
23700
- accountDiamond,
23701
- subAccount,
23702
- "forceCancelCloseRequest",
23703
- quoteId
23704
- );
23705
- }
23706
-
23707
- // src/actions/approval.ts
23708
- var approval_exports = {};
23709
- __export(approval_exports, {
23710
- ApprovalState: () => ApprovalState,
23711
- approve: () => approve,
23712
- getAllowance: () => getAllowance,
23713
- getApprovalState: () => getApprovalState,
23714
- getBalance: () => getBalance,
23715
- getDecimals: () => getDecimals,
23716
- prepareApprove: () => prepareApprove
23717
- });
23718
-
23719
- // src/abis/ERC20.ts
23720
- var ERC20ABI = [
22866
+ // src/abis/ClearingHouse.ts
22867
+ var ClearingHouseABI = [
22868
+ // ─── Liquidation Lifecycle ────────────────────────────────────
23721
22869
  {
23722
- name: "approve",
22870
+ name: "initiateLiquidation",
23723
22871
  type: "function",
23724
22872
  stateMutability: "nonpayable",
23725
22873
  inputs: [
23726
- { name: "spender", type: "address" },
23727
- { name: "amount", type: "uint256" }
22874
+ { name: "partyA", type: "address" },
22875
+ { name: "partyB", type: "address" }
23728
22876
  ],
23729
- outputs: [{ name: "success", type: "bool" }]
22877
+ outputs: [{ name: "liquidationId", type: "uint256" }]
23730
22878
  },
23731
22879
  {
23732
- name: "allowance",
22880
+ name: "deallocateLiquidation",
23733
22881
  type: "function",
23734
- stateMutability: "view",
23735
- inputs: [
23736
- { name: "owner", type: "address" },
23737
- { name: "spender", type: "address" }
23738
- ],
23739
- outputs: [{ name: "remaining", type: "uint256" }]
22882
+ stateMutability: "nonpayable",
22883
+ inputs: [{ name: "liquidationId", type: "uint256" }],
22884
+ outputs: []
23740
22885
  },
23741
22886
  {
23742
- name: "balanceOf",
22887
+ name: "closePositionsInLiquidation",
23743
22888
  type: "function",
23744
- stateMutability: "view",
23745
- inputs: [{ name: "account", type: "address" }],
23746
- outputs: [{ name: "balance", type: "uint256" }]
22889
+ stateMutability: "nonpayable",
22890
+ inputs: [
22891
+ { name: "liquidationId", type: "uint256" },
22892
+ { name: "quoteIds", type: "uint256[]" },
22893
+ { name: "closePrices", type: "uint256[]" }
22894
+ ],
22895
+ outputs: []
23747
22896
  },
23748
22897
  {
23749
- name: "decimals",
22898
+ name: "distributeLiquidation",
23750
22899
  type: "function",
23751
- stateMutability: "view",
23752
- inputs: [],
23753
- outputs: [{ name: "decimals", type: "uint8" }]
22900
+ stateMutability: "nonpayable",
22901
+ inputs: [{ name: "liquidationId", type: "uint256" }],
22902
+ outputs: []
23754
22903
  },
23755
22904
  {
23756
- name: "symbol",
22905
+ name: "settleLiquidation",
23757
22906
  type: "function",
23758
- stateMutability: "view",
23759
- inputs: [],
23760
- outputs: [{ name: "symbol", type: "string" }]
22907
+ stateMutability: "nonpayable",
22908
+ inputs: [{ name: "liquidationId", type: "uint256" }],
22909
+ outputs: []
23761
22910
  },
22911
+ // ─── Soft Liquidation (v0.8.5) ────────────────────────────────
23762
22912
  {
23763
- name: "totalSupply",
22913
+ name: "applySoftLiquidationPenalty",
23764
22914
  type: "function",
23765
- stateMutability: "view",
23766
- inputs: [],
23767
- outputs: [{ name: "supply", type: "uint256" }]
22915
+ stateMutability: "nonpayable",
22916
+ inputs: [
22917
+ { name: "partyB", type: "address" },
22918
+ { name: "level", type: "uint8" }
22919
+ ],
22920
+ outputs: []
23768
22921
  },
23769
22922
  {
23770
- name: "transfer",
22923
+ name: "setSoftLiquidationThreshold",
23771
22924
  type: "function",
23772
22925
  stateMutability: "nonpayable",
23773
22926
  inputs: [
23774
- { name: "to", type: "address" },
23775
- { name: "amount", type: "uint256" }
22927
+ { name: "level", type: "uint8" },
22928
+ { name: "ratio", type: "uint256" },
22929
+ { name: "penalty", type: "uint256" }
23776
22930
  ],
23777
- outputs: [{ name: "success", type: "bool" }]
22931
+ outputs: []
23778
22932
  },
22933
+ // ─── Auto-Takeover ────────────────────────────────────────────
23779
22934
  {
23780
- name: "mint",
22935
+ name: "autoTakeover",
23781
22936
  type: "function",
23782
22937
  stateMutability: "nonpayable",
23783
22938
  inputs: [
23784
- { name: "to", type: "address" },
23785
- { name: "amount", type: "uint256" }
22939
+ { name: "liquidationId", type: "uint256" },
22940
+ { name: "newPartyB", type: "address" }
23786
22941
  ],
23787
22942
  outputs: []
23788
- }
23789
- ];
23790
-
23791
- // src/actions/approval.ts
23792
- var ApprovalState = /* @__PURE__ */ ((ApprovalState2) => {
23793
- ApprovalState2["UNKNOWN"] = "UNKNOWN";
23794
- ApprovalState2["NOT_APPROVED"] = "NOT_APPROVED";
23795
- ApprovalState2["PENDING"] = "PENDING";
23796
- ApprovalState2["APPROVED"] = "APPROVED";
23797
- return ApprovalState2;
23798
- })(ApprovalState || {});
23799
- function prepareApprove(tokenAddress, account, spender, amount) {
23800
- validateAddress(spender, "spender");
23801
- const data = encodeFunctionData({
23802
- abi: ERC20ABI,
23803
- functionName: "approve",
23804
- args: [spender, amount]
23805
- });
23806
- return {
23807
- functionName: "approve",
23808
- args: [spender, amount],
23809
- config: { account, to: tokenAddress, data, value: 0n }
23810
- };
23811
- }
23812
- async function approve(walletClient, publicClient, tokenAddress, spender, amount) {
23813
- const account = walletClient.account?.address;
23814
- if (!account) throw new Error("Wallet client has no account");
23815
- const prepared = prepareApprove(tokenAddress, account, spender, amount);
23816
- const gas = await publicClient.estimateGas(prepared.config);
23817
- return walletClient.sendTransaction({
23818
- ...prepared.config,
23819
- gas: calculateGasMargin(gas),
23820
- chain: walletClient.chain
23821
- });
23822
- }
23823
- async function getAllowance(publicClient, tokenAddress, owner, spender) {
23824
- return await publicClient.readContract({
23825
- address: tokenAddress,
23826
- abi: ERC20ABI,
23827
- functionName: "allowance",
23828
- args: [owner, spender]
23829
- });
23830
- }
23831
- async function getBalance(publicClient, tokenAddress, account) {
23832
- return await publicClient.readContract({
23833
- address: tokenAddress,
23834
- abi: ERC20ABI,
23835
- functionName: "balanceOf",
23836
- args: [account]
23837
- });
23838
- }
23839
- async function getDecimals(publicClient, tokenAddress) {
23840
- return await publicClient.readContract({
23841
- address: tokenAddress,
23842
- abi: ERC20ABI,
23843
- functionName: "decimals"
23844
- });
23845
- }
23846
- async function getApprovalState(publicClient, tokenAddress, owner, spender, requiredAmount) {
23847
- try {
23848
- const allowance = await getAllowance(publicClient, tokenAddress, owner, spender);
23849
- if (allowance >= requiredAmount) {
23850
- return "APPROVED" /* APPROVED */;
23851
- }
23852
- return "NOT_APPROVED" /* NOT_APPROVED */;
23853
- } catch {
23854
- return "UNKNOWN" /* UNKNOWN */;
23855
- }
23856
- }
23857
-
23858
- // src/actions/delegation.ts
23859
- var delegation_exports = {};
23860
- __export(delegation_exports, {
23861
- delegateAccess: () => delegateAccess,
23862
- hasDelegatedAccess: () => hasDelegatedAccess,
23863
- prepareDelegateAccess: () => prepareDelegateAccess,
23864
- prepareProposeRevoke: () => prepareProposeRevoke,
23865
- prepareRevokeAccess: () => prepareRevokeAccess,
23866
- proposeRevoke: () => proposeRevoke,
23867
- revokeAccess: () => revokeAccess
23868
- });
23869
- function prepareDelegateAccess(multiAccount, account, params) {
23870
- validateAddress(params.account, "subAccount");
23871
- validateAddress(params.target, "target");
23872
- const data = encodeFunctionData({
23873
- abi: MultiAccountABI,
23874
- functionName: "delegateAccesses",
23875
- args: [params.account, params.target, params.selectors, params.activate]
23876
- });
23877
- return {
23878
- functionName: "delegateAccesses",
23879
- args: [params.account, params.target, params.selectors, params.activate],
23880
- config: { account, to: multiAccount, data, value: 0n }
23881
- };
23882
- }
23883
- function prepareProposeRevoke(multiAccount, account, params) {
23884
- const data = encodeFunctionData({
23885
- abi: MultiAccountABI,
23886
- functionName: "proposeToRevokeAccesses",
23887
- args: [params.account, params.target, params.selectors]
23888
- });
23889
- return {
23890
- functionName: "proposeToRevokeAccesses",
23891
- args: [params.account, params.target, params.selectors],
23892
- config: { account, to: multiAccount, data, value: 0n }
23893
- };
23894
- }
23895
- function prepareRevokeAccess(multiAccount, account, params) {
23896
- const data = encodeFunctionData({
23897
- abi: MultiAccountABI,
23898
- functionName: "revokeAccesses",
23899
- args: [params.account, params.target, params.selectors]
23900
- });
23901
- return {
23902
- functionName: "revokeAccesses",
23903
- args: [params.account, params.target, params.selectors],
23904
- config: { account, to: multiAccount, data, value: 0n }
23905
- };
23906
- }
23907
- async function delegateAccess(walletClient, publicClient, multiAccount, params) {
23908
- const account = walletClient.account?.address;
23909
- if (!account) throw new Error("Wallet client has no account");
23910
- const prepared = prepareDelegateAccess(multiAccount, account, params);
23911
- const gas = await publicClient.estimateGas(prepared.config);
23912
- return walletClient.sendTransaction({
23913
- ...prepared.config,
23914
- gas: calculateGasMargin(gas),
23915
- chain: walletClient.chain
23916
- });
23917
- }
23918
- async function proposeRevoke(walletClient, publicClient, multiAccount, params) {
23919
- const account = walletClient.account?.address;
23920
- if (!account) throw new Error("Wallet client has no account");
23921
- const prepared = prepareProposeRevoke(multiAccount, account, params);
23922
- const gas = await publicClient.estimateGas(prepared.config);
23923
- return walletClient.sendTransaction({
23924
- ...prepared.config,
23925
- gas: calculateGasMargin(gas),
23926
- chain: walletClient.chain
23927
- });
23928
- }
23929
- async function revokeAccess(walletClient, publicClient, multiAccount, params) {
23930
- const account = walletClient.account?.address;
23931
- if (!account) throw new Error("Wallet client has no account");
23932
- const prepared = prepareRevokeAccess(multiAccount, account, params);
23933
- const gas = await publicClient.estimateGas(prepared.config);
23934
- return walletClient.sendTransaction({
23935
- ...prepared.config,
23936
- gas: calculateGasMargin(gas),
23937
- chain: walletClient.chain
23938
- });
23939
- }
23940
- async function hasDelegatedAccess(publicClient, multiAccount, params) {
23941
- validateAddress(params.account, "subAccount");
23942
- validateAddress(params.target, "target");
23943
- const result = await publicClient.readContract({
23944
- address: multiAccount,
23945
- abi: MultiAccountABI,
23946
- functionName: "delegatedAccesses",
23947
- args: [params.account, params.target, params.selector]
23948
- });
23949
- return Boolean(result);
23950
- }
23951
-
23952
- // src/actions/signature.ts
23953
- var signature_exports = {};
23954
- __export(signature_exports, {
23955
- getCurrentMessage: () => getCurrentMessage,
23956
- hasSignedCurrentVersion: () => hasSignedCurrentVersion,
23957
- prepareStoreSignature: () => prepareStoreSignature,
23958
- signTermsMessage: () => signTermsMessage,
23959
- storeSignature: () => storeSignature
23960
- });
23961
-
23962
- // src/abis/SignatureStore.ts
23963
- var SignatureStoreABI = [
22943
+ },
22944
+ // ─── ADL Assurance ────────────────────────────────────────────
23964
22945
  {
23965
- name: "storeSignatureForCurrentVersion",
22946
+ name: "depositADLAssurance",
23966
22947
  type: "function",
23967
22948
  stateMutability: "nonpayable",
23968
- inputs: [{ name: "signature", type: "bytes" }],
22949
+ inputs: [
22950
+ { name: "partyB", type: "address" },
22951
+ { name: "amount", type: "uint256" }
22952
+ ],
23969
22953
  outputs: []
23970
22954
  },
23971
22955
  {
23972
- name: "hasCurrentVersionSignature",
22956
+ name: "slashADLAssurance",
23973
22957
  type: "function",
23974
- stateMutability: "view",
23975
- inputs: [{ name: "user", type: "address" }],
23976
- outputs: [{ name: "hasSigned", type: "bool" }]
22958
+ stateMutability: "nonpayable",
22959
+ inputs: [{ name: "partyB", type: "address" }],
22960
+ outputs: []
23977
22961
  },
22962
+ // ─── Insurance Vault ──────────────────────────────────────────
23978
22963
  {
23979
- name: "getSignature",
22964
+ name: "setMaxLiquidatorProfit",
23980
22965
  type: "function",
23981
- stateMutability: "view",
23982
- inputs: [
23983
- { name: "version", type: "uint256" },
23984
- { name: "user", type: "address" }
23985
- ],
23986
- outputs: [{ name: "signature", type: "bytes" }]
22966
+ stateMutability: "nonpayable",
22967
+ inputs: [{ name: "maxProfit", type: "uint256" }],
22968
+ outputs: []
23987
22969
  },
23988
22970
  {
23989
- name: "getCurrentVersionMessage",
22971
+ name: "reimbursePartyB",
23990
22972
  type: "function",
23991
- stateMutability: "view",
23992
- inputs: [],
23993
- outputs: [{ name: "message", type: "string" }]
22973
+ stateMutability: "nonpayable",
22974
+ inputs: [
22975
+ { name: "partyB", type: "address" },
22976
+ { name: "amount", type: "uint256" }
22977
+ ],
22978
+ outputs: []
23994
22979
  },
22980
+ // ─── View Functions ───────────────────────────────────────────
23995
22981
  {
23996
- name: "getCurrentVersion",
22982
+ name: "getLiquidation",
23997
22983
  type: "function",
23998
22984
  stateMutability: "view",
23999
- inputs: [],
24000
- outputs: [{ name: "version", type: "uint256" }]
22985
+ inputs: [{ name: "liquidationId", type: "uint256" }],
22986
+ outputs: [
22987
+ {
22988
+ name: "liquidation",
22989
+ type: "tuple",
22990
+ components: [
22991
+ { name: "id", type: "uint256" },
22992
+ { name: "partyA", type: "address" },
22993
+ { name: "partyB", type: "address" },
22994
+ { name: "status", type: "uint8" },
22995
+ { name: "deallocatedAmount", type: "uint256" },
22996
+ { name: "settledAmount", type: "uint256" },
22997
+ { name: "createdAt", type: "uint256" }
22998
+ ]
22999
+ }
23000
+ ]
23001
+ },
23002
+ // ─── Events ───────────────────────────────────────────────────
23003
+ {
23004
+ name: "LiquidationInitiated",
23005
+ type: "event",
23006
+ inputs: [
23007
+ { name: "liquidationId", type: "uint256", indexed: true },
23008
+ { name: "partyA", type: "address", indexed: true },
23009
+ { name: "partyB", type: "address", indexed: true }
23010
+ ]
23011
+ },
23012
+ {
23013
+ name: "LiquidationSettled",
23014
+ type: "event",
23015
+ inputs: [
23016
+ { name: "liquidationId", type: "uint256", indexed: true }
23017
+ ]
23018
+ },
23019
+ {
23020
+ name: "SoftLiquidationPenalty",
23021
+ type: "event",
23022
+ inputs: [
23023
+ { name: "partyB", type: "address", indexed: true },
23024
+ { name: "level", type: "uint8", indexed: false },
23025
+ { name: "penalty", type: "uint256", indexed: false }
23026
+ ]
24001
23027
  }
24002
23028
  ];
24003
23029
 
24004
- // src/actions/signature.ts
24005
- function prepareStoreSignature(signatureStore, account, signature) {
24006
- const data = encodeFunctionData({
24007
- abi: SignatureStoreABI,
24008
- functionName: "storeSignatureForCurrentVersion",
24009
- args: [signature]
24010
- });
24011
- return {
24012
- functionName: "storeSignatureForCurrentVersion",
24013
- args: [signature],
24014
- config: { account, to: signatureStore, data, value: 0n }
24015
- };
24016
- }
24017
- async function storeSignature(walletClient, publicClient, signatureStore, signature) {
24018
- const account = walletClient.account?.address;
24019
- if (!account) throw new Error("Wallet client has no account");
24020
- const prepared = prepareStoreSignature(signatureStore, account, signature);
24021
- const gas = await publicClient.estimateGas(prepared.config);
24022
- return walletClient.sendTransaction({
24023
- ...prepared.config,
24024
- gas: calculateGasMargin(gas),
24025
- chain: walletClient.chain
24026
- });
24027
- }
24028
- async function signTermsMessage(walletClient, publicClient, signatureStore) {
24029
- const account = walletClient.account;
24030
- if (!account) throw new Error("Wallet client has no account");
24031
- const message = await publicClient.readContract({
24032
- address: signatureStore,
24033
- abi: SignatureStoreABI,
24034
- functionName: "getCurrentVersionMessage"
24035
- });
24036
- return walletClient.signMessage({
24037
- account,
24038
- message
24039
- });
24040
- }
24041
- async function hasSignedCurrentVersion(publicClient, signatureStore, user) {
24042
- return await publicClient.readContract({
24043
- address: signatureStore,
24044
- abi: SignatureStoreABI,
24045
- functionName: "hasCurrentVersionSignature",
24046
- args: [user]
24047
- });
24048
- }
24049
- async function getCurrentMessage(publicClient, signatureStore) {
24050
- return await publicClient.readContract({
24051
- address: signatureStore,
24052
- abi: SignatureStoreABI,
24053
- functionName: "getCurrentVersionMessage"
24054
- });
24055
- }
24056
-
24057
- // src/actions/admin.ts
24058
- var admin_exports = {};
24059
- __export(admin_exports, {
24060
- grantRole: () => grantRole,
24061
- prepareGrantRole: () => prepareGrantRole,
24062
- prepareRevokeRole: () => prepareRevokeRole,
24063
- revokeRole: () => revokeRole
24064
- });
24065
- function prepareGrantRole(symmioDiamond, account, role, grantee) {
24066
- validateAddress(grantee, "grantee");
24067
- const data = encodeFunctionData({
24068
- abi: SymmioDiamondABI,
24069
- functionName: "grantRole",
24070
- args: [grantee, role]
24071
- });
24072
- return {
24073
- functionName: "grantRole",
24074
- args: [grantee, role],
24075
- config: { account, to: symmioDiamond, data, value: 0n }
24076
- };
24077
- }
24078
- function prepareRevokeRole(symmioDiamond, account, role, revokee) {
24079
- validateAddress(revokee, "revokee");
24080
- const data = encodeFunctionData({
24081
- abi: SymmioDiamondABI,
24082
- functionName: "revokeRole",
24083
- args: [revokee, role]
24084
- });
24085
- return {
24086
- functionName: "revokeRole",
24087
- args: [revokee, role],
24088
- config: { account, to: symmioDiamond, data, value: 0n }
24089
- };
24090
- }
24091
- async function grantRole(walletClient, publicClient, symmioDiamond, role, grantee) {
24092
- const account = walletClient.account?.address;
24093
- if (!account) throw new Error("Wallet client has no account");
24094
- const prepared = prepareGrantRole(symmioDiamond, account, role, grantee);
24095
- const gas = await publicClient.estimateGas(prepared.config);
24096
- return walletClient.sendTransaction({
24097
- ...prepared.config,
24098
- gas: calculateGasMargin(gas),
24099
- chain: walletClient.chain
24100
- });
24101
- }
24102
- async function revokeRole(walletClient, publicClient, symmioDiamond, role, revokee) {
24103
- const account = walletClient.account?.address;
24104
- if (!account) throw new Error("Wallet client has no account");
24105
- const prepared = prepareRevokeRole(symmioDiamond, account, role, revokee);
24106
- const gas = await publicClient.estimateGas(prepared.config);
24107
- return walletClient.sendTransaction({
24108
- ...prepared.config,
24109
- gas: calculateGasMargin(gas),
24110
- chain: walletClient.chain
24111
- });
24112
- }
23030
+ // src/abis/MuonVerifier.ts
23031
+ var MuonVerifierABI = [
23032
+ {
23033
+ name: "addSignatureKey",
23034
+ type: "function",
23035
+ stateMutability: "nonpayable",
23036
+ inputs: [
23037
+ { name: "publicKey", type: "address" },
23038
+ { name: "nodeId", type: "bytes32" }
23039
+ ],
23040
+ outputs: []
23041
+ },
23042
+ {
23043
+ name: "removeSignatureKey",
23044
+ type: "function",
23045
+ stateMutability: "nonpayable",
23046
+ inputs: [{ name: "publicKey", type: "address" }],
23047
+ outputs: []
23048
+ },
23049
+ {
23050
+ name: "rotateSignatureKey",
23051
+ type: "function",
23052
+ stateMutability: "nonpayable",
23053
+ inputs: [
23054
+ { name: "oldKey", type: "address" },
23055
+ { name: "newKey", type: "address" }
23056
+ ],
23057
+ outputs: []
23058
+ },
23059
+ {
23060
+ name: "isValidKey",
23061
+ type: "function",
23062
+ stateMutability: "view",
23063
+ inputs: [{ name: "publicKey", type: "address" }],
23064
+ outputs: [{ name: "valid", type: "bool" }]
23065
+ },
23066
+ {
23067
+ name: "getActiveKeys",
23068
+ type: "function",
23069
+ stateMutability: "view",
23070
+ inputs: [],
23071
+ outputs: [{ name: "keys", type: "address[]" }]
23072
+ }
23073
+ ];
24113
23074
 
24114
- // src/actions/instant.ts
24115
- var instant_exports = {};
24116
- __export(instant_exports, {
24117
- cancelInstantClose: () => cancelInstantClose,
24118
- createSiweMessage: () => createSiweMessage,
24119
- getNonce: () => getNonce,
24120
- getOpenInstantCloses: () => getOpenInstantCloses,
24121
- instantClose: () => instantClose,
24122
- instantOpen: () => instantOpen,
24123
- login: () => login
24124
- });
24125
- function getHedgerBaseUrl(chainId) {
24126
- const baseUrl = HEDGER_BASE_URLS[chainId];
24127
- if (!baseUrl) {
24128
- throw new Error(`No hedger base URL configured for chain ${chainId}.`);
23075
+ // src/abis/SignatureStore.ts
23076
+ var SignatureStoreABI = [
23077
+ {
23078
+ name: "storeSignatureForCurrentVersion",
23079
+ type: "function",
23080
+ stateMutability: "nonpayable",
23081
+ inputs: [{ name: "signature", type: "bytes" }],
23082
+ outputs: []
23083
+ },
23084
+ {
23085
+ name: "hasCurrentVersionSignature",
23086
+ type: "function",
23087
+ stateMutability: "view",
23088
+ inputs: [{ name: "user", type: "address" }],
23089
+ outputs: [{ name: "hasSigned", type: "bool" }]
23090
+ },
23091
+ {
23092
+ name: "getSignature",
23093
+ type: "function",
23094
+ stateMutability: "view",
23095
+ inputs: [
23096
+ { name: "version", type: "uint256" },
23097
+ { name: "user", type: "address" }
23098
+ ],
23099
+ outputs: [{ name: "signature", type: "bytes" }]
23100
+ },
23101
+ {
23102
+ name: "getCurrentVersionMessage",
23103
+ type: "function",
23104
+ stateMutability: "view",
23105
+ inputs: [],
23106
+ outputs: [{ name: "message", type: "string" }]
23107
+ },
23108
+ {
23109
+ name: "getCurrentVersion",
23110
+ type: "function",
23111
+ stateMutability: "view",
23112
+ inputs: [],
23113
+ outputs: [{ name: "version", type: "uint256" }]
24129
23114
  }
24130
- return baseUrl;
24131
- }
24132
- function createSiweMessage(params) {
24133
- const version = params.version ?? "1";
24134
- const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
24135
- const expirationTime = new Date(
24136
- Date.now() + 30 * 24 * 60 * 60 * 1e3
24137
- ).toISOString();
24138
- const message = [
24139
- `${params.domain} wants you to sign in with your Ethereum account:`,
24140
- params.address,
24141
- "",
24142
- params.statement,
24143
- "",
24144
- `URI: ${params.uri}`,
24145
- `Version: ${version}`,
24146
- `Chain ID: ${params.chainId}`,
24147
- `Nonce: ${params.nonce}`,
24148
- `Issued At: ${issuedAt}`,
24149
- `Expiration Time: ${expirationTime}`
24150
- ].join("\n");
24151
- return { message, issuedAt, expirationTime };
24152
- }
24153
- async function getNonce(chainId, subAccount) {
24154
- const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24155
- const url = new URL(`nonce/${subAccount}`, hedgerBaseUrl).href;
24156
- const response = await fetch(url);
24157
- if (!response.ok) {
24158
- throw new Error(`Failed to fetch nonce: ${response.statusText}`);
23115
+ ];
23116
+
23117
+ // src/abis/ERC20.ts
23118
+ var ERC20ABI = [
23119
+ {
23120
+ name: "approve",
23121
+ type: "function",
23122
+ stateMutability: "nonpayable",
23123
+ inputs: [
23124
+ { name: "spender", type: "address" },
23125
+ { name: "amount", type: "uint256" }
23126
+ ],
23127
+ outputs: [{ name: "success", type: "bool" }]
23128
+ },
23129
+ {
23130
+ name: "allowance",
23131
+ type: "function",
23132
+ stateMutability: "view",
23133
+ inputs: [
23134
+ { name: "owner", type: "address" },
23135
+ { name: "spender", type: "address" }
23136
+ ],
23137
+ outputs: [{ name: "remaining", type: "uint256" }]
23138
+ },
23139
+ {
23140
+ name: "balanceOf",
23141
+ type: "function",
23142
+ stateMutability: "view",
23143
+ inputs: [{ name: "account", type: "address" }],
23144
+ outputs: [{ name: "balance", type: "uint256" }]
23145
+ },
23146
+ {
23147
+ name: "decimals",
23148
+ type: "function",
23149
+ stateMutability: "view",
23150
+ inputs: [],
23151
+ outputs: [{ name: "decimals", type: "uint8" }]
23152
+ },
23153
+ {
23154
+ name: "symbol",
23155
+ type: "function",
23156
+ stateMutability: "view",
23157
+ inputs: [],
23158
+ outputs: [{ name: "symbol", type: "string" }]
23159
+ },
23160
+ {
23161
+ name: "totalSupply",
23162
+ type: "function",
23163
+ stateMutability: "view",
23164
+ inputs: [],
23165
+ outputs: [{ name: "supply", type: "uint256" }]
23166
+ },
23167
+ {
23168
+ name: "transfer",
23169
+ type: "function",
23170
+ stateMutability: "nonpayable",
23171
+ inputs: [
23172
+ { name: "to", type: "address" },
23173
+ { name: "amount", type: "uint256" }
23174
+ ],
23175
+ outputs: [{ name: "success", type: "bool" }]
23176
+ },
23177
+ {
23178
+ name: "mint",
23179
+ type: "function",
23180
+ stateMutability: "nonpayable",
23181
+ inputs: [
23182
+ { name: "to", type: "address" },
23183
+ { name: "amount", type: "uint256" }
23184
+ ],
23185
+ outputs: []
24159
23186
  }
24160
- const data = await response.json();
24161
- return data.nonce;
23187
+ ];
23188
+
23189
+ // src/constants/chains.ts
23190
+ var SupportedChainId = /* @__PURE__ */ ((SupportedChainId2) => {
23191
+ SupportedChainId2[SupportedChainId2["ARBITRUM"] = 42161] = "ARBITRUM";
23192
+ SupportedChainId2[SupportedChainId2["BASE"] = 8453] = "BASE";
23193
+ SupportedChainId2[SupportedChainId2["BSC"] = 56] = "BSC";
23194
+ SupportedChainId2[SupportedChainId2["POLYGON"] = 137] = "POLYGON";
23195
+ SupportedChainId2[SupportedChainId2["MAINNET"] = 1] = "MAINNET";
23196
+ return SupportedChainId2;
23197
+ })(SupportedChainId || {});
23198
+ var V3_CHAIN_IDS = [
23199
+ 42161 /* ARBITRUM */,
23200
+ 8453 /* BASE */
23201
+ ];
23202
+ var FALLBACK_CHAIN_ID = 42161 /* ARBITRUM */;
23203
+ var CHAIN_NAMES = {
23204
+ [42161 /* ARBITRUM */]: "Arbitrum One",
23205
+ [8453 /* BASE */]: "Base",
23206
+ [56 /* BSC */]: "BNB Chain",
23207
+ [137 /* POLYGON */]: "Polygon",
23208
+ [1 /* MAINNET */]: "Ethereum"
23209
+ };
23210
+
23211
+ // src/constants/addresses.ts
23212
+ var MULTI_ACCOUNT_ADDRESS = {
23213
+ [42161 /* ARBITRUM */]: "0x6273242a7E88b3De90822b31648C212215caaFE4",
23214
+ [8453 /* BASE */]: "0xE43166cE17d3511B09438a359dAa53513225101D"
23215
+ };
23216
+ var SYMMIO_DIAMOND_ADDRESS = {
23217
+ [42161 /* ARBITRUM */]: "0x8F06459f184553e5d04F07F868720BDaCAB39395",
23218
+ [8453 /* BASE */]: "0x91Cf2D8Ed503EC52768999aA6D8DBeA6e52dbe43"
23219
+ };
23220
+ var COLLATERAL_ADDRESS = {
23221
+ [42161 /* ARBITRUM */]: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
23222
+ [8453 /* BASE */]: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
23223
+ };
23224
+ var CLEARING_HOUSE_ADDRESS = {
23225
+ [42161 /* ARBITRUM */]: "0x0000000000000000000000000000000000000000",
23226
+ [8453 /* BASE */]: "0x0000000000000000000000000000000000000000"
23227
+ };
23228
+ var SIGNATURE_STORE_ADDRESS = {
23229
+ [42161 /* ARBITRUM */]: "0x94eEa58De1C8945c342dB4bE9670301638E403e2"
23230
+ };
23231
+ var DEFAULT_PARTY_B_ADDRESS = {
23232
+ [42161 /* ARBITRUM */]: "0x00c069d68bc7420740460DBC3cc3fFF9b3742421",
23233
+ [8453 /* BASE */]: "0x1EcAbF0Eba136920677C9575FAccee36f30592cf"
23234
+ };
23235
+ var COLLATERAL_DECIMALS = {
23236
+ [42161 /* ARBITRUM */]: 6,
23237
+ [8453 /* BASE */]: 6
23238
+ };
23239
+ function getAddress(addressMap, chainId, name) {
23240
+ const addr = addressMap[chainId];
23241
+ if (!addr || addr === "0x0000000000000000000000000000000000000000") {
23242
+ throw new Error(`${name} address not configured for chain ${chainId}`);
23243
+ }
23244
+ return addr;
24162
23245
  }
24163
- async function login(chainId, params) {
24164
- const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24165
- const url = new URL("login", hedgerBaseUrl).href;
24166
- const body = {
24167
- account_address: params.accountAddress,
24168
- expiration_time: params.expirationTime,
24169
- issued_at: params.issuedAt,
24170
- signature: params.signature,
24171
- nonce: params.nonce
24172
- };
24173
- const response = await fetch(url, {
24174
- method: "POST",
24175
- headers: { "Content-Type": "application/json" },
24176
- body: JSON.stringify(body)
24177
- });
24178
- if (!response.ok) {
24179
- const errorData = await response.json().catch(() => null);
24180
- throw new Error(
24181
- errorData?.error_message ?? `Login failed: ${response.statusText}`
24182
- );
23246
+
23247
+ // src/constants/selectors.ts
23248
+ var SEND_QUOTE_WITH_AFFILIATE_SELECTOR = "0x40f1310c";
23249
+ var CLOSE_QUOTE_SELECTOR = "0x501e891f";
23250
+ var ALL_TRADING_SELECTORS = [
23251
+ SEND_QUOTE_WITH_AFFILIATE_SELECTOR,
23252
+ CLOSE_QUOTE_SELECTOR
23253
+ ];
23254
+
23255
+ // src/constants/defaults.ts
23256
+ var MARKET_ORDER_DEADLINE = 300n;
23257
+ var LIMIT_ORDER_DEADLINE = 311040120n;
23258
+ var MARKET_PRICE_COEFFICIENT = 1.01;
23259
+ var MAX_LEVERAGE = 50;
23260
+ var DEFAULT_PRECISION = 2;
23261
+ var GAS_MARGIN_PERCENTAGE = 20n;
23262
+ var STANDARD_WITHDRAW_COOLDOWN = 43200;
23263
+ var MUON_BASE_URLS = [
23264
+ "https://muon-oracle1.rasa.capital/v1/",
23265
+ "https://muon-oracle2.rasa.capital/v1/",
23266
+ "https://muon-oracle3.rasa.capital/v1/",
23267
+ "https://muon-oracle4.rasa.capital/v1/"
23268
+ ];
23269
+ var MUON_APP_NAME = "symmio";
23270
+ var MUON_REQUEST_TIMEOUT = 15e3;
23271
+ var HEDGER_BASE_URLS = {
23272
+ [42161 /* ARBITRUM */]: "https://www.perps-streaming.com/v1/42161a/0x6273242a7E88b3De90822b31648C212215caaFE4",
23273
+ [8453 /* BASE */]: "https://www.perps-streaming.com/v1/8453a/0x6273242a7E88b3De90822b31648C212215caaFE4"
23274
+ };
23275
+ var SymmioSDKError = class extends Error {
23276
+ constructor(message, code) {
23277
+ super(message);
23278
+ this.code = code;
23279
+ this.name = "SymmioSDKError";
24183
23280
  }
24184
- const data = await response.json();
24185
- if (!data.access_token) {
24186
- throw new Error("No access token received");
23281
+ };
23282
+ function validateAddress(address, name) {
23283
+ if (!isAddress(address)) {
23284
+ throw new SymmioSDKError(
23285
+ `Invalid ${name} address: ${address}`,
23286
+ "INVALID_ADDRESS"
23287
+ );
24187
23288
  }
24188
- return {
24189
- accessToken: data.access_token,
24190
- expirationTime: params.expirationTime,
24191
- issuedAt: params.issuedAt
24192
- };
23289
+ return address;
24193
23290
  }
24194
- async function instantOpen(chainId, params, accessToken) {
24195
- const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24196
- const url = new URL("instant_open", hedgerBaseUrl).href;
24197
- const body = {
24198
- symbolId: params.symbolId,
24199
- positionType: params.positionType,
24200
- orderType: params.orderType,
24201
- price: params.price,
24202
- quantity: params.quantity,
24203
- cva: params.cva,
24204
- lf: params.lf,
24205
- partyAmm: params.partyAmm,
24206
- partyBmm: params.partyBmm,
24207
- maxFundingRate: params.maxFundingRate,
24208
- deadline: params.deadline
24209
- };
24210
- const response = await fetch(url, {
24211
- method: "POST",
24212
- headers: {
24213
- "Content-Type": "application/json",
24214
- Authorization: `Bearer ${accessToken}`
24215
- },
24216
- body: JSON.stringify(body)
24217
- });
24218
- if (!response.ok) {
24219
- const errorData = await response.json().catch(() => null);
24220
- throw new Error(
24221
- errorData?.error_message ?? `Instant open failed: ${response.statusText}`
23291
+ function validateAmount(amount, name) {
23292
+ if (amount <= 0n) {
23293
+ throw new SymmioSDKError(
23294
+ `${name} must be a positive amount, got ${amount}`,
23295
+ "INVALID_AMOUNT"
24222
23296
  );
24223
23297
  }
24224
- return response.json();
24225
23298
  }
24226
- async function instantClose(chainId, params, accessToken) {
24227
- const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24228
- const url = new URL("instant_close", hedgerBaseUrl).href;
24229
- const body = {
24230
- quote_id: params.quoteId,
24231
- quantity_to_close: params.quantityToClose,
24232
- close_price: params.closePrice
24233
- };
24234
- const response = await fetch(url, {
24235
- method: "POST",
24236
- headers: {
24237
- "Content-Type": "application/json",
24238
- Authorization: `Bearer ${accessToken}`
24239
- },
24240
- body: JSON.stringify(body)
24241
- });
24242
- if (!response.ok) {
24243
- const errorData = await response.json().catch(() => null);
24244
- throw new Error(
24245
- errorData?.error_message ?? `Instant close failed: ${response.statusText}`
23299
+ function validateChainId(chainId, supportedChains) {
23300
+ if (!supportedChains.includes(chainId)) {
23301
+ throw new SymmioSDKError(
23302
+ `Chain ${chainId} is not supported. Supported: ${supportedChains.join(", ")}`,
23303
+ "UNSUPPORTED_CHAIN"
24246
23304
  );
24247
23305
  }
24248
- return response.json();
24249
23306
  }
24250
- async function cancelInstantClose(chainId, quoteId, accessToken) {
24251
- const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24252
- const url = new URL(`instant_close/${quoteId}`, hedgerBaseUrl).href;
24253
- const response = await fetch(url, {
24254
- method: "DELETE",
24255
- headers: {
24256
- "Content-Type": "application/json",
24257
- Authorization: `Bearer ${accessToken}`
24258
- }
24259
- });
24260
- if (!response.ok) {
24261
- const errorData = await response.json().catch(() => null);
24262
- throw new Error(
24263
- errorData?.error_message ?? `Cancel instant close failed: ${response.statusText}`
23307
+ function validateDeadline(deadline) {
23308
+ const now = BigInt(Math.floor(Date.now() / 1e3));
23309
+ if (deadline <= now) {
23310
+ throw new SymmioSDKError(
23311
+ `Deadline ${deadline} is in the past (current: ${now})`,
23312
+ "EXPIRED_DEADLINE"
24264
23313
  );
24265
23314
  }
24266
23315
  }
24267
- async function getOpenInstantCloses(chainId, account, accessToken) {
24268
- const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24269
- const url = new URL(`instant_close/${account}`, hedgerBaseUrl).href;
24270
- const response = await fetch(url, {
24271
- headers: {
24272
- Authorization: `Bearer ${accessToken}`
24273
- }
24274
- });
24275
- if (!response.ok) {
24276
- const errorData = await response.json().catch(() => null);
24277
- throw new Error(
24278
- errorData?.error_message ?? `Failed to fetch instant closes: ${response.statusText}`
23316
+ function validateQuantity(quantity) {
23317
+ if (quantity <= 0n) {
23318
+ throw new SymmioSDKError(
23319
+ `Quantity must be positive, got ${quantity}`,
23320
+ "INVALID_QUANTITY"
24279
23321
  );
24280
23322
  }
24281
- return response.json();
24282
23323
  }
24283
23324
 
24284
- // src/actions/stats.ts
24285
- var stats_exports = {};
24286
- __export(stats_exports, {
24287
- calculateAvailableForOrder: () => calculateAvailableForOrder,
24288
- getPartyAStats: () => getPartyAStats
24289
- });
24290
- async function getPartyAStats(publicClient, symmioDiamond, partyA) {
24291
- const result = await publicClient.readContract({
24292
- address: symmioDiamond,
24293
- abi: SymmioDiamondABI,
24294
- functionName: "partyAStats",
24295
- args: [partyA]
24296
- });
23325
+ // src/clients/muon.ts
23326
+ function parseSchnorrSign(sigs) {
24297
23327
  return {
24298
- collateralBalance: result[1],
24299
- allocatedBalance: result[2],
24300
- availableBalance: result[3],
24301
- lockedCVA: result[4],
24302
- lockedLF: result[5],
24303
- lockedPartyAMM: result[6],
24304
- lockedPartyBMM: result[7],
24305
- pendingLockedCVA: result[8],
24306
- pendingLockedLF: result[9],
24307
- pendingLockedPartyAMM: result[10],
24308
- pendingLockedPartyBMM: result[11],
24309
- positionsCount: Number(result[12]),
24310
- pendingCount: Number(result[13]),
24311
- nonces: 0
23328
+ signature: BigInt(sigs.signature),
23329
+ owner: sigs.owner,
23330
+ nonce: sigs.nonce
24312
23331
  };
24313
23332
  }
24314
- function calculateAvailableForOrder(stats, upnl) {
24315
- const {
24316
- allocatedBalance,
24317
- lockedCVA,
24318
- lockedLF,
24319
- lockedPartyAMM,
24320
- pendingLockedCVA,
24321
- pendingLockedLF,
24322
- pendingLockedPartyAMM
24323
- } = stats;
24324
- const totalPendingLocked = pendingLockedCVA + pendingLockedLF + pendingLockedPartyAMM;
24325
- if (upnl >= 0n) {
24326
- const totalLocked = lockedCVA + lockedLF + lockedPartyAMM;
24327
- return allocatedBalance + upnl - totalLocked - totalPendingLocked;
23333
+ function parseSingleUpnlSig(result) {
23334
+ const data = result["result"];
23335
+ if (!data) {
23336
+ throw new SymmioSDKError("Invalid Muon response: missing result", "MUON_PARSE_ERROR");
24328
23337
  }
24329
- const absUpnl = -upnl;
24330
- const consideringMm = absUpnl > lockedPartyAMM ? absUpnl : lockedPartyAMM;
24331
- return allocatedBalance - lockedCVA - lockedLF - totalPendingLocked - consideringMm;
23338
+ const sigData = data["data"];
23339
+ const signParams = sigData?.["signParams"] ?? data["signParams"];
23340
+ const signatures = sigData?.["signatures"] ?? data["signatures"];
23341
+ return {
23342
+ reqId: signParams["reqId"],
23343
+ timestamp: BigInt(signParams["timestamp"]),
23344
+ upnl: BigInt(signParams["upnl"]),
23345
+ gatewaySignature: signatures?.[0]?.["signature"] ?? "0x",
23346
+ sigs: parseSchnorrSign(
23347
+ signParams["sigs"] ?? signatures?.[1]
23348
+ )
23349
+ };
24332
23350
  }
24333
-
24334
- // src/client.ts
24335
- var SymmioSDK = class {
24336
- chainId;
24337
- muon;
24338
- _publicClient;
24339
- _walletClient;
24340
- _multiAccount;
24341
- _symmioDiamond;
24342
- _collateral;
24343
- _clearingHouse;
24344
- _signatureStore;
24345
- constructor(options) {
24346
- this.chainId = options.chainId;
24347
- this._publicClient = options.publicClient;
24348
- this._walletClient = options.walletClient;
24349
- const cfg = options.config ?? {};
24350
- this._multiAccount = cfg.multiAccountAddress ?? getAddress(MULTI_ACCOUNT_ADDRESS, this.chainId, "MultiAccount");
24351
- this._symmioDiamond = cfg.symmioDiamondAddress ?? getAddress(SYMMIO_DIAMOND_ADDRESS, this.chainId, "SymmioDiamond");
24352
- this._collateral = cfg.collateralAddress ?? getAddress(COLLATERAL_ADDRESS, this.chainId, "Collateral");
24353
- try {
24354
- this._clearingHouse = cfg.clearingHouseAddress ?? getAddress(CLEARING_HOUSE_ADDRESS, this.chainId, "ClearingHouse");
24355
- } catch {
24356
- }
24357
- try {
24358
- this._signatureStore = cfg.signatureStoreAddress ?? getAddress(SIGNATURE_STORE_ADDRESS, this.chainId, "SignatureStore");
24359
- } catch {
24360
- }
24361
- this.muon = new MuonClient({
24362
- baseUrls: cfg.muonBaseUrls ?? MUON_BASE_URLS,
24363
- appName: cfg.muonAppName ?? MUON_APP_NAME
24364
- });
23351
+ function parseSingleUpnlAndPriceSig(result) {
23352
+ const data = result["result"];
23353
+ if (!data) {
23354
+ throw new SymmioSDKError("Invalid Muon response: missing result", "MUON_PARSE_ERROR");
24365
23355
  }
24366
- get walletClient() {
24367
- return this._walletClient ?? null;
23356
+ const sigData = data["data"];
23357
+ const signParams = sigData?.["signParams"] ?? data["signParams"];
23358
+ const signatures = sigData?.["signatures"] ?? data["signatures"];
23359
+ return {
23360
+ reqId: signParams["reqId"],
23361
+ timestamp: BigInt(signParams["timestamp"]),
23362
+ upnl: BigInt(signParams["upnl"]),
23363
+ price: BigInt(signParams["price"]),
23364
+ gatewaySignature: signatures?.[0]?.["signature"] ?? "0x",
23365
+ sigs: parseSchnorrSign(
23366
+ signParams["sigs"] ?? signatures?.[1]
23367
+ )
23368
+ };
23369
+ }
23370
+ function parseBatchSig(result) {
23371
+ const data = result["result"];
23372
+ if (!data) {
23373
+ throw new SymmioSDKError("Invalid Muon response: missing result", "MUON_PARSE_ERROR");
24368
23374
  }
24369
- get isWriteReady() {
24370
- return !!this._walletClient;
23375
+ const sigData = data["data"];
23376
+ const signParams = sigData?.["signParams"] ?? data["signParams"];
23377
+ const signatures = sigData?.["signatures"] ?? data["signatures"];
23378
+ return {
23379
+ reqId: signParams["reqId"],
23380
+ timestamp: BigInt(signParams["timestamp"]),
23381
+ upnl: BigInt(signParams["upnl"]),
23382
+ prices: signParams["prices"].map((p) => BigInt(p)),
23383
+ symbolIds: signParams["symbolIds"].map((s) => BigInt(s)),
23384
+ gatewaySignature: signatures?.[0]?.["signature"] ?? "0x",
23385
+ sigs: parseSchnorrSign(
23386
+ signParams["sigs"] ?? signatures?.[1]
23387
+ )
23388
+ };
23389
+ }
23390
+ var MuonClient = class {
23391
+ baseUrls;
23392
+ appName;
23393
+ timeout;
23394
+ constructor(config) {
23395
+ this.baseUrls = config?.baseUrls ?? MUON_BASE_URLS;
23396
+ this.appName = config?.appName ?? MUON_APP_NAME;
23397
+ this.timeout = config?.timeout ?? MUON_REQUEST_TIMEOUT;
24371
23398
  }
24372
- requireWalletClient() {
24373
- if (!this._walletClient) {
24374
- throw new Error("WalletClient is required for write operations");
23399
+ /**
23400
+ * Sends a request to Muon, trying each base URL in order until one succeeds.
23401
+ */
23402
+ async sendRequest(method, params) {
23403
+ let lastError = null;
23404
+ for (const baseUrl of this.baseUrls) {
23405
+ try {
23406
+ const searchParams = new URLSearchParams({
23407
+ app: this.appName,
23408
+ method
23409
+ });
23410
+ for (const [key, value] of Object.entries(params)) {
23411
+ searchParams.set(`params[${key}]`, value);
23412
+ }
23413
+ const url = `${baseUrl}?${searchParams.toString()}`;
23414
+ const controller = new AbortController();
23415
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
23416
+ const response = await fetch(url, { signal: controller.signal });
23417
+ clearTimeout(timeoutId);
23418
+ if (!response.ok) {
23419
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
23420
+ }
23421
+ const json = await response.json();
23422
+ if (json["error"]) {
23423
+ throw new Error(`Muon error: ${JSON.stringify(json["error"])}`);
23424
+ }
23425
+ return json;
23426
+ } catch (err) {
23427
+ lastError = err instanceof Error ? err : new Error(String(err));
23428
+ }
24375
23429
  }
24376
- return this._walletClient;
24377
- }
24378
- // ─── Contract Addresses ────────────────────────────────────────
24379
- get addresses() {
24380
- return {
24381
- multiAccount: this._multiAccount,
24382
- symmioDiamond: this._symmioDiamond,
24383
- collateral: this._collateral,
24384
- clearingHouse: this._clearingHouse,
24385
- signatureStore: this._signatureStore
24386
- };
24387
- }
24388
- // ─── Account Module (MultiAccount) ─────────────────────────────
24389
- get account() {
24390
- const pc = this._publicClient;
24391
- const ma = this._multiAccount;
24392
- return {
24393
- /** Creates a new account. */
24394
- addAccount: (name) => addAccount(this.requireWalletClient(), pc, ma, name),
24395
- /** Edits an account's name. */
24396
- editName: (accountAddress, name) => editAccountName(
24397
- this.requireWalletClient(),
24398
- pc,
24399
- ma,
24400
- accountAddress,
24401
- name
24402
- ),
24403
- /** Gets all accounts for a user (paginated). */
24404
- getAll: (user, start, size) => getAccounts(pc, ma, user, start, size),
24405
- /** Gets the number of accounts for a user. */
24406
- getCount: (user) => getAccountsLength(pc, ma, user),
24407
- /** Gets the owner of an account. */
24408
- getOwner: (accountAddress) => getOwner(pc, ma, accountAddress)
24409
- };
24410
- }
24411
- // ─── Deposit Module (MultiAccount) ─────────────────────────────
24412
- get deposit() {
24413
- const pc = this._publicClient;
24414
- const ma = this._multiAccount;
24415
- return {
24416
- /** Standard deposit to an account. */
24417
- standard: (params) => deposit(this.requireWalletClient(), pc, ma, params),
24418
- /** Deposit and allocate in a single transaction. */
24419
- depositAndAllocate: (params) => depositAndAllocate(
24420
- this.requireWalletClient(),
24421
- pc,
24422
- ma,
24423
- params
24424
- )
24425
- };
24426
- }
24427
- // ─── Withdraw Module (MultiAccount) ────────────────────────────
24428
- get withdraw() {
24429
- const pc = this._publicClient;
24430
- const ma = this._multiAccount;
24431
- return {
24432
- /** Withdraws collateral from an account. */
24433
- withdraw: (params) => withdraw(this.requireWalletClient(), pc, ma, params)
24434
- };
24435
- }
24436
- // ─── Allocate / Deallocate Module (via _call proxy) ────────────
24437
- get collateral() {
24438
- const pc = this._publicClient;
24439
- const ma = this._multiAccount;
24440
- return {
24441
- /** Allocate collateral to a trading account. */
24442
- allocate: (subAccount, params) => allocate(
24443
- this.requireWalletClient(),
24444
- pc,
24445
- ma,
24446
- subAccount,
24447
- params
24448
- ),
24449
- /** Deallocate collateral (requires Muon signature). */
24450
- deallocate: (subAccount, params) => deallocate(
24451
- this.requireWalletClient(),
24452
- pc,
24453
- ma,
24454
- subAccount,
24455
- params
24456
- ),
24457
- /** Transfer funds to recipient's allocated balance. */
24458
- internalTransfer: (subAccount, params) => internalTransfer(
24459
- this.requireWalletClient(),
24460
- pc,
24461
- ma,
24462
- subAccount,
24463
- params
24464
- )
24465
- };
24466
- }
24467
- // ─── Trade Module ──────────────────────────────────────────────
24468
- get trade() {
24469
- const pc = this._publicClient;
24470
- const ma = this._multiAccount;
24471
- return {
24472
- /** Opens a position via sendQuoteWithAffiliate. */
24473
- sendQuote: (subAccount, params) => sendQuote(
24474
- this.requireWalletClient(),
24475
- pc,
24476
- ma,
24477
- subAccount,
24478
- params
24479
- ),
24480
- /** Close a position. */
24481
- closePosition: (subAccount, params) => closePosition(
24482
- this.requireWalletClient(),
24483
- pc,
24484
- ma,
24485
- subAccount,
24486
- params
24487
- ),
24488
- /** Cancel a pending quote. */
24489
- cancelQuote: (subAccount, quoteId) => cancelQuote(
24490
- this.requireWalletClient(),
24491
- pc,
24492
- ma,
24493
- subAccount,
24494
- quoteId
24495
- ),
24496
- /** Cancel a pending close request. */
24497
- cancelCloseRequest: (subAccount, quoteId) => cancelCloseRequest(
24498
- this.requireWalletClient(),
24499
- pc,
24500
- ma,
24501
- subAccount,
24502
- quoteId
24503
- ),
24504
- /** Force cancel a quote. */
24505
- forceCancelQuote: (subAccount, quoteId) => forceCancelQuote(
24506
- this.requireWalletClient(),
24507
- pc,
24508
- ma,
24509
- subAccount,
24510
- quoteId
24511
- ),
24512
- /** Force cancel a close request. */
24513
- forceCancelCloseRequest: (subAccount, quoteId) => forceCancelCloseRequest(
24514
- this.requireWalletClient(),
24515
- pc,
24516
- ma,
24517
- subAccount,
24518
- quoteId
24519
- )
24520
- };
24521
- }
24522
- // ─── Approval Module ───────────────────────────────────────────
24523
- get approval() {
24524
- const pc = this._publicClient;
24525
- const collateral = this._collateral;
24526
- const ma = this._multiAccount;
24527
- return {
24528
- /** Approve the MultiAccount contract to spend collateral. */
24529
- approveCollateral: (amount) => approve(
24530
- this.requireWalletClient(),
24531
- pc,
24532
- collateral,
24533
- ma,
24534
- amount
24535
- ),
24536
- /** Approve any spender for any token. */
24537
- approve: (token, spender, amount) => approve(
24538
- this.requireWalletClient(),
24539
- pc,
24540
- token,
24541
- spender,
24542
- amount
24543
- ),
24544
- /** Get current allowance. */
24545
- getAllowance: (token, owner, spender) => getAllowance(pc, token, owner, spender),
24546
- /** Get token balance. */
24547
- getBalance: (token, account) => getBalance(pc, token, account),
24548
- /** Get approval state for a required amount. */
24549
- getState: (token, owner, spender, requiredAmount) => getApprovalState(pc, token, owner, spender, requiredAmount)
24550
- };
24551
- }
24552
- // ─── Delegation Module ─────────────────────────────────────────
24553
- get delegation() {
24554
- const pc = this._publicClient;
24555
- const ma = this._multiAccount;
24556
- return {
24557
- /** Delegate access to selectors. */
24558
- delegateAccess: (params) => delegateAccess(
24559
- this.requireWalletClient(),
24560
- pc,
24561
- ma,
24562
- params
24563
- ),
24564
- /** Propose to revoke delegated access (starts cooldown). */
24565
- proposeRevoke: (params) => proposeRevoke(
24566
- this.requireWalletClient(),
24567
- pc,
24568
- ma,
24569
- params
24570
- ),
24571
- /** Revoke delegated access (after cooldown). */
24572
- revokeAccess: (params) => revokeAccess(
24573
- this.requireWalletClient(),
24574
- pc,
24575
- ma,
24576
- params
24577
- ),
24578
- /** Reads whether a selector is delegated to a target for a sub-account. */
24579
- hasAccess: (params) => hasDelegatedAccess(pc, ma, params)
24580
- };
24581
- }
24582
- // ─── Signature Module ──────────────────────────────────────────
24583
- get signature() {
24584
- const pc = this._publicClient;
24585
- const ss = this._signatureStore;
24586
- return {
24587
- signTerms: () => {
24588
- if (!ss) throw new Error("SignatureStore not configured for this chain");
24589
- return signTermsMessage(this.requireWalletClient(), pc, ss);
24590
- },
24591
- storeSignature: (sig) => {
24592
- if (!ss) throw new Error("SignatureStore not configured for this chain");
24593
- return storeSignature(
24594
- this.requireWalletClient(),
24595
- pc,
24596
- ss,
24597
- sig
24598
- );
24599
- },
24600
- hasSigned: (user) => {
24601
- if (!ss) throw new Error("SignatureStore not configured for this chain");
24602
- return hasSignedCurrentVersion(pc, ss, user);
24603
- },
24604
- getMessage: () => {
24605
- if (!ss) throw new Error("SignatureStore not configured for this chain");
24606
- return getCurrentMessage(pc, ss);
24607
- }
24608
- };
24609
- }
24610
- // ─── Admin Module ──────────────────────────────────────────────
24611
- get admin() {
24612
- const pc = this._publicClient;
24613
- const sd = this._symmioDiamond;
24614
- return {
24615
- grantRole: (role, grantee) => grantRole(this.requireWalletClient(), pc, sd, role, grantee),
24616
- revokeRole: (role, revokee) => revokeRole(this.requireWalletClient(), pc, sd, role, revokee)
24617
- };
24618
- }
24619
- // ─── Instant Trading Module ──────────────────────────────────
24620
- get instant() {
24621
- return {
24622
- /** Creates a SIWE message for instant trading authentication. */
24623
- createSiweMessage: (params) => createSiweMessage(params),
24624
- /** Fetches a nonce from the hedger for SIWE authentication. */
24625
- getNonce: (subAccount) => getNonce(this.chainId, subAccount),
24626
- /** Exchanges a signed SIWE message for an access token. */
24627
- login: (params) => login(this.chainId, params),
24628
- /** Opens a position instantly via the hedger (off-chain). */
24629
- open: (params, accessToken) => instantOpen(this.chainId, params, accessToken),
24630
- /** Closes a position instantly via the hedger (off-chain). */
24631
- close: (params, accessToken) => instantClose(this.chainId, params, accessToken),
24632
- /** Cancels a pending instant close request. */
24633
- cancelClose: (quoteId, accessToken) => cancelInstantClose(this.chainId, quoteId, accessToken),
24634
- /** Fetches the list of open instant close requests for an account. */
24635
- getOpenCloses: (account, accessToken) => getOpenInstantCloses(this.chainId, account, accessToken)
24636
- };
23430
+ throw new SymmioSDKError(
23431
+ `All Muon nodes failed. Last error: ${lastError?.message}`,
23432
+ "MUON_REQUEST_FAILED"
23433
+ );
24637
23434
  }
24638
- // ─── Stats Module ───────────────────────────────────────────
24639
- get stats() {
24640
- const pc = this._publicClient;
24641
- const sd = this._symmioDiamond;
24642
- return {
24643
- /** Reads partyA statistics (balances, locks) from the Diamond contract. */
24644
- getPartyAStats: (partyA) => getPartyAStats(pc, sd, partyA),
24645
- /** Calculates available margin for placing orders given uPNL. */
24646
- calculateAvailableForOrder: (stats, upnl) => calculateAvailableForOrder(stats, upnl)
24647
- };
23435
+ /**
23436
+ * Gets a UPnL + Price signature for opening a position (sendQuote).
23437
+ */
23438
+ async getQuoteSig(params) {
23439
+ const result = await this.sendRequest("uPnl_A_withSymbolPrice", {
23440
+ partyA: params.partyA,
23441
+ chainId: params.chainId.toString(),
23442
+ symmio: params.symmioAddress,
23443
+ symbolId: params.symbolId.toString()
23444
+ });
23445
+ return parseSingleUpnlAndPriceSig(result);
24648
23446
  }
24649
- // ─── Muon Signatures ──────────────────────────────────────────
24650
- async getQuoteSig(partyA, symbolId) {
24651
- return this.muon.getQuoteSig({
24652
- partyA,
24653
- chainId: this.chainId,
24654
- symmioAddress: this._symmioDiamond,
24655
- symbolId
23447
+ /**
23448
+ * Gets a UPnL signature for deallocating funds.
23449
+ * v0.8.5: Now includes pendingBalance for safe deallocate.
23450
+ */
23451
+ async getDeallocateSig(params) {
23452
+ const result = await this.sendRequest("uPnl_A", {
23453
+ partyA: params.partyA,
23454
+ chainId: params.chainId.toString(),
23455
+ symmio: params.symmioAddress
24656
23456
  });
23457
+ return parseSingleUpnlSig(result);
24657
23458
  }
24658
- async getDeallocateSig(partyA) {
24659
- return this.muon.getDeallocateSig({
24660
- partyA,
24661
- chainId: this.chainId,
24662
- symmioAddress: this._symmioDiamond
23459
+ /**
23460
+ * Gets a batch signature for multiple positions (v0.8.5).
23461
+ * Single signature covers multiple symbol prices for batch open/close.
23462
+ */
23463
+ async getBatchSig(params) {
23464
+ const result = await this.sendRequest("uPnl_A_withSymbolPrices", {
23465
+ partyA: params.partyA,
23466
+ chainId: params.chainId.toString(),
23467
+ symmio: params.symmioAddress,
23468
+ symbolIds: params.symbolIds.join(",")
24663
23469
  });
23470
+ return parseBatchSig(result);
24664
23471
  }
24665
23472
  };
24666
23473
 
24667
- // src/types/common.ts
24668
- var PositionType = /* @__PURE__ */ ((PositionType2) => {
24669
- PositionType2[PositionType2["LONG"] = 0] = "LONG";
24670
- PositionType2[PositionType2["SHORT"] = 1] = "SHORT";
24671
- return PositionType2;
24672
- })(PositionType || {});
24673
- var OrderType = /* @__PURE__ */ ((OrderType2) => {
24674
- OrderType2[OrderType2["LIMIT"] = 0] = "LIMIT";
24675
- OrderType2[OrderType2["MARKET"] = 1] = "MARKET";
24676
- return OrderType2;
24677
- })(OrderType || {});
24678
- var QuoteStatus = /* @__PURE__ */ ((QuoteStatus2) => {
24679
- QuoteStatus2[QuoteStatus2["PENDING"] = 0] = "PENDING";
24680
- QuoteStatus2[QuoteStatus2["LOCKED"] = 1] = "LOCKED";
24681
- QuoteStatus2[QuoteStatus2["CANCEL_PENDING"] = 2] = "CANCEL_PENDING";
24682
- QuoteStatus2[QuoteStatus2["CANCELED"] = 3] = "CANCELED";
24683
- QuoteStatus2[QuoteStatus2["OPENED"] = 4] = "OPENED";
24684
- QuoteStatus2[QuoteStatus2["CLOSE_PENDING"] = 5] = "CLOSE_PENDING";
24685
- QuoteStatus2[QuoteStatus2["CANCEL_CLOSE_PENDING"] = 6] = "CANCEL_CLOSE_PENDING";
24686
- QuoteStatus2[QuoteStatus2["CLOSED"] = 7] = "CLOSED";
24687
- QuoteStatus2[QuoteStatus2["LIQUIDATED"] = 8] = "LIQUIDATED";
24688
- QuoteStatus2[QuoteStatus2["EXPIRED"] = 9] = "EXPIRED";
24689
- return QuoteStatus2;
24690
- })(QuoteStatus || {});
24691
- var LiquidationStatus = /* @__PURE__ */ ((LiquidationStatus2) => {
24692
- LiquidationStatus2[LiquidationStatus2["NONE"] = 0] = "NONE";
24693
- LiquidationStatus2[LiquidationStatus2["PENDING"] = 1] = "PENDING";
24694
- LiquidationStatus2[LiquidationStatus2["ACTIVE"] = 2] = "ACTIVE";
24695
- LiquidationStatus2[LiquidationStatus2["COMPLETED"] = 3] = "COMPLETED";
24696
- return LiquidationStatus2;
24697
- })(LiquidationStatus || {});
24698
- var SoftLiquidationLevel = /* @__PURE__ */ ((SoftLiquidationLevel2) => {
24699
- SoftLiquidationLevel2[SoftLiquidationLevel2["NONE"] = 0] = "NONE";
24700
- SoftLiquidationLevel2[SoftLiquidationLevel2["WARNING"] = 1] = "WARNING";
24701
- SoftLiquidationLevel2[SoftLiquidationLevel2["CRITICAL"] = 2] = "CRITICAL";
24702
- SoftLiquidationLevel2[SoftLiquidationLevel2["EMERGENCY"] = 3] = "EMERGENCY";
24703
- return SoftLiquidationLevel2;
24704
- })(SoftLiquidationLevel || {});
23474
+ // src/actions/account.ts
23475
+ var account_exports = {};
23476
+ __export(account_exports, {
23477
+ addAccount: () => addAccount,
23478
+ editAccountName: () => editAccountName,
23479
+ getAccounts: () => getAccounts,
23480
+ getAccountsLength: () => getAccountsLength,
23481
+ getOwner: () => getOwner,
23482
+ prepareAddAccount: () => prepareAddAccount,
23483
+ prepareEditAccountName: () => prepareEditAccountName
23484
+ });
24705
23485
 
24706
- // src/types/affiliate.ts
24707
- var AffiliateFeeLevel = /* @__PURE__ */ ((AffiliateFeeLevel2) => {
24708
- AffiliateFeeLevel2[AffiliateFeeLevel2["USER_SYMBOL"] = 0] = "USER_SYMBOL";
24709
- AffiliateFeeLevel2[AffiliateFeeLevel2["USER_DEFAULT"] = 1] = "USER_DEFAULT";
24710
- AffiliateFeeLevel2[AffiliateFeeLevel2["SYMBOL"] = 2] = "SYMBOL";
24711
- AffiliateFeeLevel2[AffiliateFeeLevel2["AFFILIATE_DEFAULT"] = 3] = "AFFILIATE_DEFAULT";
24712
- return AffiliateFeeLevel2;
24713
- })(AffiliateFeeLevel || {});
23486
+ // src/utils/gas.ts
23487
+ function calculateGasMargin(estimatedGas) {
23488
+ return estimatedGas * (100n + GAS_MARGIN_PERCENTAGE) / 100n;
23489
+ }
24714
23490
 
24715
- // src/types/clearingHouse.ts
24716
- var ClearingHouseLiquidationStatus = /* @__PURE__ */ ((ClearingHouseLiquidationStatus2) => {
24717
- ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["INITIATED"] = 0] = "INITIATED";
24718
- ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["DEALLOCATED"] = 1] = "DEALLOCATED";
24719
- ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["POSITIONS_CLOSED"] = 2] = "POSITIONS_CLOSED";
24720
- ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["SETTLED"] = 3] = "SETTLED";
24721
- ClearingHouseLiquidationStatus2[ClearingHouseLiquidationStatus2["COMPLETED"] = 4] = "COMPLETED";
24722
- return ClearingHouseLiquidationStatus2;
24723
- })(ClearingHouseLiquidationStatus || {});
23491
+ // src/actions/account.ts
23492
+ function prepareAddAccount(multiAccount, account, name) {
23493
+ const data = encodeFunctionData({
23494
+ abi: MultiAccountABI,
23495
+ functionName: "addAccount",
23496
+ args: [name]
23497
+ });
23498
+ return {
23499
+ functionName: "addAccount",
23500
+ args: [name],
23501
+ config: { account, to: multiAccount, data, value: 0n }
23502
+ };
23503
+ }
23504
+ function prepareEditAccountName(multiAccount, account, accountAddress, name) {
23505
+ const data = encodeFunctionData({
23506
+ abi: MultiAccountABI,
23507
+ functionName: "editAccountName",
23508
+ args: [accountAddress, name]
23509
+ });
23510
+ return {
23511
+ functionName: "editAccountName",
23512
+ args: [accountAddress, name],
23513
+ config: { account, to: multiAccount, data, value: 0n }
23514
+ };
23515
+ }
23516
+ async function addAccount(walletClient, publicClient, multiAccount, name) {
23517
+ const account = walletClient.account?.address;
23518
+ if (!account) throw new Error("Wallet client has no account");
23519
+ const prepared = prepareAddAccount(multiAccount, account, name);
23520
+ const gas = await publicClient.estimateGas(prepared.config);
23521
+ return walletClient.sendTransaction({
23522
+ ...prepared.config,
23523
+ gas: calculateGasMargin(gas),
23524
+ chain: walletClient.chain
23525
+ });
23526
+ }
23527
+ async function editAccountName(walletClient, publicClient, multiAccount, accountAddress, name) {
23528
+ const account = walletClient.account?.address;
23529
+ if (!account) throw new Error("Wallet client has no account");
23530
+ const prepared = prepareEditAccountName(multiAccount, account, accountAddress, name);
23531
+ const gas = await publicClient.estimateGas(prepared.config);
23532
+ return walletClient.sendTransaction({
23533
+ ...prepared.config,
23534
+ gas: calculateGasMargin(gas),
23535
+ chain: walletClient.chain
23536
+ });
23537
+ }
23538
+ async function getAccounts(publicClient, multiAccount, user, start = 0, size = 100) {
23539
+ const result = await publicClient.readContract({
23540
+ address: multiAccount,
23541
+ abi: MultiAccountABI,
23542
+ functionName: "getAccounts",
23543
+ args: [user, BigInt(start), BigInt(size)]
23544
+ });
23545
+ return result;
23546
+ }
23547
+ async function getAccountsLength(publicClient, multiAccount, user) {
23548
+ const result = await publicClient.readContract({
23549
+ address: multiAccount,
23550
+ abi: MultiAccountABI,
23551
+ functionName: "getAccountsLength",
23552
+ args: [user]
23553
+ });
23554
+ return Number(result);
23555
+ }
23556
+ async function getOwner(publicClient, multiAccount, accountAddress) {
23557
+ const result = await publicClient.readContract({
23558
+ address: multiAccount,
23559
+ abi: MultiAccountABI,
23560
+ functionName: "owners",
23561
+ args: [accountAddress]
23562
+ });
23563
+ return result;
23564
+ }
24724
23565
 
24725
- // src/types/instant.ts
24726
- var InstantCloseStatus = /* @__PURE__ */ ((InstantCloseStatus2) => {
24727
- InstantCloseStatus2[InstantCloseStatus2["STARTED"] = 0] = "STARTED";
24728
- InstantCloseStatus2[InstantCloseStatus2["PROCESSING"] = 1] = "PROCESSING";
24729
- InstantCloseStatus2[InstantCloseStatus2["FAILED"] = 2] = "FAILED";
24730
- InstantCloseStatus2[InstantCloseStatus2["FINISHED"] = 3] = "FINISHED";
24731
- return InstantCloseStatus2;
24732
- })(InstantCloseStatus || {});
23566
+ // src/actions/deposit.ts
23567
+ var deposit_exports = {};
23568
+ __export(deposit_exports, {
23569
+ deposit: () => deposit,
23570
+ depositAndAllocate: () => depositAndAllocate,
23571
+ prepareDeposit: () => prepareDeposit,
23572
+ prepareDepositAndAllocate: () => prepareDepositAndAllocate
23573
+ });
23574
+ function prepareDeposit(multiAccount, account, params) {
23575
+ validateAmount(params.amount, "deposit amount");
23576
+ validateAddress(params.account, "account");
23577
+ const data = encodeFunctionData({
23578
+ abi: MultiAccountABI,
23579
+ functionName: "depositForAccount",
23580
+ args: [params.account, params.amount]
23581
+ });
23582
+ return {
23583
+ functionName: "depositForAccount",
23584
+ args: [params.account, params.amount],
23585
+ config: { account, to: multiAccount, data, value: 0n }
23586
+ };
23587
+ }
23588
+ function prepareDepositAndAllocate(multiAccount, account, params) {
23589
+ validateAmount(params.amount, "deposit amount");
23590
+ validateAddress(params.account, "account");
23591
+ const data = encodeFunctionData({
23592
+ abi: MultiAccountABI,
23593
+ functionName: "depositAndAllocateForAccount",
23594
+ args: [params.account, params.amount]
23595
+ });
23596
+ return {
23597
+ functionName: "depositAndAllocateForAccount",
23598
+ args: [params.account, params.amount],
23599
+ config: { account, to: multiAccount, data, value: 0n }
23600
+ };
23601
+ }
23602
+ async function deposit(walletClient, publicClient, multiAccount, params) {
23603
+ const account = walletClient.account?.address;
23604
+ if (!account) throw new Error("Wallet client has no account");
23605
+ const prepared = prepareDeposit(multiAccount, account, params);
23606
+ const gas = await publicClient.estimateGas(prepared.config);
23607
+ return walletClient.sendTransaction({
23608
+ ...prepared.config,
23609
+ gas: calculateGasMargin(gas),
23610
+ chain: walletClient.chain
23611
+ });
23612
+ }
23613
+ async function depositAndAllocate(walletClient, publicClient, multiAccount, params) {
23614
+ const account = walletClient.account?.address;
23615
+ if (!account) throw new Error("Wallet client has no account");
23616
+ const prepared = prepareDepositAndAllocate(multiAccount, account, params);
23617
+ const gas = await publicClient.estimateGas(prepared.config);
23618
+ return walletClient.sendTransaction({
23619
+ ...prepared.config,
23620
+ gas: calculateGasMargin(gas),
23621
+ chain: walletClient.chain
23622
+ });
23623
+ }
24733
23624
 
24734
- // src/abis/ClearingHouse.ts
24735
- var ClearingHouseABI = [
24736
- // ─── Liquidation Lifecycle ────────────────────────────────────
24737
- {
24738
- name: "initiateLiquidation",
24739
- type: "function",
24740
- stateMutability: "nonpayable",
24741
- inputs: [
24742
- { name: "partyA", type: "address" },
24743
- { name: "partyB", type: "address" }
24744
- ],
24745
- outputs: [{ name: "liquidationId", type: "uint256" }]
24746
- },
24747
- {
24748
- name: "deallocateLiquidation",
24749
- type: "function",
24750
- stateMutability: "nonpayable",
24751
- inputs: [{ name: "liquidationId", type: "uint256" }],
24752
- outputs: []
24753
- },
24754
- {
24755
- name: "closePositionsInLiquidation",
24756
- type: "function",
24757
- stateMutability: "nonpayable",
24758
- inputs: [
24759
- { name: "liquidationId", type: "uint256" },
24760
- { name: "quoteIds", type: "uint256[]" },
24761
- { name: "closePrices", type: "uint256[]" }
24762
- ],
24763
- outputs: []
24764
- },
24765
- {
24766
- name: "distributeLiquidation",
24767
- type: "function",
24768
- stateMutability: "nonpayable",
24769
- inputs: [{ name: "liquidationId", type: "uint256" }],
24770
- outputs: []
24771
- },
24772
- {
24773
- name: "settleLiquidation",
24774
- type: "function",
24775
- stateMutability: "nonpayable",
24776
- inputs: [{ name: "liquidationId", type: "uint256" }],
24777
- outputs: []
24778
- },
24779
- // ─── Soft Liquidation (v0.8.5) ────────────────────────────────
24780
- {
24781
- name: "applySoftLiquidationPenalty",
24782
- type: "function",
24783
- stateMutability: "nonpayable",
24784
- inputs: [
24785
- { name: "partyB", type: "address" },
24786
- { name: "level", type: "uint8" }
24787
- ],
24788
- outputs: []
24789
- },
24790
- {
24791
- name: "setSoftLiquidationThreshold",
24792
- type: "function",
24793
- stateMutability: "nonpayable",
24794
- inputs: [
24795
- { name: "level", type: "uint8" },
24796
- { name: "ratio", type: "uint256" },
24797
- { name: "penalty", type: "uint256" }
24798
- ],
24799
- outputs: []
24800
- },
24801
- // ─── Auto-Takeover ────────────────────────────────────────────
24802
- {
24803
- name: "autoTakeover",
24804
- type: "function",
24805
- stateMutability: "nonpayable",
24806
- inputs: [
24807
- { name: "liquidationId", type: "uint256" },
24808
- { name: "newPartyB", type: "address" }
24809
- ],
24810
- outputs: []
24811
- },
24812
- // ─── ADL Assurance ────────────────────────────────────────────
24813
- {
24814
- name: "depositADLAssurance",
24815
- type: "function",
24816
- stateMutability: "nonpayable",
24817
- inputs: [
24818
- { name: "partyB", type: "address" },
24819
- { name: "amount", type: "uint256" }
24820
- ],
24821
- outputs: []
24822
- },
24823
- {
24824
- name: "slashADLAssurance",
24825
- type: "function",
24826
- stateMutability: "nonpayable",
24827
- inputs: [{ name: "partyB", type: "address" }],
24828
- outputs: []
24829
- },
24830
- // ─── Insurance Vault ──────────────────────────────────────────
24831
- {
24832
- name: "setMaxLiquidatorProfit",
24833
- type: "function",
24834
- stateMutability: "nonpayable",
24835
- inputs: [{ name: "maxProfit", type: "uint256" }],
24836
- outputs: []
24837
- },
24838
- {
24839
- name: "reimbursePartyB",
24840
- type: "function",
24841
- stateMutability: "nonpayable",
24842
- inputs: [
24843
- { name: "partyB", type: "address" },
24844
- { name: "amount", type: "uint256" }
24845
- ],
24846
- outputs: []
24847
- },
24848
- // ─── View Functions ───────────────────────────────────────────
24849
- {
24850
- name: "getLiquidation",
24851
- type: "function",
24852
- stateMutability: "view",
24853
- inputs: [{ name: "liquidationId", type: "uint256" }],
24854
- outputs: [
24855
- {
24856
- name: "liquidation",
24857
- type: "tuple",
24858
- components: [
24859
- { name: "id", type: "uint256" },
24860
- { name: "partyA", type: "address" },
24861
- { name: "partyB", type: "address" },
24862
- { name: "status", type: "uint8" },
24863
- { name: "deallocatedAmount", type: "uint256" },
24864
- { name: "settledAmount", type: "uint256" },
24865
- { name: "createdAt", type: "uint256" }
24866
- ]
24867
- }
23625
+ // src/actions/withdraw.ts
23626
+ var withdraw_exports = {};
23627
+ __export(withdraw_exports, {
23628
+ prepareWithdraw: () => prepareWithdraw,
23629
+ withdraw: () => withdraw
23630
+ });
23631
+ function prepareWithdraw(multiAccount, account, params) {
23632
+ validateAmount(params.amount, "withdraw amount");
23633
+ validateAddress(params.account, "account");
23634
+ const data = encodeFunctionData({
23635
+ abi: MultiAccountABI,
23636
+ functionName: "withdrawFromAccount",
23637
+ args: [params.account, params.amount]
23638
+ });
23639
+ return {
23640
+ functionName: "withdrawFromAccount",
23641
+ args: [params.account, params.amount],
23642
+ config: { account, to: multiAccount, data, value: 0n }
23643
+ };
23644
+ }
23645
+ async function withdraw(walletClient, publicClient, multiAccount, params) {
23646
+ const account = walletClient.account?.address;
23647
+ if (!account) throw new Error("Wallet client has no account");
23648
+ const prepared = prepareWithdraw(multiAccount, account, params);
23649
+ const gas = await publicClient.estimateGas(prepared.config);
23650
+ return walletClient.sendTransaction({
23651
+ ...prepared.config,
23652
+ gas: calculateGasMargin(gas),
23653
+ chain: walletClient.chain
23654
+ });
23655
+ }
23656
+
23657
+ // src/actions/allocate.ts
23658
+ var allocate_exports = {};
23659
+ __export(allocate_exports, {
23660
+ allocate: () => allocate,
23661
+ deallocate: () => deallocate,
23662
+ internalTransfer: () => internalTransfer,
23663
+ prepareAllocate: () => prepareAllocate,
23664
+ prepareDeallocate: () => prepareDeallocate,
23665
+ prepareInternalTransfer: () => prepareInternalTransfer
23666
+ });
23667
+ function encodeCall(abi, functionName, args) {
23668
+ return encodeFunctionData({
23669
+ abi,
23670
+ functionName,
23671
+ args
23672
+ });
23673
+ }
23674
+ function wrapInProxyCall(accountDiamondAbi, subAccount, callDatas) {
23675
+ const data = encodeFunctionData({
23676
+ abi: accountDiamondAbi,
23677
+ functionName: "_call",
23678
+ args: [subAccount, callDatas]
23679
+ });
23680
+ return {
23681
+ functionName: "_call",
23682
+ args: [subAccount, callDatas],
23683
+ data
23684
+ };
23685
+ }
23686
+
23687
+ // src/actions/allocate.ts
23688
+ function prepareAllocate(multiAccount, account, subAccount, params) {
23689
+ validateAmount(params.amount, "allocate amount");
23690
+ const innerData = encodeFunctionData({
23691
+ abi: SymmioDiamondABI,
23692
+ functionName: "allocate",
23693
+ args: [params.amount]
23694
+ });
23695
+ const proxy = wrapInProxyCall(
23696
+ MultiAccountABI,
23697
+ subAccount,
23698
+ [innerData]
23699
+ );
23700
+ return {
23701
+ functionName: "_call",
23702
+ args: proxy.args,
23703
+ config: { account, to: multiAccount, data: proxy.data, value: 0n }
23704
+ };
23705
+ }
23706
+ function prepareDeallocate(multiAccount, account, subAccount, params) {
23707
+ validateAmount(params.amount, "deallocate amount");
23708
+ const muonSig = {
23709
+ reqId: params.upnlSig.reqId,
23710
+ timestamp: params.upnlSig.timestamp,
23711
+ upnl: params.upnlSig.upnl,
23712
+ gatewaySignature: params.upnlSig.gatewaySignature,
23713
+ sigs: {
23714
+ signature: params.upnlSig.sigs.signature,
23715
+ owner: params.upnlSig.sigs.owner,
23716
+ nonce: params.upnlSig.sigs.nonce
23717
+ }
23718
+ };
23719
+ const innerData = encodeFunctionData({
23720
+ abi: SymmioDiamondABI,
23721
+ functionName: "deallocate",
23722
+ args: [params.amount, muonSig]
23723
+ });
23724
+ const proxy = wrapInProxyCall(
23725
+ MultiAccountABI,
23726
+ subAccount,
23727
+ [innerData]
23728
+ );
23729
+ return {
23730
+ functionName: "_call",
23731
+ args: proxy.args,
23732
+ config: { account, to: multiAccount, data: proxy.data, value: 0n }
23733
+ };
23734
+ }
23735
+ function prepareInternalTransfer(multiAccount, account, subAccount, params) {
23736
+ validateAmount(params.amount, "transfer amount");
23737
+ validateAddress(params.recipient, "recipient");
23738
+ const innerData = encodeFunctionData({
23739
+ abi: SymmioDiamondABI,
23740
+ functionName: "internalTransfer",
23741
+ args: [params.recipient, params.amount]
23742
+ });
23743
+ const proxy = wrapInProxyCall(
23744
+ MultiAccountABI,
23745
+ subAccount,
23746
+ [innerData]
23747
+ );
23748
+ return {
23749
+ functionName: "_call",
23750
+ args: proxy.args,
23751
+ config: { account, to: multiAccount, data: proxy.data, value: 0n }
23752
+ };
23753
+ }
23754
+ async function allocate(walletClient, publicClient, multiAccount, subAccount, params) {
23755
+ const account = walletClient.account?.address;
23756
+ if (!account) throw new Error("Wallet client has no account");
23757
+ const prepared = prepareAllocate(multiAccount, account, subAccount, params);
23758
+ const gas = await publicClient.estimateGas(prepared.config);
23759
+ return walletClient.sendTransaction({
23760
+ ...prepared.config,
23761
+ gas: calculateGasMargin(gas),
23762
+ chain: walletClient.chain
23763
+ });
23764
+ }
23765
+ async function deallocate(walletClient, publicClient, multiAccount, subAccount, params) {
23766
+ const account = walletClient.account?.address;
23767
+ if (!account) throw new Error("Wallet client has no account");
23768
+ const prepared = prepareDeallocate(multiAccount, account, subAccount, params);
23769
+ const gas = await publicClient.estimateGas(prepared.config);
23770
+ return walletClient.sendTransaction({
23771
+ ...prepared.config,
23772
+ gas: calculateGasMargin(gas),
23773
+ chain: walletClient.chain
23774
+ });
23775
+ }
23776
+ async function internalTransfer(walletClient, publicClient, multiAccount, subAccount, params) {
23777
+ const account = walletClient.account?.address;
23778
+ if (!account) throw new Error("Wallet client has no account");
23779
+ const prepared = prepareInternalTransfer(multiAccount, account, subAccount, params);
23780
+ const gas = await publicClient.estimateGas(prepared.config);
23781
+ return walletClient.sendTransaction({
23782
+ ...prepared.config,
23783
+ gas: calculateGasMargin(gas),
23784
+ chain: walletClient.chain
23785
+ });
23786
+ }
23787
+
23788
+ // src/actions/trade.ts
23789
+ var trade_exports = {};
23790
+ __export(trade_exports, {
23791
+ preparePairTrade: () => preparePairTrade,
23792
+ prepareSendQuote: () => prepareSendQuote,
23793
+ sendQuote: () => sendQuote
23794
+ });
23795
+ function buildUpnlSigTuple(sig) {
23796
+ return {
23797
+ reqId: sig.reqId,
23798
+ timestamp: sig.timestamp,
23799
+ upnl: sig.upnl,
23800
+ price: sig.price,
23801
+ gatewaySignature: sig.gatewaySignature,
23802
+ sigs: {
23803
+ signature: sig.sigs.signature,
23804
+ owner: sig.sigs.owner,
23805
+ nonce: sig.sigs.nonce
23806
+ }
23807
+ };
23808
+ }
23809
+ function prepareSendQuote(multiAccount, account, subAccount, params) {
23810
+ validateQuantity(params.quantity);
23811
+ const innerData = encodeFunctionData({
23812
+ abi: SymmioDiamondABI,
23813
+ functionName: "sendQuoteWithAffiliate",
23814
+ args: [
23815
+ params.partyBsWhiteList,
23816
+ BigInt(params.symbolId),
23817
+ params.positionType,
23818
+ params.orderType,
23819
+ params.price,
23820
+ params.quantity,
23821
+ params.cva,
23822
+ params.lf,
23823
+ params.partyAmm,
23824
+ params.partyBmm,
23825
+ params.maxFundingRate,
23826
+ params.deadline,
23827
+ params.affiliate,
23828
+ buildUpnlSigTuple(params.upnlSig)
24868
23829
  ]
24869
- },
24870
- // ─── Events ───────────────────────────────────────────────────
24871
- {
24872
- name: "LiquidationInitiated",
24873
- type: "event",
24874
- inputs: [
24875
- { name: "liquidationId", type: "uint256", indexed: true },
24876
- { name: "partyA", type: "address", indexed: true },
24877
- { name: "partyB", type: "address", indexed: true }
23830
+ });
23831
+ const proxy = wrapInProxyCall(
23832
+ MultiAccountABI,
23833
+ subAccount,
23834
+ [innerData]
23835
+ );
23836
+ return {
23837
+ functionName: "_call",
23838
+ args: proxy.args,
23839
+ config: { account, to: multiAccount, data: proxy.data, value: 0n }
23840
+ };
23841
+ }
23842
+ function preparePairTrade(multiAccount, account, subAccount, longParams, shortParams) {
23843
+ const longData = encodeFunctionData({
23844
+ abi: SymmioDiamondABI,
23845
+ functionName: "sendQuoteWithAffiliate",
23846
+ args: [
23847
+ longParams.partyBsWhiteList,
23848
+ BigInt(longParams.symbolId),
23849
+ longParams.positionType,
23850
+ longParams.orderType,
23851
+ longParams.price,
23852
+ longParams.quantity,
23853
+ longParams.cva,
23854
+ longParams.lf,
23855
+ longParams.partyAmm,
23856
+ longParams.partyBmm,
23857
+ longParams.maxFundingRate,
23858
+ longParams.deadline,
23859
+ longParams.affiliate,
23860
+ buildUpnlSigTuple(longParams.upnlSig)
23861
+ ]
23862
+ });
23863
+ const shortData = encodeFunctionData({
23864
+ abi: SymmioDiamondABI,
23865
+ functionName: "sendQuoteWithAffiliate",
23866
+ args: [
23867
+ shortParams.partyBsWhiteList,
23868
+ BigInt(shortParams.symbolId),
23869
+ shortParams.positionType,
23870
+ shortParams.orderType,
23871
+ shortParams.price,
23872
+ shortParams.quantity,
23873
+ shortParams.cva,
23874
+ shortParams.lf,
23875
+ shortParams.partyAmm,
23876
+ shortParams.partyBmm,
23877
+ shortParams.maxFundingRate,
23878
+ shortParams.deadline,
23879
+ shortParams.affiliate,
23880
+ buildUpnlSigTuple(shortParams.upnlSig)
23881
+ ]
23882
+ });
23883
+ const proxy = wrapInProxyCall(
23884
+ MultiAccountABI,
23885
+ subAccount,
23886
+ [longData, shortData]
23887
+ );
23888
+ return {
23889
+ functionName: "_call",
23890
+ args: proxy.args,
23891
+ config: { account, to: multiAccount, data: proxy.data, value: 0n }
23892
+ };
23893
+ }
23894
+ async function sendQuote(walletClient, publicClient, multiAccount, subAccount, params) {
23895
+ const account = walletClient.account?.address;
23896
+ if (!account) throw new Error("Wallet client has no account");
23897
+ const prepared = prepareSendQuote(multiAccount, account, subAccount, params);
23898
+ const gas = await publicClient.estimateGas(prepared.config);
23899
+ return walletClient.sendTransaction({
23900
+ ...prepared.config,
23901
+ gas: calculateGasMargin(gas),
23902
+ chain: walletClient.chain
23903
+ });
23904
+ }
23905
+
23906
+ // src/actions/close.ts
23907
+ var close_exports = {};
23908
+ __export(close_exports, {
23909
+ closePosition: () => closePosition,
23910
+ prepareClosePosition: () => prepareClosePosition,
23911
+ preparePairClose: () => preparePairClose
23912
+ });
23913
+ function prepareClosePosition(multiAccount, account, subAccount, params) {
23914
+ const innerData = encodeFunctionData({
23915
+ abi: SymmioDiamondABI,
23916
+ functionName: "requestToClosePosition",
23917
+ args: [
23918
+ params.quoteId,
23919
+ params.closePrice,
23920
+ params.quantityToClose,
23921
+ params.orderType,
23922
+ params.deadline
24878
23923
  ]
24879
- },
24880
- {
24881
- name: "LiquidationSettled",
24882
- type: "event",
24883
- inputs: [
24884
- { name: "liquidationId", type: "uint256", indexed: true }
23924
+ });
23925
+ const proxy = wrapInProxyCall(
23926
+ MultiAccountABI,
23927
+ subAccount,
23928
+ [innerData]
23929
+ );
23930
+ return {
23931
+ functionName: "_call",
23932
+ args: proxy.args,
23933
+ config: { account, to: multiAccount, data: proxy.data, value: 0n }
23934
+ };
23935
+ }
23936
+ function preparePairClose(multiAccount, account, subAccount, longClose, shortClose) {
23937
+ const longData = encodeFunctionData({
23938
+ abi: SymmioDiamondABI,
23939
+ functionName: "requestToClosePosition",
23940
+ args: [
23941
+ longClose.quoteId,
23942
+ longClose.closePrice,
23943
+ longClose.quantityToClose,
23944
+ longClose.orderType,
23945
+ longClose.deadline
24885
23946
  ]
24886
- },
24887
- {
24888
- name: "SoftLiquidationPenalty",
24889
- type: "event",
24890
- inputs: [
24891
- { name: "partyB", type: "address", indexed: true },
24892
- { name: "level", type: "uint8", indexed: false },
24893
- { name: "penalty", type: "uint256", indexed: false }
23947
+ });
23948
+ const shortData = encodeFunctionData({
23949
+ abi: SymmioDiamondABI,
23950
+ functionName: "requestToClosePosition",
23951
+ args: [
23952
+ shortClose.quoteId,
23953
+ shortClose.closePrice,
23954
+ shortClose.quantityToClose,
23955
+ shortClose.orderType,
23956
+ shortClose.deadline
24894
23957
  ]
23958
+ });
23959
+ const proxy = wrapInProxyCall(
23960
+ MultiAccountABI,
23961
+ subAccount,
23962
+ [longData, shortData]
23963
+ );
23964
+ return {
23965
+ functionName: "_call",
23966
+ args: proxy.args,
23967
+ config: { account, to: multiAccount, data: proxy.data, value: 0n }
23968
+ };
23969
+ }
23970
+ async function closePosition(walletClient, publicClient, multiAccount, subAccount, params) {
23971
+ const account = walletClient.account?.address;
23972
+ if (!account) throw new Error("Wallet client has no account");
23973
+ const prepared = prepareClosePosition(multiAccount, account, subAccount, params);
23974
+ const gas = await publicClient.estimateGas(prepared.config);
23975
+ return walletClient.sendTransaction({
23976
+ ...prepared.config,
23977
+ gas: calculateGasMargin(gas),
23978
+ chain: walletClient.chain
23979
+ });
23980
+ }
23981
+
23982
+ // src/actions/cancel.ts
23983
+ var cancel_exports = {};
23984
+ __export(cancel_exports, {
23985
+ cancelCloseRequest: () => cancelCloseRequest,
23986
+ cancelQuote: () => cancelQuote,
23987
+ forceCancelCloseRequest: () => forceCancelCloseRequest,
23988
+ forceCancelQuote: () => forceCancelQuote,
23989
+ prepareCancelCloseRequest: () => prepareCancelCloseRequest,
23990
+ prepareCancelQuote: () => prepareCancelQuote,
23991
+ prepareForceCancelCloseRequest: () => prepareForceCancelCloseRequest,
23992
+ prepareForceCancelQuote: () => prepareForceCancelQuote
23993
+ });
23994
+ function prepareCancelAction(accountDiamond, account, subAccount, functionName, quoteId) {
23995
+ const innerData = encodeFunctionData({
23996
+ abi: SymmioDiamondABI,
23997
+ functionName,
23998
+ args: [quoteId]
23999
+ });
24000
+ const proxy = wrapInProxyCall(
24001
+ MultiAccountABI,
24002
+ subAccount,
24003
+ [innerData]
24004
+ );
24005
+ return {
24006
+ functionName: "_call",
24007
+ args: proxy.args,
24008
+ config: { account, to: accountDiamond, data: proxy.data, value: 0n }
24009
+ };
24010
+ }
24011
+ async function executeCancelAction(walletClient, publicClient, accountDiamond, subAccount, functionName, quoteId) {
24012
+ const account = walletClient.account?.address;
24013
+ if (!account) throw new Error("Wallet client has no account");
24014
+ const prepared = prepareCancelAction(
24015
+ accountDiamond,
24016
+ account,
24017
+ subAccount,
24018
+ functionName,
24019
+ quoteId
24020
+ );
24021
+ const gas = await publicClient.estimateGas(prepared.config);
24022
+ return walletClient.sendTransaction({
24023
+ ...prepared.config,
24024
+ gas: calculateGasMargin(gas),
24025
+ chain: walletClient.chain
24026
+ });
24027
+ }
24028
+ function prepareCancelQuote(accountDiamond, account, subAccount, quoteId) {
24029
+ return prepareCancelAction(
24030
+ accountDiamond,
24031
+ account,
24032
+ subAccount,
24033
+ "requestToCancelQuote",
24034
+ quoteId
24035
+ );
24036
+ }
24037
+ function prepareCancelCloseRequest(accountDiamond, account, subAccount, quoteId) {
24038
+ return prepareCancelAction(
24039
+ accountDiamond,
24040
+ account,
24041
+ subAccount,
24042
+ "requestToCancelCloseRequest",
24043
+ quoteId
24044
+ );
24045
+ }
24046
+ function prepareForceCancelQuote(accountDiamond, account, subAccount, quoteId) {
24047
+ return prepareCancelAction(
24048
+ accountDiamond,
24049
+ account,
24050
+ subAccount,
24051
+ "forceCancelQuote",
24052
+ quoteId
24053
+ );
24054
+ }
24055
+ function prepareForceCancelCloseRequest(accountDiamond, account, subAccount, quoteId) {
24056
+ return prepareCancelAction(
24057
+ accountDiamond,
24058
+ account,
24059
+ subAccount,
24060
+ "forceCancelCloseRequest",
24061
+ quoteId
24062
+ );
24063
+ }
24064
+ async function cancelQuote(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
24065
+ return executeCancelAction(
24066
+ walletClient,
24067
+ publicClient,
24068
+ accountDiamond,
24069
+ subAccount,
24070
+ "requestToCancelQuote",
24071
+ quoteId
24072
+ );
24073
+ }
24074
+ async function cancelCloseRequest(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
24075
+ return executeCancelAction(
24076
+ walletClient,
24077
+ publicClient,
24078
+ accountDiamond,
24079
+ subAccount,
24080
+ "requestToCancelCloseRequest",
24081
+ quoteId
24082
+ );
24083
+ }
24084
+ async function forceCancelQuote(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
24085
+ return executeCancelAction(
24086
+ walletClient,
24087
+ publicClient,
24088
+ accountDiamond,
24089
+ subAccount,
24090
+ "forceCancelQuote",
24091
+ quoteId
24092
+ );
24093
+ }
24094
+ async function forceCancelCloseRequest(walletClient, publicClient, accountDiamond, subAccount, quoteId) {
24095
+ return executeCancelAction(
24096
+ walletClient,
24097
+ publicClient,
24098
+ accountDiamond,
24099
+ subAccount,
24100
+ "forceCancelCloseRequest",
24101
+ quoteId
24102
+ );
24103
+ }
24104
+
24105
+ // src/actions/approval.ts
24106
+ var approval_exports = {};
24107
+ __export(approval_exports, {
24108
+ ApprovalState: () => ApprovalState,
24109
+ approve: () => approve,
24110
+ getAllowance: () => getAllowance,
24111
+ getApprovalState: () => getApprovalState,
24112
+ getBalance: () => getBalance,
24113
+ getDecimals: () => getDecimals,
24114
+ prepareApprove: () => prepareApprove
24115
+ });
24116
+ var ApprovalState = /* @__PURE__ */ ((ApprovalState2) => {
24117
+ ApprovalState2["UNKNOWN"] = "UNKNOWN";
24118
+ ApprovalState2["NOT_APPROVED"] = "NOT_APPROVED";
24119
+ ApprovalState2["PENDING"] = "PENDING";
24120
+ ApprovalState2["APPROVED"] = "APPROVED";
24121
+ return ApprovalState2;
24122
+ })(ApprovalState || {});
24123
+ function prepareApprove(tokenAddress, account, spender, amount) {
24124
+ validateAddress(spender, "spender");
24125
+ const data = encodeFunctionData({
24126
+ abi: ERC20ABI,
24127
+ functionName: "approve",
24128
+ args: [spender, amount]
24129
+ });
24130
+ return {
24131
+ functionName: "approve",
24132
+ args: [spender, amount],
24133
+ config: { account, to: tokenAddress, data, value: 0n }
24134
+ };
24135
+ }
24136
+ async function approve(walletClient, publicClient, tokenAddress, spender, amount) {
24137
+ const account = walletClient.account?.address;
24138
+ if (!account) throw new Error("Wallet client has no account");
24139
+ const prepared = prepareApprove(tokenAddress, account, spender, amount);
24140
+ const gas = await publicClient.estimateGas(prepared.config);
24141
+ return walletClient.sendTransaction({
24142
+ ...prepared.config,
24143
+ gas: calculateGasMargin(gas),
24144
+ chain: walletClient.chain
24145
+ });
24146
+ }
24147
+ async function getAllowance(publicClient, tokenAddress, owner, spender) {
24148
+ return await publicClient.readContract({
24149
+ address: tokenAddress,
24150
+ abi: ERC20ABI,
24151
+ functionName: "allowance",
24152
+ args: [owner, spender]
24153
+ });
24154
+ }
24155
+ async function getBalance(publicClient, tokenAddress, account) {
24156
+ return await publicClient.readContract({
24157
+ address: tokenAddress,
24158
+ abi: ERC20ABI,
24159
+ functionName: "balanceOf",
24160
+ args: [account]
24161
+ });
24162
+ }
24163
+ async function getDecimals(publicClient, tokenAddress) {
24164
+ return await publicClient.readContract({
24165
+ address: tokenAddress,
24166
+ abi: ERC20ABI,
24167
+ functionName: "decimals"
24168
+ });
24169
+ }
24170
+ async function getApprovalState(publicClient, tokenAddress, owner, spender, requiredAmount) {
24171
+ try {
24172
+ const allowance = await getAllowance(publicClient, tokenAddress, owner, spender);
24173
+ if (allowance >= requiredAmount) {
24174
+ return "APPROVED" /* APPROVED */;
24175
+ }
24176
+ return "NOT_APPROVED" /* NOT_APPROVED */;
24177
+ } catch {
24178
+ return "UNKNOWN" /* UNKNOWN */;
24179
+ }
24180
+ }
24181
+
24182
+ // src/actions/delegation.ts
24183
+ var delegation_exports = {};
24184
+ __export(delegation_exports, {
24185
+ delegateAccess: () => delegateAccess,
24186
+ hasDelegatedAccess: () => hasDelegatedAccess,
24187
+ prepareDelegateAccess: () => prepareDelegateAccess,
24188
+ prepareProposeRevoke: () => prepareProposeRevoke,
24189
+ prepareRevokeAccess: () => prepareRevokeAccess,
24190
+ proposeRevoke: () => proposeRevoke,
24191
+ revokeAccess: () => revokeAccess
24192
+ });
24193
+ function prepareDelegateAccess(multiAccount, account, params) {
24194
+ validateAddress(params.account, "subAccount");
24195
+ validateAddress(params.target, "target");
24196
+ const data = encodeFunctionData({
24197
+ abi: MultiAccountABI,
24198
+ functionName: "delegateAccesses",
24199
+ args: [params.account, params.target, params.selectors, params.activate]
24200
+ });
24201
+ return {
24202
+ functionName: "delegateAccesses",
24203
+ args: [params.account, params.target, params.selectors, params.activate],
24204
+ config: { account, to: multiAccount, data, value: 0n }
24205
+ };
24206
+ }
24207
+ function prepareProposeRevoke(multiAccount, account, params) {
24208
+ const data = encodeFunctionData({
24209
+ abi: MultiAccountABI,
24210
+ functionName: "proposeToRevokeAccesses",
24211
+ args: [params.account, params.target, params.selectors]
24212
+ });
24213
+ return {
24214
+ functionName: "proposeToRevokeAccesses",
24215
+ args: [params.account, params.target, params.selectors],
24216
+ config: { account, to: multiAccount, data, value: 0n }
24217
+ };
24218
+ }
24219
+ function prepareRevokeAccess(multiAccount, account, params) {
24220
+ const data = encodeFunctionData({
24221
+ abi: MultiAccountABI,
24222
+ functionName: "revokeAccesses",
24223
+ args: [params.account, params.target, params.selectors]
24224
+ });
24225
+ return {
24226
+ functionName: "revokeAccesses",
24227
+ args: [params.account, params.target, params.selectors],
24228
+ config: { account, to: multiAccount, data, value: 0n }
24229
+ };
24230
+ }
24231
+ async function delegateAccess(walletClient, publicClient, multiAccount, params) {
24232
+ const account = walletClient.account?.address;
24233
+ if (!account) throw new Error("Wallet client has no account");
24234
+ const prepared = prepareDelegateAccess(multiAccount, account, params);
24235
+ const gas = await publicClient.estimateGas(prepared.config);
24236
+ return walletClient.sendTransaction({
24237
+ ...prepared.config,
24238
+ gas: calculateGasMargin(gas),
24239
+ chain: walletClient.chain
24240
+ });
24241
+ }
24242
+ async function proposeRevoke(walletClient, publicClient, multiAccount, params) {
24243
+ const account = walletClient.account?.address;
24244
+ if (!account) throw new Error("Wallet client has no account");
24245
+ const prepared = prepareProposeRevoke(multiAccount, account, params);
24246
+ const gas = await publicClient.estimateGas(prepared.config);
24247
+ return walletClient.sendTransaction({
24248
+ ...prepared.config,
24249
+ gas: calculateGasMargin(gas),
24250
+ chain: walletClient.chain
24251
+ });
24252
+ }
24253
+ async function revokeAccess(walletClient, publicClient, multiAccount, params) {
24254
+ const account = walletClient.account?.address;
24255
+ if (!account) throw new Error("Wallet client has no account");
24256
+ const prepared = prepareRevokeAccess(multiAccount, account, params);
24257
+ const gas = await publicClient.estimateGas(prepared.config);
24258
+ return walletClient.sendTransaction({
24259
+ ...prepared.config,
24260
+ gas: calculateGasMargin(gas),
24261
+ chain: walletClient.chain
24262
+ });
24263
+ }
24264
+ async function hasDelegatedAccess(publicClient, multiAccount, params) {
24265
+ validateAddress(params.account, "subAccount");
24266
+ validateAddress(params.target, "target");
24267
+ const result = await publicClient.readContract({
24268
+ address: multiAccount,
24269
+ abi: MultiAccountABI,
24270
+ functionName: "delegatedAccesses",
24271
+ args: [params.account, params.target, params.selector]
24272
+ });
24273
+ return Boolean(result);
24274
+ }
24275
+
24276
+ // src/actions/signature.ts
24277
+ var signature_exports = {};
24278
+ __export(signature_exports, {
24279
+ getCurrentMessage: () => getCurrentMessage,
24280
+ hasSignedCurrentVersion: () => hasSignedCurrentVersion,
24281
+ prepareStoreSignature: () => prepareStoreSignature,
24282
+ signTermsMessage: () => signTermsMessage,
24283
+ storeSignature: () => storeSignature
24284
+ });
24285
+ function prepareStoreSignature(signatureStore, account, signature) {
24286
+ const data = encodeFunctionData({
24287
+ abi: SignatureStoreABI,
24288
+ functionName: "storeSignatureForCurrentVersion",
24289
+ args: [signature]
24290
+ });
24291
+ return {
24292
+ functionName: "storeSignatureForCurrentVersion",
24293
+ args: [signature],
24294
+ config: { account, to: signatureStore, data, value: 0n }
24295
+ };
24296
+ }
24297
+ async function storeSignature(walletClient, publicClient, signatureStore, signature) {
24298
+ const account = walletClient.account?.address;
24299
+ if (!account) throw new Error("Wallet client has no account");
24300
+ const prepared = prepareStoreSignature(signatureStore, account, signature);
24301
+ const gas = await publicClient.estimateGas(prepared.config);
24302
+ return walletClient.sendTransaction({
24303
+ ...prepared.config,
24304
+ gas: calculateGasMargin(gas),
24305
+ chain: walletClient.chain
24306
+ });
24307
+ }
24308
+ async function signTermsMessage(walletClient, publicClient, signatureStore) {
24309
+ const account = walletClient.account;
24310
+ if (!account) throw new Error("Wallet client has no account");
24311
+ const message = await publicClient.readContract({
24312
+ address: signatureStore,
24313
+ abi: SignatureStoreABI,
24314
+ functionName: "getCurrentVersionMessage"
24315
+ });
24316
+ return walletClient.signMessage({
24317
+ account,
24318
+ message
24319
+ });
24320
+ }
24321
+ async function hasSignedCurrentVersion(publicClient, signatureStore, user) {
24322
+ return await publicClient.readContract({
24323
+ address: signatureStore,
24324
+ abi: SignatureStoreABI,
24325
+ functionName: "hasCurrentVersionSignature",
24326
+ args: [user]
24327
+ });
24328
+ }
24329
+ async function getCurrentMessage(publicClient, signatureStore) {
24330
+ return await publicClient.readContract({
24331
+ address: signatureStore,
24332
+ abi: SignatureStoreABI,
24333
+ functionName: "getCurrentVersionMessage"
24334
+ });
24335
+ }
24336
+
24337
+ // src/actions/admin.ts
24338
+ var admin_exports = {};
24339
+ __export(admin_exports, {
24340
+ grantRole: () => grantRole,
24341
+ prepareGrantRole: () => prepareGrantRole,
24342
+ prepareRevokeRole: () => prepareRevokeRole,
24343
+ revokeRole: () => revokeRole
24344
+ });
24345
+ function prepareGrantRole(symmioDiamond, account, role, grantee) {
24346
+ validateAddress(grantee, "grantee");
24347
+ const data = encodeFunctionData({
24348
+ abi: SymmioDiamondABI,
24349
+ functionName: "grantRole",
24350
+ args: [grantee, role]
24351
+ });
24352
+ return {
24353
+ functionName: "grantRole",
24354
+ args: [grantee, role],
24355
+ config: { account, to: symmioDiamond, data, value: 0n }
24356
+ };
24357
+ }
24358
+ function prepareRevokeRole(symmioDiamond, account, role, revokee) {
24359
+ validateAddress(revokee, "revokee");
24360
+ const data = encodeFunctionData({
24361
+ abi: SymmioDiamondABI,
24362
+ functionName: "revokeRole",
24363
+ args: [revokee, role]
24364
+ });
24365
+ return {
24366
+ functionName: "revokeRole",
24367
+ args: [revokee, role],
24368
+ config: { account, to: symmioDiamond, data, value: 0n }
24369
+ };
24370
+ }
24371
+ async function grantRole(walletClient, publicClient, symmioDiamond, role, grantee) {
24372
+ const account = walletClient.account?.address;
24373
+ if (!account) throw new Error("Wallet client has no account");
24374
+ const prepared = prepareGrantRole(symmioDiamond, account, role, grantee);
24375
+ const gas = await publicClient.estimateGas(prepared.config);
24376
+ return walletClient.sendTransaction({
24377
+ ...prepared.config,
24378
+ gas: calculateGasMargin(gas),
24379
+ chain: walletClient.chain
24380
+ });
24381
+ }
24382
+ async function revokeRole(walletClient, publicClient, symmioDiamond, role, revokee) {
24383
+ const account = walletClient.account?.address;
24384
+ if (!account) throw new Error("Wallet client has no account");
24385
+ const prepared = prepareRevokeRole(symmioDiamond, account, role, revokee);
24386
+ const gas = await publicClient.estimateGas(prepared.config);
24387
+ return walletClient.sendTransaction({
24388
+ ...prepared.config,
24389
+ gas: calculateGasMargin(gas),
24390
+ chain: walletClient.chain
24391
+ });
24392
+ }
24393
+
24394
+ // src/actions/instant.ts
24395
+ var instant_exports = {};
24396
+ __export(instant_exports, {
24397
+ cancelInstantClose: () => cancelInstantClose,
24398
+ createSiweMessage: () => createSiweMessage,
24399
+ getNonce: () => getNonce,
24400
+ getOpenInstantCloses: () => getOpenInstantCloses,
24401
+ instantClose: () => instantClose,
24402
+ instantOpen: () => instantOpen,
24403
+ login: () => login
24404
+ });
24405
+ function getHedgerBaseUrl(chainId) {
24406
+ const baseUrl = HEDGER_BASE_URLS[chainId];
24407
+ if (!baseUrl) {
24408
+ throw new Error(`No hedger base URL configured for chain ${chainId}.`);
24895
24409
  }
24896
- ];
24897
-
24898
- // src/abis/MuonVerifier.ts
24899
- var MuonVerifierABI = [
24900
- {
24901
- name: "addSignatureKey",
24902
- type: "function",
24903
- stateMutability: "nonpayable",
24904
- inputs: [
24905
- { name: "publicKey", type: "address" },
24906
- { name: "nodeId", type: "bytes32" }
24907
- ],
24908
- outputs: []
24909
- },
24910
- {
24911
- name: "removeSignatureKey",
24912
- type: "function",
24913
- stateMutability: "nonpayable",
24914
- inputs: [{ name: "publicKey", type: "address" }],
24915
- outputs: []
24916
- },
24917
- {
24918
- name: "rotateSignatureKey",
24919
- type: "function",
24920
- stateMutability: "nonpayable",
24921
- inputs: [
24922
- { name: "oldKey", type: "address" },
24923
- { name: "newKey", type: "address" }
24924
- ],
24925
- outputs: []
24926
- },
24927
- {
24928
- name: "isValidKey",
24929
- type: "function",
24930
- stateMutability: "view",
24931
- inputs: [{ name: "publicKey", type: "address" }],
24932
- outputs: [{ name: "valid", type: "bool" }]
24933
- },
24934
- {
24935
- name: "getActiveKeys",
24936
- type: "function",
24937
- stateMutability: "view",
24938
- inputs: [],
24939
- outputs: [{ name: "keys", type: "address[]" }]
24410
+ return baseUrl;
24411
+ }
24412
+ function createSiweMessage(params) {
24413
+ const version = params.version ?? "1";
24414
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
24415
+ const expirationTime = new Date(
24416
+ Date.now() + 30 * 24 * 60 * 60 * 1e3
24417
+ ).toISOString();
24418
+ const message = [
24419
+ `${params.domain} wants you to sign in with your Ethereum account:`,
24420
+ params.address,
24421
+ "",
24422
+ params.statement,
24423
+ "",
24424
+ `URI: ${params.uri}`,
24425
+ `Version: ${version}`,
24426
+ `Chain ID: ${params.chainId}`,
24427
+ `Nonce: ${params.nonce}`,
24428
+ `Issued At: ${issuedAt}`,
24429
+ `Expiration Time: ${expirationTime}`
24430
+ ].join("\n");
24431
+ return { message, issuedAt, expirationTime };
24432
+ }
24433
+ async function getNonce(chainId, subAccount) {
24434
+ const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24435
+ const url = new URL(`nonce/${subAccount}`, hedgerBaseUrl).href;
24436
+ const response = await fetch(url);
24437
+ if (!response.ok) {
24438
+ throw new Error(`Failed to fetch nonce: ${response.statusText}`);
24940
24439
  }
24941
- ];
24440
+ const data = await response.json();
24441
+ return data.nonce;
24442
+ }
24443
+ async function login(chainId, params) {
24444
+ const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24445
+ const url = new URL("login", hedgerBaseUrl).href;
24446
+ const body = {
24447
+ account_address: params.accountAddress,
24448
+ expiration_time: params.expirationTime,
24449
+ issued_at: params.issuedAt,
24450
+ signature: params.signature,
24451
+ nonce: params.nonce
24452
+ };
24453
+ const response = await fetch(url, {
24454
+ method: "POST",
24455
+ headers: { "Content-Type": "application/json" },
24456
+ body: JSON.stringify(body)
24457
+ });
24458
+ if (!response.ok) {
24459
+ const errorData = await response.json().catch(() => null);
24460
+ throw new Error(
24461
+ errorData?.error_message ?? `Login failed: ${response.statusText}`
24462
+ );
24463
+ }
24464
+ const data = await response.json();
24465
+ if (!data.access_token) {
24466
+ throw new Error("No access token received");
24467
+ }
24468
+ return {
24469
+ accessToken: data.access_token,
24470
+ expirationTime: params.expirationTime,
24471
+ issuedAt: params.issuedAt
24472
+ };
24473
+ }
24474
+ async function instantOpen(chainId, params, accessToken) {
24475
+ const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24476
+ const url = new URL("instant_open", hedgerBaseUrl).href;
24477
+ const body = {
24478
+ symbolId: params.symbolId,
24479
+ positionType: params.positionType,
24480
+ orderType: params.orderType,
24481
+ price: params.price,
24482
+ quantity: params.quantity,
24483
+ cva: params.cva,
24484
+ lf: params.lf,
24485
+ partyAmm: params.partyAmm,
24486
+ partyBmm: params.partyBmm,
24487
+ maxFundingRate: params.maxFundingRate,
24488
+ deadline: params.deadline
24489
+ };
24490
+ const response = await fetch(url, {
24491
+ method: "POST",
24492
+ headers: {
24493
+ "Content-Type": "application/json",
24494
+ Authorization: `Bearer ${accessToken}`
24495
+ },
24496
+ body: JSON.stringify(body)
24497
+ });
24498
+ if (!response.ok) {
24499
+ const errorData = await response.json().catch(() => null);
24500
+ throw new Error(
24501
+ errorData?.error_message ?? `Instant open failed: ${response.statusText}`
24502
+ );
24503
+ }
24504
+ return response.json();
24505
+ }
24506
+ async function instantClose(chainId, params, accessToken) {
24507
+ const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24508
+ const url = new URL("instant_close", hedgerBaseUrl).href;
24509
+ const body = {
24510
+ quote_id: params.quoteId,
24511
+ quantity_to_close: params.quantityToClose,
24512
+ close_price: params.closePrice
24513
+ };
24514
+ const response = await fetch(url, {
24515
+ method: "POST",
24516
+ headers: {
24517
+ "Content-Type": "application/json",
24518
+ Authorization: `Bearer ${accessToken}`
24519
+ },
24520
+ body: JSON.stringify(body)
24521
+ });
24522
+ if (!response.ok) {
24523
+ const errorData = await response.json().catch(() => null);
24524
+ throw new Error(
24525
+ errorData?.error_message ?? `Instant close failed: ${response.statusText}`
24526
+ );
24527
+ }
24528
+ return response.json();
24529
+ }
24530
+ async function cancelInstantClose(chainId, quoteId, accessToken) {
24531
+ const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24532
+ const url = new URL(`instant_close/${quoteId}`, hedgerBaseUrl).href;
24533
+ const response = await fetch(url, {
24534
+ method: "DELETE",
24535
+ headers: {
24536
+ "Content-Type": "application/json",
24537
+ Authorization: `Bearer ${accessToken}`
24538
+ }
24539
+ });
24540
+ if (!response.ok) {
24541
+ const errorData = await response.json().catch(() => null);
24542
+ throw new Error(
24543
+ errorData?.error_message ?? `Cancel instant close failed: ${response.statusText}`
24544
+ );
24545
+ }
24546
+ }
24547
+ async function getOpenInstantCloses(chainId, account, accessToken) {
24548
+ const hedgerBaseUrl = getHedgerBaseUrl(chainId);
24549
+ const url = new URL(`instant_close/${account}`, hedgerBaseUrl).href;
24550
+ const response = await fetch(url, {
24551
+ headers: {
24552
+ Authorization: `Bearer ${accessToken}`
24553
+ }
24554
+ });
24555
+ if (!response.ok) {
24556
+ const errorData = await response.json().catch(() => null);
24557
+ throw new Error(
24558
+ errorData?.error_message ?? `Failed to fetch instant closes: ${response.statusText}`
24559
+ );
24560
+ }
24561
+ return response.json();
24562
+ }
24942
24563
 
24943
- // src/constants/selectors.ts
24944
- var SEND_QUOTE_WITH_AFFILIATE_SELECTOR = "0x40f1310c";
24945
- var CLOSE_QUOTE_SELECTOR = "0x501e891f";
24946
- var ALL_TRADING_SELECTORS = [
24947
- SEND_QUOTE_WITH_AFFILIATE_SELECTOR,
24948
- CLOSE_QUOTE_SELECTOR
24949
- ];
24564
+ // src/actions/stats.ts
24565
+ var stats_exports = {};
24566
+ __export(stats_exports, {
24567
+ calculateAvailableForOrder: () => calculateAvailableForOrder,
24568
+ getPartyAStats: () => getPartyAStats
24569
+ });
24570
+ async function getPartyAStats(publicClient, symmioDiamond, partyA) {
24571
+ const result = await publicClient.readContract({
24572
+ address: symmioDiamond,
24573
+ abi: SymmioDiamondABI,
24574
+ functionName: "partyAStats",
24575
+ args: [partyA]
24576
+ });
24577
+ return {
24578
+ collateralBalance: result[1],
24579
+ allocatedBalance: result[2],
24580
+ availableBalance: result[3],
24581
+ lockedCVA: result[4],
24582
+ lockedLF: result[5],
24583
+ lockedPartyAMM: result[6],
24584
+ lockedPartyBMM: result[7],
24585
+ pendingLockedCVA: result[8],
24586
+ pendingLockedLF: result[9],
24587
+ pendingLockedPartyAMM: result[10],
24588
+ pendingLockedPartyBMM: result[11],
24589
+ positionsCount: Number(result[12]),
24590
+ pendingCount: Number(result[13]),
24591
+ nonces: 0
24592
+ };
24593
+ }
24594
+ function calculateAvailableForOrder(stats, upnl) {
24595
+ const {
24596
+ allocatedBalance,
24597
+ lockedCVA,
24598
+ lockedLF,
24599
+ lockedPartyAMM,
24600
+ pendingLockedCVA,
24601
+ pendingLockedLF,
24602
+ pendingLockedPartyAMM
24603
+ } = stats;
24604
+ const totalPendingLocked = pendingLockedCVA + pendingLockedLF + pendingLockedPartyAMM;
24605
+ if (upnl >= 0n) {
24606
+ const totalLocked = lockedCVA + lockedLF + lockedPartyAMM;
24607
+ return allocatedBalance + upnl - totalLocked - totalPendingLocked;
24608
+ }
24609
+ const absUpnl = -upnl;
24610
+ const consideringMm = absUpnl > lockedPartyAMM ? absUpnl : lockedPartyAMM;
24611
+ return allocatedBalance - lockedCVA - lockedLF - totalPendingLocked - consideringMm;
24612
+ }
24950
24613
 
24951
24614
  // src/utils/formatting.ts
24952
24615
  function toWei(amount, decimals) {
@@ -24979,6 +24642,6 @@ function applySlippage(price, slippagePercent, isLong) {
24979
24642
  return price - price * bps / 10000n;
24980
24643
  }
24981
24644
 
24982
- export { ALL_TRADING_SELECTORS, AffiliateFeeLevel, ApprovalState, CHAIN_NAMES, CLEARING_HOUSE_ADDRESS, CLOSE_QUOTE_SELECTOR, COLLATERAL_ADDRESS, COLLATERAL_DECIMALS, ClearingHouseABI, ClearingHouseLiquidationStatus, DEFAULT_PARTY_B_ADDRESS, DEFAULT_PRECISION, ERC20ABI, FALLBACK_CHAIN_ID, InstantCloseStatus, LIMIT_ORDER_DEADLINE, LiquidationStatus, MARKET_ORDER_DEADLINE, MARKET_PRICE_COEFFICIENT, MAX_LEVERAGE, MULTI_ACCOUNT_ADDRESS, MUON_APP_NAME, MUON_BASE_URLS, MultiAccountABI, MuonClient, MuonVerifierABI, OrderType, PositionType, QuoteStatus, SEND_QUOTE_WITH_AFFILIATE_SELECTOR, SIGNATURE_STORE_ADDRESS, STANDARD_WITHDRAW_COOLDOWN, SYMMIO_DIAMOND_ADDRESS, SignatureStoreABI, SoftLiquidationLevel, SupportedChainId, SymmioDiamondABI, SymmioSDK, SymmioSDKError, V3_CHAIN_IDS, account_exports as accountActions, admin_exports as adminActions, allocate_exports as allocateActions, applySlippage, approval_exports as approvalActions, calculateGasMargin, cancel_exports as cancelActions, close_exports as closeActions, delegation_exports as delegationActions, deposit_exports as depositActions, encodeCall, formatPrice, fromWei, getAddress, instant_exports as instantActions, signature_exports as signatureActions, stats_exports as statsActions, toWei, trade_exports as tradeActions, validateAddress, validateAmount, validateChainId, validateDeadline, validateQuantity, withdraw_exports as withdrawActions, wrapInProxyCall };
24645
+ export { ALL_TRADING_SELECTORS, AffiliateFeeLevel, ApprovalState, CHAIN_NAMES, CLEARING_HOUSE_ADDRESS, CLOSE_QUOTE_SELECTOR, COLLATERAL_ADDRESS, COLLATERAL_DECIMALS, ClearingHouseABI, ClearingHouseLiquidationStatus, DEFAULT_PARTY_B_ADDRESS, DEFAULT_PRECISION, ERC20ABI, FALLBACK_CHAIN_ID, InstantCloseStatus, LIMIT_ORDER_DEADLINE, LiquidationStatus, MARKET_ORDER_DEADLINE, MARKET_PRICE_COEFFICIENT, MAX_LEVERAGE, MULTI_ACCOUNT_ADDRESS, MUON_APP_NAME, MUON_BASE_URLS, MultiAccountABI, MuonClient, MuonVerifierABI, OrderType, PositionType, QuoteStatus, SEND_QUOTE_WITH_AFFILIATE_SELECTOR, SIGNATURE_STORE_ADDRESS, STANDARD_WITHDRAW_COOLDOWN, SYMMIO_DIAMOND_ADDRESS, SignatureStoreABI, SoftLiquidationLevel, SupportedChainId, SymmioDiamondABI, SymmioSDKError, V3_CHAIN_IDS, account_exports as accountActions, admin_exports as adminActions, allocate_exports as allocateActions, applySlippage, approval_exports as approvalActions, calculateGasMargin, cancel_exports as cancelActions, close_exports as closeActions, delegation_exports as delegationActions, deposit_exports as depositActions, encodeCall, formatPrice, fromWei, getAddress, instant_exports as instantActions, signature_exports as signatureActions, stats_exports as statsActions, toWei, trade_exports as tradeActions, validateAddress, validateAmount, validateChainId, validateDeadline, validateQuantity, withdraw_exports as withdrawActions, wrapInProxyCall };
24983
24646
  //# sourceMappingURL=index.mjs.map
24984
24647
  //# sourceMappingURL=index.mjs.map