aiia-vault-sdk 1.2.15 → 1.2.16

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.
@@ -0,0 +1,300 @@
1
+ import { ethers } from "ethers";
2
+ import { ParsedEthStakingEvent, ParsedEthStakingEventRaw, RawEthStakingEventTypes } from "./types";
3
+ import { type SendTransactionMutateAsync } from "@wagmi/core/query";
4
+ import { Config } from "@wagmi/core/dist/types/createConfig";
5
+ export declare class EthStakingSDK {
6
+ name: string;
7
+ private contract;
8
+ private providers;
9
+ private contractAddress;
10
+ private isBootstrapped;
11
+ constructor(rpcUrls: string | string[], contractAddress?: string);
12
+ private getRandomProvider;
13
+ private getContractWithRandomProvider;
14
+ bootstrap(): Promise<void>;
15
+ signAndSendTransaction(tx: ethers.ContractTransaction, wallet: ethers.Wallet | SendTransactionMutateAsync<Config, any>, callbacks?: {
16
+ onSubmit?: (tx: string) => void | Promise<void>;
17
+ onFinally?: (status: {
18
+ status: boolean | null;
19
+ confirmations: number;
20
+ txHash: string;
21
+ isCompleted: boolean;
22
+ attempts: number;
23
+ }) => void | Promise<void>;
24
+ onError?: (error: Error) => void | Promise<void>;
25
+ }): Promise<{
26
+ transaction: {
27
+ hash: string;
28
+ };
29
+ status: {
30
+ status: boolean | null;
31
+ confirmations: number;
32
+ isCompleted: boolean;
33
+ attempts: number;
34
+ };
35
+ }>;
36
+ /**
37
+ * Builds a transaction to stake ETH to the contract
38
+ * @param amount Amount of ETH to stake in wei (as bigint)
39
+ * @returns Populated transaction
40
+ */
41
+ buildStakeTxRaw(amount: bigint): Promise<ethers.ContractTransaction>;
42
+ /**
43
+ * Builds a transaction to stake ETH to the contract
44
+ * @param amount Amount of ETH to stake in ether
45
+ * @returns Populated transaction
46
+ */
47
+ buildStakeTx(amount: number): Promise<ethers.ContractTransaction>;
48
+ /**
49
+ * Builds a transaction to unstake ETH
50
+ * @param amount Amount to unstake in wei (as bigint)
51
+ * @returns Populated transaction
52
+ */
53
+ buildUnstakeTxRaw(amount: bigint): Promise<ethers.ContractTransaction>;
54
+ /**
55
+ * Builds a transaction to unstake ETH
56
+ * @param amount Amount to unstake in ether
57
+ * @returns Populated transaction
58
+ */
59
+ buildUnstakeTx(amount: number): Promise<ethers.ContractTransaction>;
60
+ /**
61
+ * Builds a transaction to claim rewards
62
+ * @param amount Reward amount to claim in wei (as bigint)
63
+ * @param nonce Unique nonce to prevent replay attacks
64
+ * @param deadline Timestamp after which signature is invalid
65
+ * @param signature Signature from authorized signer
66
+ * @returns Populated transaction
67
+ */
68
+ buildClaimRewardTxRaw(amount: bigint, nonce: bigint, deadline: bigint, signature: string): Promise<ethers.ContractTransaction>;
69
+ /**
70
+ * Builds a transaction to claim rewards
71
+ * @param amount Reward amount to claim in ether
72
+ * @param nonce Unique nonce to prevent replay attacks
73
+ * @param deadline Timestamp after which signature is invalid
74
+ * @param signature Signature from authorized signer
75
+ * @returns Populated transaction
76
+ */
77
+ buildClaimRewardTx(amount: number, nonce: number, deadline: number, signature: string): Promise<ethers.ContractTransaction>;
78
+ /**
79
+ * Builds a transaction to unstake and claim in one transaction
80
+ * @param unstakeAmount Unstake amount in wei (as bigint)
81
+ * @param rewardAmount Reward amount in wei (as bigint)
82
+ * @param nonce Unique nonce to prevent replay attacks
83
+ * @param deadline Timestamp after which signature is invalid
84
+ * @param signature Signature from authorized signer
85
+ * @returns Populated transaction
86
+ */
87
+ buildUnstakeAndClaimTxRaw(unstakeAmount: bigint, rewardAmount: bigint, nonce: bigint, deadline: bigint, signature: string): Promise<ethers.ContractTransaction>;
88
+ /**
89
+ * Builds a transaction to unstake and claim in one transaction
90
+ * @param unstakeAmount Unstake amount in ether
91
+ * @param rewardAmount Reward amount in ether
92
+ * @param nonce Unique nonce to prevent replay attacks
93
+ * @param deadline Timestamp after which signature is invalid
94
+ * @param signature Signature from authorized signer
95
+ * @returns Populated transaction
96
+ */
97
+ buildUnstakeAndClaimTx(unstakeAmount: number, rewardAmount: number, nonce: number, deadline: number, signature: string): Promise<ethers.ContractTransaction>;
98
+ /**
99
+ * Builds a transaction to add rewards to the contract
100
+ * @param amount Amount to add in wei (as bigint)
101
+ * @returns Populated transaction
102
+ */
103
+ buildAddRewardsTxRaw(amount: bigint): Promise<ethers.ContractTransaction>;
104
+ /**
105
+ * Builds a transaction to add rewards to the contract
106
+ * @param amount Amount to add in ether
107
+ * @returns Populated transaction
108
+ */
109
+ buildAddRewardsTx(amount: number): Promise<ethers.ContractTransaction>;
110
+ /**
111
+ * Builds a transaction to update the maximum reward amount
112
+ * @param newMaxReward New maximum reward amount in wei (as bigint)
113
+ * @returns Populated transaction
114
+ */
115
+ buildUpdateMaxRewardAmountTxRaw(newMaxReward: bigint): Promise<ethers.ContractTransaction>;
116
+ /**
117
+ * Builds a transaction to update the maximum reward amount
118
+ * @param newMaxReward New maximum reward amount in ether
119
+ * @returns Populated transaction
120
+ */
121
+ buildUpdateMaxRewardAmountTx(newMaxReward: number): Promise<ethers.ContractTransaction>;
122
+ /**
123
+ * Builds a transaction to set the minimum stake amount
124
+ * @param newMinStake New minimum stake amount in wei (as bigint)
125
+ * @returns Populated transaction
126
+ */
127
+ buildSetMinStakeAmountTxRaw(newMinStake: bigint): Promise<ethers.ContractTransaction>;
128
+ /**
129
+ * Builds a transaction to set the minimum stake amount
130
+ * @param newMinStake New minimum stake amount in ether
131
+ * @returns Populated transaction
132
+ */
133
+ buildSetMinStakeAmountTx(newMinStake: number): Promise<ethers.ContractTransaction>;
134
+ /**
135
+ * Builds a transaction to add a new signer
136
+ * @param signer Address of the new signer
137
+ * @returns Populated transaction
138
+ */
139
+ buildAddSignerTx(signer: string): Promise<ethers.ContractTransaction>;
140
+ /**
141
+ * Builds a transaction to remove a signer
142
+ * @param signer Address of the signer to remove
143
+ * @returns Populated transaction
144
+ */
145
+ buildRemoveSignerTx(signer: string): Promise<ethers.ContractTransaction>;
146
+ /**
147
+ * Builds a transaction to pause the contract
148
+ * @returns Populated transaction
149
+ */
150
+ buildPauseTx(): Promise<ethers.ContractTransaction>;
151
+ /**
152
+ * Builds a transaction to unpause the contract
153
+ * @returns Populated transaction
154
+ */
155
+ buildUnpauseTx(): Promise<ethers.ContractTransaction>;
156
+ /**
157
+ * Builds a transaction to emergency unstake all funds
158
+ * @param recipient Address to receive the funds
159
+ * @returns Populated transaction
160
+ */
161
+ buildEmergencyUnstakeTx(recipient: string): Promise<ethers.ContractTransaction>;
162
+ /**
163
+ * Gets total staked ETH in the contract in wei
164
+ * @returns Total staked amount as bigint
165
+ */
166
+ getTotalStakedRaw(): Promise<bigint>;
167
+ /**
168
+ * Gets total staked ETH in the contract in ether
169
+ * @returns Total staked amount as number
170
+ */
171
+ getTotalStaked(): Promise<number>;
172
+ /**
173
+ * Gets total rewards distributed in wei
174
+ * @returns Total rewards as bigint
175
+ */
176
+ getTotalRewardsRaw(): Promise<bigint>;
177
+ /**
178
+ * Gets total rewards distributed in ether
179
+ * @returns Total rewards as number
180
+ */
181
+ getTotalRewards(): Promise<number>;
182
+ /**
183
+ * Gets maximum reward amount allowed in a single claim in wei
184
+ * @returns Maximum reward amount as bigint
185
+ */
186
+ getMaxRewardAmountRaw(): Promise<bigint>;
187
+ /**
188
+ * Gets maximum reward amount allowed in a single claim in ether
189
+ * @returns Maximum reward amount as number
190
+ */
191
+ getMaxRewardAmount(): Promise<number>;
192
+ /**
193
+ * Gets minimum stake amount in wei
194
+ * @returns Minimum stake amount as bigint
195
+ */
196
+ getMinStakeAmountRaw(): Promise<bigint>;
197
+ /**
198
+ * Gets minimum stake amount in ether
199
+ * @returns Minimum stake amount as number
200
+ */
201
+ getMinStakeAmount(): Promise<number>;
202
+ /**
203
+ * Gets user's stake and total claimed rewards in wei
204
+ * @param user Address of the user
205
+ * @returns Object containing stake and claimed rewards as bigint
206
+ */
207
+ getUserInfoRaw(user: string): Promise<{
208
+ stake: bigint;
209
+ claimed: bigint;
210
+ }>;
211
+ /**
212
+ * Gets user's stake and total claimed rewards in ether
213
+ * @param user Address of the user
214
+ * @returns Object containing stake and claimed rewards as number
215
+ */
216
+ getUserInfo(user: string): Promise<{
217
+ stake: number;
218
+ claimed: number;
219
+ }>;
220
+ /**
221
+ * Gets user's stake in wei
222
+ * @param user Address of the user
223
+ * @returns User's stake as bigint
224
+ */
225
+ getUserStakeRaw(user: string): Promise<bigint>;
226
+ /**
227
+ * Gets user's stake in ether
228
+ * @param user Address of the user
229
+ * @returns User's stake as number
230
+ */
231
+ getUserStake(user: string): Promise<number>;
232
+ /**
233
+ * Gets user's total rewards claimed in wei
234
+ * @param user Address of the user
235
+ * @returns User's total rewards claimed as bigint
236
+ */
237
+ getUserTotalRewardsClaimedRaw(user: string): Promise<bigint>;
238
+ /**
239
+ * Gets user's total rewards claimed in ether
240
+ * @param user Address of the user
241
+ * @returns User's total rewards claimed as number
242
+ */
243
+ getUserTotalRewardsClaimed(user: string): Promise<number>;
244
+ /**
245
+ * Checks if the contract is paused
246
+ * @returns Boolean indicating if contract is paused
247
+ */
248
+ isPaused(): Promise<boolean>;
249
+ /**
250
+ * Gets the OPERATOR_ROLE hash
251
+ * @returns The OPERATOR_ROLE hash
252
+ */
253
+ getOperatorRoleHash(): Promise<string>;
254
+ /**
255
+ * Gets the SIGNER_ROLE hash
256
+ * @returns The SIGNER_ROLE hash
257
+ */
258
+ getSignerRoleHash(): Promise<string>;
259
+ /**
260
+ * Gets the DEFAULT_ADMIN_ROLE hash
261
+ * @returns The DEFAULT_ADMIN_ROLE hash
262
+ */
263
+ getAdminRoleHash(): Promise<string>;
264
+ /**
265
+ * Checks if an address has the operator role
266
+ * @param address Address to check
267
+ * @returns Boolean indicating if the address has operator role
268
+ */
269
+ hasOperatorRole(address: string): Promise<boolean>;
270
+ /**
271
+ * Checks if an address has the signer role
272
+ * @param address Address to check
273
+ * @returns Boolean indicating if the address has signer role
274
+ */
275
+ hasSignerRole(address: string): Promise<boolean>;
276
+ /**
277
+ * Checks if an address has the admin role
278
+ * @param address Address to check
279
+ * @returns Boolean indicating if the address has admin role
280
+ */
281
+ hasAdminRole(address: string): Promise<boolean>;
282
+ /**
283
+ * Creates a signature for claiming rewards
284
+ * @param contractAddress Address of the EthStaking contract
285
+ * @param userAddress Address of the user claiming rewards
286
+ * @param amount Reward amount in ether
287
+ * @param nonce Unique nonce to prevent replay attacks
288
+ * @param deadline Timestamp after which signature is invalid
289
+ * @param signerPrivateKey Private key of the authorized signer
290
+ * @returns Signature and message hash
291
+ */
292
+ createRewardSignature(contractAddress: string, userAddress: string, amount: number, nonce: number, deadline: number, signerPrivateKey: string): {
293
+ signature: string;
294
+ messageHash: string;
295
+ };
296
+ getContractAddress(): string;
297
+ getAllEvents(fromBlock: number, toBlock: number, whitelistEvents?: Array<keyof RawEthStakingEventTypes>): Promise<ParsedEthStakingEventRaw[]>;
298
+ streamEvents(fromBlock: number, onEvent: (event: ParsedEthStakingEvent) => Promise<void>, saveLatestBlock: (blockNumber: number) => Promise<void>, batchSize?: number, sleepTime?: number, blockGap?: number): Promise<void>;
299
+ formatEventArgs: (event: ParsedEthStakingEventRaw) => ParsedEthStakingEvent;
300
+ }
@@ -0,0 +1 @@
1
+ "use strict";var t=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EthStakingSDK=void 0;const a=require("ethers"),e=t(require("./abis/EthStaking.json")),r=t(require("./contracts.json")),s=require("./utils");exports.EthStakingSDK=class{constructor(t,n){this.name="EthStaking",this.isBootstrapped=!1,this.formatEventArgs=t=>{const{eventName:e,args:r}=t;switch(e){case"Staked":case"Unstaked":return{...t,args:{...r,user:r.user.toLowerCase(),amount:Number(a.ethers.formatEther(r.amount)),timestamp:Number(r.timestamp)}};case"RewardClaimed":return{...t,args:{...r,user:r.user.toLowerCase(),amount:Number(a.ethers.formatEther(r.amount)),timestamp:Number(r.timestamp),signatureHash:r.signatureHash}};case"SignerUpdated":return{...t,args:{...r,newSigner:r.newSigner.toLowerCase()}};case"MinStakeUpdated":return{...t,args:{...r,oldAmount:Number(a.ethers.formatEther(r.oldAmount)),newAmount:Number(a.ethers.formatEther(r.newAmount))}};default:return t}};const i=Array.isArray(t)?t:[t];this.providers=i.map((t=>new a.ethers.JsonRpcProvider(t,void 0,{staticNetwork:!0})));const o=(0,s.getRandomProvider)(this.providers);this.contractAddress=(0,s.resolveContractAddress)(i[0],this.name,r.default,n),this.contract=new a.ethers.Contract(this.contractAddress,e.default.abi,o)}getRandomProvider(){return(0,s.getRandomProvider)(this.providers)}getContractWithRandomProvider(){return new a.ethers.Contract(this.contractAddress,e.default.abi,this.getRandomProvider())}async bootstrap(){if(this.isBootstrapped)return;const t=await Promise.all(this.providers.map(((t,a)=>(0,s.checkRpcHealth)(t,a))));if(this.providers=this.providers.filter(((a,e)=>t[e])),0===this.providers.length)throw new Error("No active RPC providers available");this.isBootstrapped=!0}async signAndSendTransaction(t,a,e={}){return(0,s.signAndSendTransaction)(t,a,(()=>this.getRandomProvider()),e,this.contract)}async buildStakeTxRaw(t){return await this.contract.stake.populateTransaction({value:t})}async buildStakeTx(t){return await this.buildStakeTxRaw(a.ethers.parseEther(t.toString()))}async buildUnstakeTxRaw(t){return await this.contract.unstake.populateTransaction(t)}async buildUnstakeTx(t){return await this.buildUnstakeTxRaw(a.ethers.parseEther(t.toString()))}async buildClaimRewardTxRaw(t,a,e,r){return await this.contract.claimReward.populateTransaction(t,a,e,r)}async buildClaimRewardTx(t,e,r,s){return await this.buildClaimRewardTxRaw(a.ethers.parseEther(t.toString()),BigInt(e),BigInt(r),s)}async buildUnstakeAndClaimTxRaw(t,a,e,r,s){return await this.contract.unstakeAndClaim.populateTransaction(t,a,e,r,s)}async buildUnstakeAndClaimTx(t,e,r,s,n){return await this.buildUnstakeAndClaimTxRaw(a.ethers.parseEther(t.toString()),a.ethers.parseEther(e.toString()),BigInt(r),BigInt(s),n)}async buildAddRewardsTxRaw(t){return await this.contract.addRewards.populateTransaction({value:t})}async buildAddRewardsTx(t){return await this.buildAddRewardsTxRaw(a.ethers.parseEther(t.toString()))}async buildUpdateMaxRewardAmountTxRaw(t){return await this.contract.updateMaxRewardAmount.populateTransaction(t)}async buildUpdateMaxRewardAmountTx(t){return await this.buildUpdateMaxRewardAmountTxRaw(a.ethers.parseEther(t.toString()))}async buildSetMinStakeAmountTxRaw(t){return await this.contract.setMinStakeAmount.populateTransaction(t)}async buildSetMinStakeAmountTx(t){return await this.buildSetMinStakeAmountTxRaw(a.ethers.parseEther(t.toString()))}async buildAddSignerTx(t){return await this.contract.addSigner.populateTransaction(t)}async buildRemoveSignerTx(t){return await this.contract.removeSigner.populateTransaction(t)}async buildPauseTx(){return await this.contract.pause.populateTransaction()}async buildUnpauseTx(){return await this.contract.unpause.populateTransaction()}async buildEmergencyUnstakeTx(t){return await this.contract.emergencyUnstake.populateTransaction(t)}async getTotalStakedRaw(){return await this.contract.totalStaked()}async getTotalStaked(){const t=await this.getTotalStakedRaw();return Number(a.ethers.formatEther(t))}async getTotalRewardsRaw(){return await this.contract.totalRewards()}async getTotalRewards(){const t=await this.getTotalRewardsRaw();return Number(a.ethers.formatEther(t))}async getMaxRewardAmountRaw(){return await this.contract.maxRewardAmount()}async getMaxRewardAmount(){const t=await this.getMaxRewardAmountRaw();return Number(a.ethers.formatEther(t))}async getMinStakeAmountRaw(){return await this.contract.minStakeAmount()}async getMinStakeAmount(){const t=await this.getMinStakeAmountRaw();return Number(a.ethers.formatEther(t))}async getUserInfoRaw(t){const[a,e]=await this.contract.getUserInfo(t);return{stake:a,claimed:e}}async getUserInfo(t){const{stake:e,claimed:r}=await this.getUserInfoRaw(t);return{stake:Number(a.ethers.formatEther(e)),claimed:Number(a.ethers.formatEther(r))}}async getUserStakeRaw(t){return await this.contract.userStakes(t)}async getUserStake(t){const e=await this.getUserStakeRaw(t);return Number(a.ethers.formatEther(e))}async getUserTotalRewardsClaimedRaw(t){return await this.contract.userTotalRewardsClaimed(t)}async getUserTotalRewardsClaimed(t){const e=await this.getUserTotalRewardsClaimedRaw(t);return Number(a.ethers.formatEther(e))}async isPaused(){return await this.contract.paused()}async getOperatorRoleHash(){return await this.contract.OPERATOR_ROLE()}async getSignerRoleHash(){return await this.contract.SIGNER_ROLE()}async getAdminRoleHash(){return await this.contract.DEFAULT_ADMIN_ROLE()}async hasOperatorRole(t){const a=await this.contract.OPERATOR_ROLE();return await this.contract.hasRole(a,t)}async hasSignerRole(t){const a=await this.contract.SIGNER_ROLE();return await this.contract.hasRole(a,t)}async hasAdminRole(t){const a=await this.contract.DEFAULT_ADMIN_ROLE();return await this.contract.hasRole(a,t)}createRewardSignature(t,e,r,s,n,i){const o=a.ethers.parseEther(r.toString()),c=a.ethers.solidityPackedKeccak256(["address","address","uint256","uint256","uint256"],[t,e,o,s,n]);return{signature:new a.ethers.Wallet(i).signingKey.sign(a.ethers.getBytes(c)).serialized,messageHash:c.toString()}}getContractAddress(){return this.contractAddress}async getAllEvents(t,a,e){return await this.bootstrap(),(0,s.getAllEvents)(this.contract,(()=>this.getRandomProvider()),(()=>this.getContractWithRandomProvider()),t,a,e)}async streamEvents(t,a,e,r=1e3,n=5e3,i=0){const o=["Staked","Unstaked","RewardClaimed","SignerUpdated","MinStakeUpdated"];return await this.bootstrap(),(0,s.streamEvents)({getProvider:()=>this.getRandomProvider(),getAllEvents:(t,a)=>this.getAllEvents(t,a,o),formatEvent:t=>this.formatEventArgs(t),onEvent:a,saveLatestBlock:e,fromBlock:t,batchSize:r,sleepTime:n,blockGap:i})}};
@@ -403,6 +403,50 @@ export declare class TradingVaultSDK {
403
403
  * @returns Populated transaction
404
404
  */
405
405
  buildBatchSetPositionExpirationTxRaw(tokenIds: bigint[], expiredAts: bigint[]): Promise<ethers.ContractTransaction>;
406
+ /**
407
+ * Builds a transaction to update entry price for a position
408
+ *
409
+ * @param tokenId - ID of the position
410
+ * @param newEntryPrice - New entry price for the position
411
+ * @returns Populated transaction
412
+ *
413
+ * @example
414
+ * ```typescript
415
+ * const tx = await sdk.buildUpdateEntryPriceTx(128, 110); // Update entry price to 110
416
+ * ```
417
+ */
418
+ buildUpdateEntryPriceTx(tokenId: number, newEntryPrice: number): Promise<ethers.ContractTransaction>;
419
+ /**
420
+ * Builds a raw transaction to update entry price for a position
421
+ *
422
+ * @param tokenId - ID of the position as bigint
423
+ * @param newEntryPrice - New entry price as bigint
424
+ * @returns Populated transaction
425
+ */
426
+ buildUpdateEntryPriceTxRaw(tokenId: bigint, newEntryPrice: bigint): Promise<ethers.ContractTransaction>;
427
+ /**
428
+ * Builds a transaction to batch update entry prices for multiple positions
429
+ *
430
+ * @param tokenIds - Array of position IDs
431
+ * @param newEntryPrices - Array of new entry prices
432
+ * @returns Populated transaction
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * const tokenIds = [128, 129, 130];
437
+ * const newPrices = [110, 112, 115];
438
+ * const tx = await sdk.buildBatchUpdateEntryPriceTx(tokenIds, newPrices);
439
+ * ```
440
+ */
441
+ buildBatchUpdateEntryPriceTx(tokenIds: number[], newEntryPrices: number[]): Promise<ethers.ContractTransaction>;
442
+ /**
443
+ * Builds a raw transaction to batch update entry prices for multiple positions
444
+ *
445
+ * @param tokenIds - Array of position IDs as bigint
446
+ * @param newEntryPrices - Array of new entry prices as bigint
447
+ * @returns Populated transaction
448
+ */
449
+ buildBatchUpdateEntryPriceTxRaw(tokenIds: bigint[], newEntryPrices: bigint[]): Promise<ethers.ContractTransaction>;
406
450
  /**
407
451
  * Builds a transaction to close an expired position with a provided price
408
452
  *
@@ -1 +1 @@
1
- "use strict";var t=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TradingVaultSDK=void 0;const e=require("ethers"),r=t(require("./abis/TradingVault.json")),a=t(require("./contracts.json")),n=require("./utils");exports.TradingVaultSDK=class{constructor(t,i){this.name="TradingVault",this._currency=null,this._rewardToken=null,this._currencyDecimals=null,this._rewardTokenDecimals=null,this.priceDecimals=6,this.isBootstrapped=!1,this.configs=[],this.BASE_WEIGHT=1e4,this.BASE_PRICE=100,this.formatEventArgs=t=>{const e=this._currencyDecimals,r=this._rewardTokenDecimals,{eventName:a,args:n}=t;switch(a){case"PositionCreated":return{...t,args:{...n,user:n.user.toLowerCase(),amount:Number(n.amount)/Math.pow(10,e),entryPrice:Number(n.entryPrice)/Math.pow(10,this.priceDecimals),tokenId:Number(n.tokenId),openedAt:Number(n.openedAt),expiredAt:Number(n.expiredAt),currency:n.currency.toLowerCase()}};case"PositionReduced":return{...t,args:{...n,user:n.user.toLowerCase(),reducedAmount:Number(n.reducedAmount)/Math.pow(10,e),remainingAmount:Number(n.remainingAmount)/Math.pow(10,e),totalReward:Number(n.totalReward)/Math.pow(10,r),userReward:Number(n.userReward)/Math.pow(10,r),treasuryReward:Number(n.treasuryReward)/Math.pow(10,r),rewardedAmount:Number(n.rewardedAmount)/Math.pow(10,r),weight:Number(n.weight),tokenId:Number(n.tokenId),lossAmount:Number(n.lossAmount)/Math.pow(10,e),price:Number(n.price)/Math.pow(10,this.priceDecimals),loss:Number(n.loss)/Math.pow(10,e)}};case"CurrencyBorrowed":case"CurrencyRepaid":return{...t,args:{...n,amount:Number(n.amount)/Math.pow(10,e),borrower:n.borrower.toLowerCase()}};case"PriceUpdated":return{...t,args:{...n,oldPrice:Number(n.oldPrice)/Math.pow(10,this.priceDecimals),newPrice:Number(n.newPrice)/Math.pow(10,this.priceDecimals),requiredReward:Number(n.requiredReward)/Math.pow(10,r),timestamp:Number(n.timestamp)}};case"TotalAmountUpdated":return{...t,args:{...n,newTotalAmount:Number(n.newTotalAmount)/Math.pow(10,e)}};case"CurrencyUpdated":return{...t,args:{...n,oldCurrency:n.oldCurrency.toLowerCase(),newCurrency:n.newCurrency.toLowerCase()}};case"RewardTokenUpdated":return{...t,args:{...n,oldRewardToken:n.oldRewardToken.toLowerCase(),newRewardToken:n.newRewardToken.toLowerCase()}};case"ReduceEnabledUpdated":return{...t,args:{...n,enabled:n.enabled}};case"TreasuryUpdated":return{...t,args:{...n,oldTreasury:n.oldTreasury.toLowerCase(),newTreasury:n.newTreasury.toLowerCase()}};case"RewardConfigsUpdated":return{...t,args:{...n}};case"TotalRewardsUpdated":case"TotalRewardsHarvestedUpdated":return{...t,args:{...n,oldAmount:Number(n.oldAmount)/Math.pow(10,r),newAmount:Number(n.newAmount)/Math.pow(10,r)}};case"Transfer":return{...t,args:{...n,from:n.from.toLowerCase(),to:n.to.toLowerCase(),value:Number(n.value)}};default:return t}};const o=Array.isArray(t)?t:[t];this.providers=o.map((t=>new e.ethers.JsonRpcProvider(t,void 0,{staticNetwork:!0})));const s=(0,n.getRandomProvider)(this.providers);this.contractAddress=(0,n.resolveContractAddress)(o[0],this.name,a.default,i),this.contract=new e.ethers.Contract(this.contractAddress,r.default.abi,s)}getRandomProvider(){return(0,n.getRandomProvider)(this.providers)}getContractWithRandomProvider(){return new e.ethers.Contract(this.contractAddress,r.default.abi,this.getRandomProvider())}async bootstrap(){if(this.isBootstrapped)return;const t=await Promise.all(this.providers.map(((t,e)=>(0,n.checkRpcHealth)(t,e))));if(this.providers=this.providers.filter(((e,r)=>t[r])),0===this.providers.length)throw new Error("No active RPC providers available");await Promise.all([this.getCurrencyDecimals(),this.getRewardTokenDecimals(),(async()=>{const t=await this.getRewardConfigsLength(),e=[];for(let r=0;r<t;r++)e.push(this.getRewardConfig(r));const r=await Promise.all(e);this.configs=r.map((t=>({weight:Number(t.weight)/this.BASE_WEIGHT,duration:Number(t.duration)})))})()]),this.isBootstrapped=!0}async signAndSendTransaction(t,e,r={}){return(0,n.signAndSendTransaction)(t,e,(()=>this.getRandomProvider()),r,this.contract)}async buildCreatePositionTx(t,e,r=0){const a=await this.getCurrencyDecimals(),n=BigInt(Math.floor(t*Math.pow(10,a)));return this.buildCreatePositionTxRaw(n,e,BigInt(r))}async buildReducePositionTx(t,e){const r=await this.getCurrencyDecimals(),a=BigInt(Math.floor(e*Math.pow(10,r)));return this.buildReducePositionTxRaw(t,a)}async buildReducePositionsTx(t,e){const r=await this.getCurrencyDecimals(),a=e.map((t=>BigInt(Math.floor(t*Math.pow(10,r)))));return this.buildReducePositionsTxRaw(t,a)}async buildBorrowCurrencyTx(t){const e=await this.getCurrencyDecimals(),r=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildBorrowCurrencyTxRaw(r)}async buildRepayCurrencyTx(t){const e=await this.getCurrencyDecimals(),r=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildRepayCurrencyTxRaw(r)}async buildSetPriceTx(t){const e=BigInt(Math.round(t*Math.pow(10,this.priceDecimals)));return await this.buildSetPriceTxRaw(e)}async buildBatchEmitPriceUpdatedTx(t){const e=t.map((t=>({price:BigInt(Math.round(t.price*Math.pow(10,this.priceDecimals))),timestamp:BigInt(t.timestamp)})));return await this.buildBatchEmitPriceUpdatedTxRaw(e)}async buildBatchEmitPriceUpdatedTxRaw(t){return await this.contract.batchEmitPriceUpdated.populateTransaction(t)}async buildClaimERC20Tx(t,r){const a=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),n=await a.decimals(),i=BigInt(Math.floor(r*Math.pow(10,n)));return this.buildClaimERC20TxRaw(t,i)}async buildCreatePositionTxRaw(t,e,r=0n){return await this.contract.createPosition.populateTransaction(t,e,r)}async buildReducePositionTxRaw(t,e){return await this.contract.reducePosition.populateTransaction(t,e)}async buildReducePositionsTxRaw(t,e){return await this.contract.reducePositions.populateTransaction(t,e)}async buildBorrowCurrencyTxRaw(t){return await this.contract.borrowCurrency.populateTransaction(t)}async buildRepayCurrencyTxRaw(t){return await this.contract.repayCurrency.populateTransaction(t)}async buildSetPriceTxRaw(t){return await this.contract.setPrice.populateTransaction(t)}async buildSetCurrencyTxRaw(t){this._currency=null;return await this.contract.setCurrency.populateTransaction(t)}async buildSetRewardTokenTxRaw(t){this._rewardToken=null;return await this.contract.setRewardToken.populateTransaction(t)}async buildSetTreasuryTxRaw(t){return await this.contract.setTreasury.populateTransaction(t)}async buildUpdateRewardConfigsTxRaw(t){return await this.contract.updateRewardConfigs.populateTransaction(t)}async buildSetReduceEnabledTxRaw(t){return await this.contract.setReduceEnabled.populateTransaction(t)}async buildClaimERC20TxRaw(t,e){return await this.contract.claimERC20.populateTransaction(t,e)}async buildApproveERC20Tx(t,r,a){const n=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),i=await n.decimals(),o=BigInt(Math.floor(a*Math.pow(10,Number(i))));return this.buildApproveERC20TxRaw(t,r,o)}async buildApproveERC20TxRaw(t,e,r){return await(0,n.buildApproveERC20Tx)(t,e,r,this.getRandomProvider())}async getAllowanceRaw(t,e,r){return await(0,n.getTokenAllowance)(t,e,r,this.getRandomProvider())}async getAllowance(t,e,r){const[a,i]=await Promise.all([this.getAllowanceRaw(t,e,r),(0,n.getTokenDecimals)(t,this.getRandomProvider())]);return Number(a)/Math.pow(10,i)}async buildGrantOperatorRoleTxRaw(t){return await this.contract.grantOperatorRole.populateTransaction(t)}async getOperatorRoleHash(){return await this.contract.OPERATOR_ROLE()}async hasOperatorRole(t){const e=await this.contract.OPERATOR_ROLE();return await this.contract.hasRole(e,t)}async buildGrantOperatorRoleTx(t){return await this.contract.grantOperatorRole.populateTransaction(t)}async getPriceSetterRoleHash(){return await this.contract.PRICE_SETTER_ROLE()}async hasPriceSetterRole(t){const e=await this.contract.PRICE_SETTER_ROLE();return await this.contract.hasRole(e,t)}async buildGrantPriceSetterRoleTx(t){return await this.contract.grantPriceSetterRole.populateTransaction(t)}async getAdminRoleHash(){return await this.contract.DEFAULT_ADMIN_ROLE()}async hasAdminRole(t){const e=await this.contract.DEFAULT_ADMIN_ROLE();return await this.contract.hasRole(e,t)}async buildGrantAdminRoleTx(t){const e=await this.contract.DEFAULT_ADMIN_ROLE();return await this.contract.grantRole.populateTransaction(e,t)}async getPrice(){const t=await this.getPriceRaw(),e=this.priceDecimals;return Number(t)/Math.pow(10,e)}async getPriceRaw(){return await this.contract.price()}async getCurrency(){return this._currency||(this._currency=await this.contract.currency()),this._currency}async getRewardToken(){return this._rewardToken||(this._rewardToken=await this.contract.rewardToken()),this._rewardToken}async getTreasury(){return await this.contract.treasury()}async getTotalAmount(){const t=await this.getTotalAmountRaw(),e=await this.getCurrencyDecimals();return Number(t)/Math.pow(10,e)}async getTotalAmountRaw(){return await this.contract.totalAmount()}async getTotalBorrowed(){const t=await this.getTotalBorrowedRaw(),e=await this.getCurrencyDecimals();return Number(t)/Math.pow(10,e)}async getTotalBorrowedRaw(){return await this.contract.totalBorrowed()}async isReduceEnabled(){return await this.contract.isReduceEnabled()}async getPosition(t){const e=await this.getPositionRaw(t),r=await this.getCurrencyDecimals(),a=await this.getRewardTokenDecimals(),n=this.priceDecimals;return{remainingAmount:Number(e.remainingAmount)/Math.pow(10,r),entryPrice:Number(e.entryPrice)/Math.pow(10,n),outPrice:Number(e.outPrice)/Math.pow(10,n),openedAt:Number(e.openedAt),closedAt:Number(e.closedAt),rewardedAmount:Number(e.rewardedAmount)/Math.pow(10,a),lossAmount:Number(e.lossAmount)/Math.pow(10,r),initAmount:Number(e.initAmount)/Math.pow(10,r),expiredAt:Number(e.expiredAt)}}async getPositionRaw(t){return await this.contract.positions(t)}async getRewardConfig(t){return await this.contract.rewardConfigs(t)}async getRewardConfigsLength(){return await this.contract.getRewardConfigsLength()}async getCurrencyDecimals(){if(null===this._currencyDecimals){const t=await this.getCurrency(),r=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider());this._currencyDecimals=Number(await r.decimals())}return this._currencyDecimals}async getRewardTokenDecimals(){if(null===this._rewardTokenDecimals){const t=await this.getRewardToken(),r=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider());this._rewardTokenDecimals=Number(await r.decimals())}return this._rewardTokenDecimals}async getERC721BalanceOf(t){const e=await this.getERC721BalanceOfRaw(t);return Number(e)}async getERC721BalanceOfRaw(t){return await this.contract.balanceOf(t)}getContractAddress(){return this.contractAddress}getConfigs(){return[...this.configs]}async getAllEvents(t,e,r){return await this.bootstrap(),(0,n.getAllEvents)(this.contract,(()=>this.getRandomProvider()),(()=>this.getContractWithRandomProvider()),t,e,r)}async streamEvents(t,e,r,a=1e3,i=5e3,o=0){const s=["CurrencyBorrowed","CurrencyRepaid","CurrencyUpdated","PositionCreated","PositionReduced","PriceUpdated","ReduceEnabledUpdated","RewardConfigsUpdated","RewardTokenUpdated","TotalAmountUpdated","TotalRewardsHarvestedUpdated","TotalRewardsUpdated","Transfer","TreasuryUpdated"];return await this.bootstrap(),(0,n.streamEvents)({getProvider:()=>this.getRandomProvider(),getAllEvents:(t,e)=>this.getAllEvents(t,e,s),formatEvent:t=>this.formatEventArgs(t),onEvent:e,saveLatestBlock:r,fromBlock:t,batchSize:a,sleepTime:i,blockGap:o})}estimateUnrealizedPnl({price:t,entryPrice:e,initAmount:r,remainingAmount:a}){const n=a*(t-e)/this.BASE_PRICE;return{pnl:n,pnlPercentage:n/r*100}}estReducePosition({amount:t,price:e,entryPrice:r,openedAt:a,configs:n=[]}){const i=this.BASE_PRICE;this.BASE_WEIGHT;let o=t,s=0,c=0,u=0,d=0;if(e<r){return o=t-t*(r-e)/100,{amount:o,totalReward:0,userReward:0,treasuryReward:0,weight:0}}if(e>=r){s=t*(e-r)/i;const o=Math.floor(Date.now()/1e3)-a;d=this.getRewardWeight(o,n),c=s*d,u=s-c}return{amount:o,totalReward:s,userReward:c,treasuryReward:u,weight:d}}estReducePositions({positions:t,price:e,configs:r=[]}){return t.map((t=>this.estReducePosition({amount:t.amount,price:e,entryPrice:t.entryPrice,openedAt:t.openedAt,configs:r}))).reduce(((t,e)=>({amount:t.amount+e.amount,totalReward:t.totalReward+e.totalReward,userReward:t.userReward+e.userReward,treasuryReward:t.treasuryReward+e.treasuryReward})),{amount:0,totalReward:0,userReward:0,treasuryReward:0})}getRewardWeight(t,e){return(0,n.getRewardWeight)(t,e)}estimateUnrealizedPnls({price:t,positions:e}){return e.reduce(((e,r)=>{const{pnl:a}=this.estimateUnrealizedPnl({price:t,...r});return{totalInitAmount:e.totalInitAmount+r.initAmount,totalRemainingAmount:e.totalRemainingAmount+r.remainingAmount,totalRewardedAmount:e.totalRewardedAmount+r.rewardedAmount,totalLossAmount:e.totalLossAmount+r.lossAmount,totalPnl:e.totalPnl+a}}),{totalInitAmount:0,totalRemainingAmount:0,totalRewardedAmount:0,totalLossAmount:0,totalPnl:0})}async buildAddReward(t){const e=await this.getRewardTokenDecimals(),r=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildAddRewardTxRaw(r)}async buildAddRewardTxRaw(t){return await this.contract.addReward.populateTransaction(t)}async ownerOf(t){const e="number"==typeof t?BigInt(t):t;return await this.contract.ownerOf(e)}async isOwnerOf(t,e){try{return(await this.ownerOf(t)).toLowerCase()===e.toLowerCase()}catch(t){return!1}}async buildSetPositionExpirationTx(t,e){return this.buildSetPositionExpirationTxRaw(BigInt(t),BigInt(e))}async buildSetPositionExpirationTxRaw(t,e){return await this.contract.setPositionExpiration.populateTransaction(t,e)}async buildBatchSetPositionExpirationTx(t,e){const r=t.map((t=>BigInt(t))),a=e.map((t=>BigInt(t)));return this.buildBatchSetPositionExpirationTxRaw(r,a)}async buildBatchSetPositionExpirationTxRaw(t,e){return await this.contract.batchSetPositionExpiration.populateTransaction(t,e)}async buildCloseExpiredPositionTx(t,e){const r=BigInt(Math.round(e*Math.pow(10,this.priceDecimals)));return this.buildCloseExpiredPositionTxRaw(BigInt(t),r)}async buildCloseExpiredPositionTxRaw(t,e){return await this.contract.closeExpiredPosition.populateTransaction(t,e)}};
1
+ "use strict";var t=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TradingVaultSDK=void 0;const e=require("ethers"),r=t(require("./abis/TradingVault.json")),a=t(require("./contracts.json")),n=require("./utils");exports.TradingVaultSDK=class{constructor(t,i){this.name="TradingVault",this._currency=null,this._rewardToken=null,this._currencyDecimals=null,this._rewardTokenDecimals=null,this.priceDecimals=6,this.isBootstrapped=!1,this.configs=[],this.BASE_WEIGHT=1e4,this.BASE_PRICE=100,this.formatEventArgs=t=>{const e=this._currencyDecimals,r=this._rewardTokenDecimals,{eventName:a,args:n}=t;switch(a){case"PositionCreated":return{...t,args:{...n,user:n.user.toLowerCase(),amount:Number(n.amount)/Math.pow(10,e),entryPrice:Number(n.entryPrice)/Math.pow(10,this.priceDecimals),tokenId:Number(n.tokenId),openedAt:Number(n.openedAt),expiredAt:Number(n.expiredAt),currency:n.currency.toLowerCase()}};case"EntryPriceUpdated":return{...t,args:{...n,tokenId:Number(n.tokenId),oldEntryPrice:Number(n.oldEntryPrice)/Math.pow(10,this.priceDecimals),newEntryPrice:Number(n.newEntryPrice)/Math.pow(10,this.priceDecimals)}};case"PositionExpirationUpdated":return{...t,args:{...n,tokenId:Number(n.tokenId),expiredAt:Number(n.expiredAt)}};case"PositionReduced":return{...t,args:{...n,user:n.user.toLowerCase(),reducedAmount:Number(n.reducedAmount)/Math.pow(10,e),remainingAmount:Number(n.remainingAmount)/Math.pow(10,e),totalReward:Number(n.totalReward)/Math.pow(10,r),userReward:Number(n.userReward)/Math.pow(10,r),treasuryReward:Number(n.treasuryReward)/Math.pow(10,r),rewardedAmount:Number(n.rewardedAmount)/Math.pow(10,r),weight:Number(n.weight),tokenId:Number(n.tokenId),lossAmount:Number(n.lossAmount)/Math.pow(10,e),price:Number(n.price)/Math.pow(10,this.priceDecimals),loss:Number(n.loss)/Math.pow(10,e)}};case"CurrencyBorrowed":case"CurrencyRepaid":return{...t,args:{...n,amount:Number(n.amount)/Math.pow(10,e),borrower:n.borrower.toLowerCase()}};case"PriceUpdated":return{...t,args:{...n,oldPrice:Number(n.oldPrice)/Math.pow(10,this.priceDecimals),newPrice:Number(n.newPrice)/Math.pow(10,this.priceDecimals),requiredReward:Number(n.requiredReward)/Math.pow(10,r),timestamp:Number(n.timestamp)}};case"TotalAmountUpdated":return{...t,args:{...n,newTotalAmount:Number(n.newTotalAmount)/Math.pow(10,e)}};case"CurrencyUpdated":return{...t,args:{...n,oldCurrency:n.oldCurrency.toLowerCase(),newCurrency:n.newCurrency.toLowerCase()}};case"RewardTokenUpdated":return{...t,args:{...n,oldRewardToken:n.oldRewardToken.toLowerCase(),newRewardToken:n.newRewardToken.toLowerCase()}};case"ReduceEnabledUpdated":return{...t,args:{...n,enabled:n.enabled}};case"TreasuryUpdated":return{...t,args:{...n,oldTreasury:n.oldTreasury.toLowerCase(),newTreasury:n.newTreasury.toLowerCase()}};case"RewardConfigsUpdated":return{...t,args:{...n}};case"TotalRewardsUpdated":case"TotalRewardsHarvestedUpdated":return{...t,args:{...n,oldAmount:Number(n.oldAmount)/Math.pow(10,r),newAmount:Number(n.newAmount)/Math.pow(10,r)}};case"Transfer":return{...t,args:{...n,from:n.from.toLowerCase(),to:n.to.toLowerCase(),value:Number(n.value)}};default:return t}};const o=Array.isArray(t)?t:[t];this.providers=o.map((t=>new e.ethers.JsonRpcProvider(t,void 0,{staticNetwork:!0})));const s=(0,n.getRandomProvider)(this.providers);this.contractAddress=(0,n.resolveContractAddress)(o[0],this.name,a.default,i),this.contract=new e.ethers.Contract(this.contractAddress,r.default.abi,s)}getRandomProvider(){return(0,n.getRandomProvider)(this.providers)}getContractWithRandomProvider(){return new e.ethers.Contract(this.contractAddress,r.default.abi,this.getRandomProvider())}async bootstrap(){if(this.isBootstrapped)return;const t=await Promise.all(this.providers.map(((t,e)=>(0,n.checkRpcHealth)(t,e))));if(this.providers=this.providers.filter(((e,r)=>t[r])),0===this.providers.length)throw new Error("No active RPC providers available");await Promise.all([this.getCurrencyDecimals(),this.getRewardTokenDecimals(),(async()=>{const t=await this.getRewardConfigsLength(),e=[];for(let r=0;r<t;r++)e.push(this.getRewardConfig(r));const r=await Promise.all(e);this.configs=r.map((t=>({weight:Number(t.weight)/this.BASE_WEIGHT,duration:Number(t.duration)})))})()]),this.isBootstrapped=!0}async signAndSendTransaction(t,e,r={}){return(0,n.signAndSendTransaction)(t,e,(()=>this.getRandomProvider()),r,this.contract)}async buildCreatePositionTx(t,e,r=0){const a=await this.getCurrencyDecimals(),n=BigInt(Math.floor(t*Math.pow(10,a)));return this.buildCreatePositionTxRaw(n,e,BigInt(r))}async buildReducePositionTx(t,e){const r=await this.getCurrencyDecimals(),a=BigInt(Math.floor(e*Math.pow(10,r)));return this.buildReducePositionTxRaw(t,a)}async buildReducePositionsTx(t,e){const r=await this.getCurrencyDecimals(),a=e.map((t=>BigInt(Math.floor(t*Math.pow(10,r)))));return this.buildReducePositionsTxRaw(t,a)}async buildBorrowCurrencyTx(t){const e=await this.getCurrencyDecimals(),r=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildBorrowCurrencyTxRaw(r)}async buildRepayCurrencyTx(t){const e=await this.getCurrencyDecimals(),r=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildRepayCurrencyTxRaw(r)}async buildSetPriceTx(t){const e=BigInt(Math.round(t*Math.pow(10,this.priceDecimals)));return await this.buildSetPriceTxRaw(e)}async buildBatchEmitPriceUpdatedTx(t){const e=t.map((t=>({price:BigInt(Math.round(t.price*Math.pow(10,this.priceDecimals))),timestamp:BigInt(t.timestamp)})));return await this.buildBatchEmitPriceUpdatedTxRaw(e)}async buildBatchEmitPriceUpdatedTxRaw(t){return await this.contract.batchEmitPriceUpdated.populateTransaction(t)}async buildClaimERC20Tx(t,r){const a=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),n=await a.decimals(),i=BigInt(Math.floor(r*Math.pow(10,n)));return this.buildClaimERC20TxRaw(t,i)}async buildCreatePositionTxRaw(t,e,r=0n){return await this.contract.createPosition.populateTransaction(t,e,r)}async buildReducePositionTxRaw(t,e){return await this.contract.reducePosition.populateTransaction(t,e)}async buildReducePositionsTxRaw(t,e){return await this.contract.reducePositions.populateTransaction(t,e)}async buildBorrowCurrencyTxRaw(t){return await this.contract.borrowCurrency.populateTransaction(t)}async buildRepayCurrencyTxRaw(t){return await this.contract.repayCurrency.populateTransaction(t)}async buildSetPriceTxRaw(t){return await this.contract.setPrice.populateTransaction(t)}async buildSetCurrencyTxRaw(t){this._currency=null;return await this.contract.setCurrency.populateTransaction(t)}async buildSetRewardTokenTxRaw(t){this._rewardToken=null;return await this.contract.setRewardToken.populateTransaction(t)}async buildSetTreasuryTxRaw(t){return await this.contract.setTreasury.populateTransaction(t)}async buildUpdateRewardConfigsTxRaw(t){return await this.contract.updateRewardConfigs.populateTransaction(t)}async buildSetReduceEnabledTxRaw(t){return await this.contract.setReduceEnabled.populateTransaction(t)}async buildClaimERC20TxRaw(t,e){return await this.contract.claimERC20.populateTransaction(t,e)}async buildApproveERC20Tx(t,r,a){const n=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),i=await n.decimals(),o=BigInt(Math.floor(a*Math.pow(10,Number(i))));return this.buildApproveERC20TxRaw(t,r,o)}async buildApproveERC20TxRaw(t,e,r){return await(0,n.buildApproveERC20Tx)(t,e,r,this.getRandomProvider())}async getAllowanceRaw(t,e,r){return await(0,n.getTokenAllowance)(t,e,r,this.getRandomProvider())}async getAllowance(t,e,r){const[a,i]=await Promise.all([this.getAllowanceRaw(t,e,r),(0,n.getTokenDecimals)(t,this.getRandomProvider())]);return Number(a)/Math.pow(10,i)}async buildGrantOperatorRoleTxRaw(t){return await this.contract.grantOperatorRole.populateTransaction(t)}async getOperatorRoleHash(){return await this.contract.OPERATOR_ROLE()}async hasOperatorRole(t){const e=await this.contract.OPERATOR_ROLE();return await this.contract.hasRole(e,t)}async buildGrantOperatorRoleTx(t){return await this.contract.grantOperatorRole.populateTransaction(t)}async getPriceSetterRoleHash(){return await this.contract.PRICE_SETTER_ROLE()}async hasPriceSetterRole(t){const e=await this.contract.PRICE_SETTER_ROLE();return await this.contract.hasRole(e,t)}async buildGrantPriceSetterRoleTx(t){return await this.contract.grantPriceSetterRole.populateTransaction(t)}async getAdminRoleHash(){return await this.contract.DEFAULT_ADMIN_ROLE()}async hasAdminRole(t){const e=await this.contract.DEFAULT_ADMIN_ROLE();return await this.contract.hasRole(e,t)}async buildGrantAdminRoleTx(t){const e=await this.contract.DEFAULT_ADMIN_ROLE();return await this.contract.grantRole.populateTransaction(e,t)}async getPrice(){const t=await this.getPriceRaw(),e=this.priceDecimals;return Number(t)/Math.pow(10,e)}async getPriceRaw(){return await this.contract.price()}async getCurrency(){return this._currency||(this._currency=await this.contract.currency()),this._currency}async getRewardToken(){return this._rewardToken||(this._rewardToken=await this.contract.rewardToken()),this._rewardToken}async getTreasury(){return await this.contract.treasury()}async getTotalAmount(){const t=await this.getTotalAmountRaw(),e=await this.getCurrencyDecimals();return Number(t)/Math.pow(10,e)}async getTotalAmountRaw(){return await this.contract.totalAmount()}async getTotalBorrowed(){const t=await this.getTotalBorrowedRaw(),e=await this.getCurrencyDecimals();return Number(t)/Math.pow(10,e)}async getTotalBorrowedRaw(){return await this.contract.totalBorrowed()}async isReduceEnabled(){return await this.contract.isReduceEnabled()}async getPosition(t){const e=await this.getPositionRaw(t),r=await this.getCurrencyDecimals(),a=await this.getRewardTokenDecimals(),n=this.priceDecimals;return{remainingAmount:Number(e.remainingAmount)/Math.pow(10,r),entryPrice:Number(e.entryPrice)/Math.pow(10,n),outPrice:Number(e.outPrice)/Math.pow(10,n),openedAt:Number(e.openedAt),closedAt:Number(e.closedAt),rewardedAmount:Number(e.rewardedAmount)/Math.pow(10,a),lossAmount:Number(e.lossAmount)/Math.pow(10,r),initAmount:Number(e.initAmount)/Math.pow(10,r),expiredAt:Number(e.expiredAt)}}async getPositionRaw(t){return await this.contract.positions(t)}async getRewardConfig(t){return await this.contract.rewardConfigs(t)}async getRewardConfigsLength(){return await this.contract.getRewardConfigsLength()}async getCurrencyDecimals(){if(null===this._currencyDecimals){const t=await this.getCurrency(),r=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider());this._currencyDecimals=Number(await r.decimals())}return this._currencyDecimals}async getRewardTokenDecimals(){if(null===this._rewardTokenDecimals){const t=await this.getRewardToken(),r=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider());this._rewardTokenDecimals=Number(await r.decimals())}return this._rewardTokenDecimals}async getERC721BalanceOf(t){const e=await this.getERC721BalanceOfRaw(t);return Number(e)}async getERC721BalanceOfRaw(t){return await this.contract.balanceOf(t)}getContractAddress(){return this.contractAddress}getConfigs(){return[...this.configs]}async getAllEvents(t,e,r){return await this.bootstrap(),(0,n.getAllEvents)(this.contract,(()=>this.getRandomProvider()),(()=>this.getContractWithRandomProvider()),t,e,r)}async streamEvents(t,e,r,a=1e3,i=5e3,o=0){const s=["CurrencyBorrowed","CurrencyRepaid","CurrencyUpdated","EntryPriceUpdated","PositionCreated","PositionExpirationUpdated","PositionReduced","PriceUpdated","ReduceEnabledUpdated","RewardConfigsUpdated","RewardTokenUpdated","TotalAmountUpdated","TotalRewardsHarvestedUpdated","TotalRewardsUpdated","Transfer","TreasuryUpdated"];return await this.bootstrap(),(0,n.streamEvents)({getProvider:()=>this.getRandomProvider(),getAllEvents:(t,e)=>this.getAllEvents(t,e,s),formatEvent:t=>this.formatEventArgs(t),onEvent:e,saveLatestBlock:r,fromBlock:t,batchSize:a,sleepTime:i,blockGap:o})}estimateUnrealizedPnl({price:t,entryPrice:e,initAmount:r,remainingAmount:a}){const n=a*(t-e)/this.BASE_PRICE;return{pnl:n,pnlPercentage:n/r*100}}estReducePosition({amount:t,price:e,entryPrice:r,openedAt:a,configs:n=[]}){const i=this.BASE_PRICE;this.BASE_WEIGHT;let o=t,s=0,c=0,u=0,d=0;if(e<r){return o=t-t*(r-e)/100,{amount:o,totalReward:0,userReward:0,treasuryReward:0,weight:0}}if(e>=r){s=t*(e-r)/i;const o=Math.floor(Date.now()/1e3)-a;d=this.getRewardWeight(o,n),c=s*d,u=s-c}return{amount:o,totalReward:s,userReward:c,treasuryReward:u,weight:d}}estReducePositions({positions:t,price:e,configs:r=[]}){return t.map((t=>this.estReducePosition({amount:t.amount,price:e,entryPrice:t.entryPrice,openedAt:t.openedAt,configs:r}))).reduce(((t,e)=>({amount:t.amount+e.amount,totalReward:t.totalReward+e.totalReward,userReward:t.userReward+e.userReward,treasuryReward:t.treasuryReward+e.treasuryReward})),{amount:0,totalReward:0,userReward:0,treasuryReward:0})}getRewardWeight(t,e){return(0,n.getRewardWeight)(t,e)}estimateUnrealizedPnls({price:t,positions:e}){return e.reduce(((e,r)=>{const{pnl:a}=this.estimateUnrealizedPnl({price:t,...r});return{totalInitAmount:e.totalInitAmount+r.initAmount,totalRemainingAmount:e.totalRemainingAmount+r.remainingAmount,totalRewardedAmount:e.totalRewardedAmount+r.rewardedAmount,totalLossAmount:e.totalLossAmount+r.lossAmount,totalPnl:e.totalPnl+a}}),{totalInitAmount:0,totalRemainingAmount:0,totalRewardedAmount:0,totalLossAmount:0,totalPnl:0})}async buildAddReward(t){const e=await this.getRewardTokenDecimals(),r=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildAddRewardTxRaw(r)}async buildAddRewardTxRaw(t){return await this.contract.addReward.populateTransaction(t)}async ownerOf(t){const e="number"==typeof t?BigInt(t):t;return await this.contract.ownerOf(e)}async isOwnerOf(t,e){try{return(await this.ownerOf(t)).toLowerCase()===e.toLowerCase()}catch(t){return!1}}async buildSetPositionExpirationTx(t,e){return this.buildSetPositionExpirationTxRaw(BigInt(t),BigInt(e))}async buildSetPositionExpirationTxRaw(t,e){return await this.contract.setPositionExpiration.populateTransaction(t,e)}async buildBatchSetPositionExpirationTx(t,e){const r=t.map((t=>BigInt(t))),a=e.map((t=>BigInt(t)));return this.buildBatchSetPositionExpirationTxRaw(r,a)}async buildBatchSetPositionExpirationTxRaw(t,e){return await this.contract.batchSetPositionExpiration.populateTransaction(t,e)}async buildUpdateEntryPriceTx(t,e){const r=BigInt(Math.round(e*Math.pow(10,this.priceDecimals)));return this.buildUpdateEntryPriceTxRaw(BigInt(t),r)}async buildUpdateEntryPriceTxRaw(t,e){return await this.contract.updateEntryPrice.populateTransaction(t,e)}async buildBatchUpdateEntryPriceTx(t,e){const r=t.map((t=>BigInt(t))),a=e.map((t=>BigInt(Math.round(t*Math.pow(10,this.priceDecimals)))));return this.buildBatchUpdateEntryPriceTxRaw(r,a)}async buildBatchUpdateEntryPriceTxRaw(t,e){return await this.contract.batchUpdateEntryPrice.populateTransaction(t,e)}async buildCloseExpiredPositionTx(t,e){const r=BigInt(Math.round(e*Math.pow(10,this.priceDecimals)));return this.buildCloseExpiredPositionTxRaw(BigInt(t),r)}async buildCloseExpiredPositionTxRaw(t,e){return await this.contract.closeExpiredPosition.populateTransaction(t,e)}};