aiia-vault-sdk 1.4.1 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,6 +30,26 @@ export interface MaxReferralLevelsUpdatedEvent {
30
30
  oldValue: number;
31
31
  newValue: number;
32
32
  }
33
+ export interface SharePercentUpdatedEvent {
34
+ oldValue: number;
35
+ newValue: number;
36
+ }
37
+ export interface MaxRewardUpdatedEvent {
38
+ oldValue: number;
39
+ newValue: number;
40
+ }
41
+ export interface NFTSoldEvent {
42
+ seller: string;
43
+ tokenIds: number[];
44
+ reward: number;
45
+ timestamp: number;
46
+ }
47
+ export interface SignerAddedEvent {
48
+ signer: string;
49
+ }
50
+ export interface SignerRemovedEvent {
51
+ signer: string;
52
+ }
33
53
  export interface TransferEvent {
34
54
  from: string;
35
55
  to: string;
@@ -215,4 +235,64 @@ export declare class MultiLevelReferralNFTSDK {
215
235
  getAllEvents(fromBlock: number, toBlock: number, whitelistEvents?: string[]): Promise<ParsedMultiLevelReferralNFTEventRaw[]>;
216
236
  streamEvents(fromBlock: number, onEvent: (event: ParsedMultiLevelReferralNFTEvent) => Promise<void>, saveLatestBlock: (blockNumber: number) => Promise<void>, batchSize?: number, sleepTime?: number, blockGap?: number, shouldContinue?: () => Promise<boolean> | boolean): Promise<void>;
217
237
  formatEventArgs: (event: ParsedMultiLevelReferralNFTEventRaw) => ParsedMultiLevelReferralNFTEvent;
238
+ /**
239
+ * Gets the maximum reward that can be given when selling NFTs
240
+ * @returns The maximum reward in ETH
241
+ */
242
+ getMaxReward(): Promise<number>;
243
+ /**
244
+ * Builds a transaction to set the maximum reward
245
+ * @param maxReward - The new maximum reward in ETH
246
+ * @returns Populated transaction
247
+ */
248
+ buildSetMaxRewardTx(maxReward: number): Promise<ethers.ContractTransaction>;
249
+ /**
250
+ * Builds a transaction to sell NFTs back to the contract
251
+ * @param tokenIds - Array of token IDs to sell
252
+ * @param reward - Reward amount in ETH
253
+ * @param nonce - Unique nonce to prevent replay attacks
254
+ * @param deadline - Timestamp after which signature is invalid
255
+ * @param signature - Signature from authorized signer
256
+ * @returns Populated transaction
257
+ */
258
+ buildSellNFTTx(tokenIds: number[], reward: number, nonce: number, deadline: number, signature: string): Promise<ethers.ContractTransaction>;
259
+ /**
260
+ * Gets the current nonce for a user (used for signature verification)
261
+ * @param user - The user's address
262
+ * @returns The current nonce
263
+ */
264
+ getUserNonce(user: string): Promise<number>;
265
+ /**
266
+ * Checks if an address is an authorized signer
267
+ * @param signer - The address to check
268
+ * @returns True if the address is an authorized signer
269
+ */
270
+ isSigner(signer: string): Promise<boolean>;
271
+ /**
272
+ * Builds a transaction to add a new signer
273
+ * @param signer - Address of the new signer
274
+ * @returns Populated transaction
275
+ */
276
+ buildAddSignerTx(signer: string): Promise<ethers.ContractTransaction>;
277
+ /**
278
+ * Builds a transaction to remove a signer
279
+ * @param signer - Address of the signer to remove
280
+ * @returns Populated transaction
281
+ */
282
+ buildRemoveSignerTx(signer: string): Promise<ethers.ContractTransaction>;
283
+ /**
284
+ * Creates a signature for selling NFTs
285
+ * @param contractAddress Address of the MultiLevelReferralNFT contract
286
+ * @param userAddress Address of the user selling NFTs
287
+ * @param tokenIds Array of token IDs to sell
288
+ * @param reward Reward amount in ETH
289
+ * @param nonce Unique nonce to prevent replay attacks
290
+ * @param deadline Timestamp after which signature is invalid
291
+ * @param signerPrivateKey Private key of the authorized signer
292
+ * @returns Signature and message hash
293
+ */
294
+ createSellSignature(contractAddress: string, userAddress: string, tokenIds: number[], reward: number, nonce: number, deadline: number, signerPrivateKey: string): Promise<{
295
+ signature: string;
296
+ messageHash: string;
297
+ }>;
218
298
  }
@@ -1 +1 @@
1
- "use strict";var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MultiLevelReferralNFTSDK=void 0;const t=require("ethers"),r=e(require("./abis/NFTTicket.json")),a=e(require("./contracts.json")),s=require("./utils");exports.MultiLevelReferralNFTSDK=class{constructor(e,o){this.name="NFTTicket",this.isBootstrapped=!1,this.formatEventArgs=e=>{const{eventName:r,args:a}=e;switch(r){case"NFTMinted":return{...e,args:{...a,owner:a.owner.toLowerCase(),tokenId:Number(a.tokenId)}};case"ReferrerSet":return{...e,args:{...a,referrer:a.referrer.toLowerCase(),referee:a.referee.toLowerCase()}};case"ReferralPaid":return{...e,args:{...a,receiver:a.receiver.toLowerCase(),buyer:a.buyer.toLowerCase(),amount:Number(t.ethers.formatEther(a.amount)),level:Number(a.level),originalAmount:Number(t.ethers.formatEther(a.originalAmount)),tokenId:Number(a.tokenId)}};case"ReferralCodeSet":return{...e,args:{...a,user:a.user.toLowerCase(),referralCode:a.referralCode}};case"MaxReferralLevelsUpdated":return{...e,args:{...a,oldValue:Number(a.oldValue),newValue:Number(a.newValue)}};case"Transfer":return{...e,args:{...a,from:a.from.toLowerCase(),to:a.to.toLowerCase(),tokenId:Number(a.tokenId)}};default:return e}};const n=Array.isArray(e)?e:[e];this.providers=n.map((e=>new t.ethers.JsonRpcProvider(e,void 0,{staticNetwork:!0})));const i=(0,s.getRandomProvider)(this.providers);this.contractAddress=(0,s.resolveContractAddress)(n[0],this.name,a.default,o),this.contract=new t.ethers.Contract(this.contractAddress,r.default.abi,i)}getRandomProvider(){return(0,s.getRandomProvider)(this.providers)}getContractWithRandomProvider(){return new t.ethers.Contract(this.contractAddress,r.default.abi,this.getRandomProvider())}async bootstrap(){if(this.isBootstrapped)return;const e=await Promise.all(this.providers.map(((e,t)=>(0,s.checkRpcHealth)(e,t))));if(this.providers=this.providers.filter(((t,r)=>e[r])),0===this.providers.length)throw new Error("No active RPC providers available");this.isBootstrapped=!0}async signAndSendTransaction(e,t,r={}){return(0,s.signAndSendTransaction)(e,t,(()=>this.getRandomProvider()),r,this.contract)}async getPrice(){const e=await this.contract.price();return Number(t.ethers.formatEther(e))}async getSharePercent(){const e=await this.contract.sharePercent();return Number(e)}async getMaxReferralLevels(){const e=await this.contract.maxReferralLevels();return Number(e)}async getReferrer(e){return await this.contract.referrers(e)}async getReferralCodeOwner(e){return await this.contract.referralCodes(e)}async getUserReferralCode(e){return await this.contract.userReferralCodes(e)}async buildGenerateReferralCodeTx(){return await this.contract.generateReferralCode.populateTransaction()}async buildGenerateReferralCodeForUserTx(e){return await this.contract.generateReferralCodeForUser.populateTransaction(e)}async buildSetPriceTx(e){const r=t.ethers.parseEther(e.toString());return await this.contract.setPrice.populateTransaction(r)}async buildSetMaxReferralLevelsTx(e){if(await this.bootstrap(),e<1||e>10)throw new Error("Maximum referral levels must be between 1 and 10");return await this.contract.setMaxReferralLevels.populateTransaction(e)}async buildSetSharePercentTx(e){if(await this.bootstrap(),e<0||e>100)throw new Error("Share percentage must be between 0 and 100");return await this.contract.setSharePercent.populateTransaction(e)}async buildBuyNFTTx(e){const r=await this.getPrice(),a=await this.contract.buy.populateTransaction(e);return a.value=t.ethers.parseEther(r.toString()),a}async buildBatchBuyNFTTx(e,r){if(await this.bootstrap(),r<=0)throw new Error("Amount must be greater than 0");const a=await this.getPrice()*r,s=await this.contract.batchBuy.populateTransaction(e,r);return s.value=t.ethers.parseEther(a.toString()),s}async buildWithdrawTx(e){const r=t.ethers.parseEther(e.toString());return await this.contract.withdraw.populateTransaction(r)}async buildMintToTx(e){return await this.bootstrap(),this.contract.mintTo.populateTransaction(e)}async buildBatchMintTx(e,t){return await this.bootstrap(),this.contract.batchMint.populateTransaction(e,t)}async getOwner(){return await this.contract.owner()}getContractAddress(){return this.contractAddress}async getAllEvents(e,t,r){return await this.bootstrap(),(0,s.getAllEvents)(this.contract,(()=>this.getRandomProvider()),(()=>this.getContractWithRandomProvider()),e,t,r)}async streamEvents(e,t,r,a=1e3,o=5e3,n=0,i){return await this.bootstrap(),(0,s.streamEvents)({getProvider:()=>this.getRandomProvider(),getAllEvents:(e,t)=>this.getAllEvents(e,t),formatEvent:e=>this.formatEventArgs(e),onEvent:t,saveLatestBlock:r,fromBlock:e,batchSize:a,sleepTime:o,whitelistEvents:void 0,shouldContinue:i,blockGap:n})}};
1
+ "use strict";var e=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MultiLevelReferralNFTSDK=void 0;const t=require("ethers"),r=e(require("./abis/NFTTicket.json")),a=e(require("./contracts.json")),s=require("./utils");exports.MultiLevelReferralNFTSDK=class{constructor(e,n){this.name="NFTTicket",this.isBootstrapped=!1,this.formatEventArgs=e=>{const{eventName:r,args:a}=e;switch(r){case"NFTMinted":return{...e,args:{...a,owner:a.owner.toLowerCase(),tokenId:Number(a.tokenId)}};case"ReferrerSet":return{...e,args:{...a,referrer:a.referrer.toLowerCase(),referee:a.referee.toLowerCase()}};case"ReferralPaid":return{...e,args:{...a,receiver:a.receiver.toLowerCase(),buyer:a.buyer.toLowerCase(),amount:Number(t.ethers.formatEther(a.amount)),level:Number(a.level),originalAmount:Number(t.ethers.formatEther(a.originalAmount)),tokenId:Number(a.tokenId)}};case"ReferralCodeSet":return{...e,args:{...a,user:a.user.toLowerCase(),referralCode:a.referralCode}};case"MaxReferralLevelsUpdated":case"SharePercentUpdated":return{...e,args:{...a,oldValue:Number(a.oldValue),newValue:Number(a.newValue)}};case"MaxRewardUpdated":return{...e,args:{...a,oldValue:Number(t.ethers.formatEther(a.oldValue)),newValue:Number(t.ethers.formatEther(a.newValue))}};case"NFTSold":return{...e,args:{...a,seller:a.seller.toLowerCase(),tokenIds:a.tokenIds.map((e=>Number(e))),reward:Number(t.ethers.formatEther(a.reward)),timestamp:Number(a.timestamp)}};case"SignerAdded":case"SignerRemoved":return{...e,args:{...a,signer:a.signer.toLowerCase()}};case"Transfer":return{...e,args:{...a,from:a.from.toLowerCase(),to:a.to.toLowerCase(),tokenId:Number(a.tokenId)}};default:return e}};const o=Array.isArray(e)?e:[e];this.providers=o.map((e=>new t.ethers.JsonRpcProvider(e,void 0,{staticNetwork:!0})));const i=(0,s.getRandomProvider)(this.providers);this.contractAddress=(0,s.resolveContractAddress)(o[0],this.name,a.default,n),this.contract=new t.ethers.Contract(this.contractAddress,r.default.abi,i)}getRandomProvider(){return(0,s.getRandomProvider)(this.providers)}getContractWithRandomProvider(){return new t.ethers.Contract(this.contractAddress,r.default.abi,this.getRandomProvider())}async bootstrap(){if(this.isBootstrapped)return;const e=await Promise.all(this.providers.map(((e,t)=>(0,s.checkRpcHealth)(e,t))));if(this.providers=this.providers.filter(((t,r)=>e[r])),0===this.providers.length)throw new Error("No active RPC providers available");this.isBootstrapped=!0}async signAndSendTransaction(e,t,r={}){return(0,s.signAndSendTransaction)(e,t,(()=>this.getRandomProvider()),r,this.contract)}async getPrice(){const e=await this.contract.price();return Number(t.ethers.formatEther(e))}async getSharePercent(){const e=await this.contract.sharePercent();return Number(e)}async getMaxReferralLevels(){const e=await this.contract.maxReferralLevels();return Number(e)}async getReferrer(e){return await this.contract.referrers(e)}async getReferralCodeOwner(e){return await this.contract.referralCodes(e)}async getUserReferralCode(e){return await this.contract.userReferralCodes(e)}async buildGenerateReferralCodeTx(){return await this.contract.generateReferralCode.populateTransaction()}async buildGenerateReferralCodeForUserTx(e){return await this.contract.generateReferralCodeForUser.populateTransaction(e)}async buildSetPriceTx(e){const r=t.ethers.parseEther(e.toString());return await this.contract.setPrice.populateTransaction(r)}async buildSetMaxReferralLevelsTx(e){if(await this.bootstrap(),e<1||e>10)throw new Error("Maximum referral levels must be between 1 and 10");return await this.contract.setMaxReferralLevels.populateTransaction(e)}async buildSetSharePercentTx(e){if(await this.bootstrap(),e<0||e>100)throw new Error("Share percentage must be between 0 and 100");return await this.contract.setSharePercent.populateTransaction(e)}async buildBuyNFTTx(e){const r=await this.getPrice(),a=await this.contract.buy.populateTransaction(e);return a.value=t.ethers.parseEther(r.toString()),a}async buildBatchBuyNFTTx(e,r){if(await this.bootstrap(),r<=0)throw new Error("Amount must be greater than 0");const a=await this.getPrice()*r,s=await this.contract.batchBuy.populateTransaction(e,r);return s.value=t.ethers.parseEther(a.toString()),s}async buildWithdrawTx(e){const r=t.ethers.parseEther(e.toString());return await this.contract.withdraw.populateTransaction(r)}async buildMintToTx(e){return await this.bootstrap(),this.contract.mintTo.populateTransaction(e)}async buildBatchMintTx(e,t){return await this.bootstrap(),this.contract.batchMint.populateTransaction(e,t)}async getOwner(){return await this.contract.owner()}getContractAddress(){return this.contractAddress}async getAllEvents(e,t,r){return await this.bootstrap(),(0,s.getAllEvents)(this.contract,(()=>this.getRandomProvider()),(()=>this.getContractWithRandomProvider()),e,t,r)}async streamEvents(e,t,r,a=1e3,n=5e3,o=0,i){return await this.bootstrap(),(0,s.streamEvents)({getProvider:()=>this.getRandomProvider(),getAllEvents:(e,t)=>this.getAllEvents(e,t),formatEvent:e=>this.formatEventArgs(e),onEvent:t,saveLatestBlock:r,fromBlock:e,batchSize:a,sleepTime:n,whitelistEvents:void 0,shouldContinue:i,blockGap:o})}async getMaxReward(){const e=await this.contract.maxReward();return Number(t.ethers.formatEther(e))}async buildSetMaxRewardTx(e){await this.bootstrap();const r=t.ethers.parseEther(e.toString());return await this.contract.setMaxReward.populateTransaction(r)}async buildSellNFTTx(e,r,a,s,n){await this.bootstrap();const o=t.ethers.parseEther(r.toString());return await this.contract.sell.populateTransaction(e,o,a,s,n)}async getUserNonce(e){const t=await this.contract.userNonces(e);return Number(t)}async isSigner(e){return await this.contract.signers(e)}async buildAddSignerTx(e){return await this.bootstrap(),await this.contract.addSigner.populateTransaction(e)}async buildRemoveSignerTx(e){return await this.bootstrap(),await this.contract.removeSigner.populateTransaction(e)}async createSellSignature(e,r,a,s,n,o,i){const c=t.ethers.parseEther(s.toString()),u=t.ethers.solidityPacked(Array(a.length).fill("uint256"),a),d=t.ethers.keccak256(u),h=t.ethers.keccak256(t.ethers.solidityPacked(["address","address","bytes32","uint256","uint256","uint256"],[e,r,d,c,n,o])),l=new t.ethers.Wallet(i),w=t.ethers.getBytes(h);return{signature:await l.signMessage(w),messageHash:h.toString()}}};
@@ -209,6 +209,71 @@ export declare class TradingVaultSDK {
209
209
  getTotalAmountRaw(): Promise<bigint>;
210
210
  getTotalBorrowed(): Promise<number>;
211
211
  getTotalBorrowedRaw(): Promise<bigint>;
212
+ /**
213
+ * Gets the total debt of all users
214
+ *
215
+ * @returns The total debt as a number
216
+ *
217
+ * @example
218
+ * ```typescript
219
+ * const totalDebt = await sdk.getTotalUserDebt();
220
+ * ```
221
+ */
222
+ getTotalUserDebt(): Promise<number>;
223
+ /**
224
+ * Gets the total debt of all users in raw format
225
+ *
226
+ * @returns The total debt as a bigint
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * const totalDebtRaw = await sdk.getTotalUserDebtRaw();
231
+ * ```
232
+ */
233
+ getTotalUserDebtRaw(): Promise<bigint>;
234
+ /**
235
+ * Gets the debt of a specific user
236
+ *
237
+ * @param userAddress - The address of the user
238
+ * @returns The user's debt as a number
239
+ *
240
+ * @example
241
+ * ```typescript
242
+ * const userDebt = await sdk.getUserDebt("0x...");
243
+ * ```
244
+ */
245
+ getUserDebt(userAddress: string): Promise<number>;
246
+ /**
247
+ * Gets the debt of a specific user in raw format
248
+ *
249
+ * @param userAddress - The address of the user
250
+ * @returns The user's debt as a bigint
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * const userDebtRaw = await sdk.getUserDebtRaw("0x...");
255
+ * ```
256
+ */
257
+ getUserDebtRaw(userAddress: string): Promise<bigint>;
258
+ /**
259
+ * Builds a transaction to repay user debt
260
+ *
261
+ * @param amount - Amount of reward tokens to use for debt repayment
262
+ * @returns Populated transaction
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * const tx = await sdk.buildRepayUserDebtTx(100);
267
+ * ```
268
+ */
269
+ buildRepayUserDebtTx(amount: number): Promise<ethers.ContractTransaction>;
270
+ /**
271
+ * Builds a raw transaction to repay user debt
272
+ *
273
+ * @param amount - Amount of reward tokens as bigint
274
+ * @returns Populated transaction
275
+ */
276
+ buildRepayUserDebtTxRaw(amount: bigint): Promise<ethers.ContractTransaction>;
212
277
  isReduceEnabled(): Promise<boolean>;
213
278
  getPosition(tokenId: bigint): Promise<{
214
279
  remainingAmount: number;
@@ -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"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)}};
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"),a=t(require("./abis/TradingVault.json")),r=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,a=this._rewardTokenDecimals,{eventName:r,args:n}=t;switch(r){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,a),userReward:Number(n.userReward)/Math.pow(10,a),treasuryReward:Number(n.treasuryReward)/Math.pow(10,a),rewardedAmount:Number(n.rewardedAmount)/Math.pow(10,a),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,a),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,a),newAmount:Number(n.newAmount)/Math.pow(10,a)}};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,r.default,i),this.contract=new e.ethers.Contract(this.contractAddress,a.default.abi,s)}getRandomProvider(){return(0,n.getRandomProvider)(this.providers)}getContractWithRandomProvider(){return new e.ethers.Contract(this.contractAddress,a.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,a)=>t[a])),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 a=0;a<t;a++)e.push(this.getRewardConfig(a));const a=await Promise.all(e);this.configs=a.map((t=>({weight:Number(t.weight)/this.BASE_WEIGHT,duration:Number(t.duration)})))})()]),this.isBootstrapped=!0}async signAndSendTransaction(t,e,a={}){return(0,n.signAndSendTransaction)(t,e,(()=>this.getRandomProvider()),a,this.contract)}async buildCreatePositionTx(t,e,a=0){const r=await this.getCurrencyDecimals(),n=BigInt(Math.floor(t*Math.pow(10,r)));return this.buildCreatePositionTxRaw(n,e,BigInt(a))}async buildReducePositionTx(t,e){const a=await this.getCurrencyDecimals(),r=BigInt(Math.floor(e*Math.pow(10,a)));return this.buildReducePositionTxRaw(t,r)}async buildReducePositionsTx(t,e){const a=await this.getCurrencyDecimals(),r=e.map((t=>BigInt(Math.floor(t*Math.pow(10,a)))));return this.buildReducePositionsTxRaw(t,r)}async buildBorrowCurrencyTx(t){const e=await this.getCurrencyDecimals(),a=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildBorrowCurrencyTxRaw(a)}async buildRepayCurrencyTx(t){const e=await this.getCurrencyDecimals(),a=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildRepayCurrencyTxRaw(a)}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,a){const r=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),n=await r.decimals(),i=BigInt(Math.floor(a*Math.pow(10,n)));return this.buildClaimERC20TxRaw(t,i)}async buildCreatePositionTxRaw(t,e,a=0n){return await this.contract.createPosition.populateTransaction(t,e,a)}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,a,r){const n=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),i=await n.decimals(),o=BigInt(Math.floor(r*Math.pow(10,Number(i))));return this.buildApproveERC20TxRaw(t,a,o)}async buildApproveERC20TxRaw(t,e,a){return await(0,n.buildApproveERC20Tx)(t,e,a,this.getRandomProvider())}async getAllowanceRaw(t,e,a){return await(0,n.getTokenAllowance)(t,e,a,this.getRandomProvider())}async getAllowance(t,e,a){const[r,i]=await Promise.all([this.getAllowanceRaw(t,e,a),(0,n.getTokenDecimals)(t,this.getRandomProvider())]);return Number(r)/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 getTotalUserDebt(){const t=await this.getTotalUserDebtRaw(),e=await this.getRewardTokenDecimals();return Number(t)/Math.pow(10,e)}async getTotalUserDebtRaw(){return await this.contract.totalUserDebt()}async getUserDebt(t){const e=await this.getUserDebtRaw(t),a=await this.getRewardTokenDecimals();return Number(e)/Math.pow(10,a)}async getUserDebtRaw(t){return await this.contract.userDebt(t)}async buildRepayUserDebtTx(t){const e=await this.getRewardTokenDecimals(),a=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildRepayUserDebtTxRaw(a)}async buildRepayUserDebtTxRaw(t){return await this.contract.repayUserDebt.populateTransaction(t)}async isReduceEnabled(){return await this.contract.isReduceEnabled()}async getPosition(t){const e=await this.getPositionRaw(t),a=await this.getCurrencyDecimals(),r=await this.getRewardTokenDecimals(),n=this.priceDecimals;return{remainingAmount:Number(e.remainingAmount)/Math.pow(10,a),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,r),lossAmount:Number(e.lossAmount)/Math.pow(10,a),initAmount:Number(e.initAmount)/Math.pow(10,a),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(),a=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider());this._currencyDecimals=Number(await a.decimals())}return this._currencyDecimals}async getRewardTokenDecimals(){if(null===this._rewardTokenDecimals){const t=await this.getRewardToken(),a=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider());this._rewardTokenDecimals=Number(await a.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,a){return await this.bootstrap(),(0,n.getAllEvents)(this.contract,(()=>this.getRandomProvider()),(()=>this.getContractWithRandomProvider()),t,e,a)}async streamEvents(t,e,a,r=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:a,fromBlock:t,batchSize:r,sleepTime:i,blockGap:o})}estimateUnrealizedPnl({price:t,entryPrice:e,initAmount:a,remainingAmount:r}){const n=r*(t-e)/this.BASE_PRICE;return{pnl:n,pnlPercentage:n/a*100}}estReducePosition({amount:t,price:e,entryPrice:a,openedAt:r,configs:n=[]}){const i=this.BASE_PRICE;this.BASE_WEIGHT;let o=t,s=0,c=0,u=0,d=0;if(e<a){return o=t-t*(a-e)/100,{amount:o,totalReward:0,userReward:0,treasuryReward:0,weight:0}}if(e>=a){s=t*(e-a)/i;const o=Math.floor(Date.now()/1e3)-r;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:a=[]}){return t.map((t=>this.estReducePosition({amount:t.amount,price:e,entryPrice:t.entryPrice,openedAt:t.openedAt,configs:a}))).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,a)=>{const{pnl:r}=this.estimateUnrealizedPnl({price:t,...a});return{totalInitAmount:e.totalInitAmount+a.initAmount,totalRemainingAmount:e.totalRemainingAmount+a.remainingAmount,totalRewardedAmount:e.totalRewardedAmount+a.rewardedAmount,totalLossAmount:e.totalLossAmount+a.lossAmount,totalPnl:e.totalPnl+r}}),{totalInitAmount:0,totalRemainingAmount:0,totalRewardedAmount:0,totalLossAmount:0,totalPnl:0})}async buildAddReward(t){const e=await this.getRewardTokenDecimals(),a=BigInt(Math.floor(t*Math.pow(10,e)));return this.buildAddRewardTxRaw(a)}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 a=t.map((t=>BigInt(t))),r=e.map((t=>BigInt(t)));return this.buildBatchSetPositionExpirationTxRaw(a,r)}async buildBatchSetPositionExpirationTxRaw(t,e){return await this.contract.batchSetPositionExpiration.populateTransaction(t,e)}async buildUpdateEntryPriceTx(t,e){const a=BigInt(Math.round(e*Math.pow(10,this.priceDecimals)));return this.buildUpdateEntryPriceTxRaw(BigInt(t),a)}async buildUpdateEntryPriceTxRaw(t,e){return await this.contract.updateEntryPrice.populateTransaction(t,e)}async buildBatchUpdateEntryPriceTx(t,e){const a=t.map((t=>BigInt(t))),r=e.map((t=>BigInt(Math.round(t*Math.pow(10,this.priceDecimals)))));return this.buildBatchUpdateEntryPriceTxRaw(a,r)}async buildBatchUpdateEntryPriceTxRaw(t,e){return await this.contract.batchUpdateEntryPrice.populateTransaction(t,e)}async buildCloseExpiredPositionTx(t,e){const a=BigInt(Math.round(e*Math.pow(10,this.priceDecimals)));return this.buildCloseExpiredPositionTxRaw(BigInt(t),a)}async buildCloseExpiredPositionTxRaw(t,e){return await this.contract.closeExpiredPosition.populateTransaction(t,e)}};