aiia-vault-sdk 1.1.29 → 1.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/FairLaunch.d.ts +95 -0
- package/dist/FairLaunch.js +1 -0
- package/dist/TradingVault.d.ts +2 -2
- package/dist/TradingVault.js +1 -1
- package/dist/abis/FairLaunch.json +1211 -0
- package/dist/contracts/FairLaunch.d.ts +699 -0
- package/dist/contracts/FairLaunch.js +1 -0
- package/dist/contracts.json +7 -1
- package/dist/types.d.ts +71 -0
- package/package.json +1 -1
@@ -0,0 +1,95 @@
|
|
1
|
+
import { ethers } from "ethers";
|
2
|
+
import { type SendTransactionMutateAsync } from "@wagmi/core/query";
|
3
|
+
import { Config } from "@wagmi/core/dist/types/createConfig";
|
4
|
+
import { ParsedFairLaunchEventRaw, ParsedFairLaunchEvent } from "./types";
|
5
|
+
export interface UserContribution {
|
6
|
+
amount: number;
|
7
|
+
tokenAllocation: number;
|
8
|
+
hasClaimedInitial: boolean;
|
9
|
+
vestedClaimed: number;
|
10
|
+
tradingVaultId: number;
|
11
|
+
}
|
12
|
+
export interface SaleInfo {
|
13
|
+
startTime: number;
|
14
|
+
endTime: number;
|
15
|
+
totalTokensForSale: number;
|
16
|
+
totalRaised: number;
|
17
|
+
tokenPrice: number;
|
18
|
+
saleEnded: boolean;
|
19
|
+
claimingEnabled: boolean;
|
20
|
+
liquidityAdded: boolean;
|
21
|
+
}
|
22
|
+
export declare class FairLaunchSDK {
|
23
|
+
name: string;
|
24
|
+
private contract;
|
25
|
+
private providers;
|
26
|
+
private contractAddress;
|
27
|
+
private isBootstrapped;
|
28
|
+
private _projectToken;
|
29
|
+
private _fundingToken;
|
30
|
+
private _projectTokenDecimals;
|
31
|
+
private _fundingTokenDecimals;
|
32
|
+
constructor(rpcUrls: string | string[], contractAddress?: string);
|
33
|
+
private getRandomProvider;
|
34
|
+
private getContractWithRandomProvider;
|
35
|
+
bootstrap(): Promise<void>;
|
36
|
+
signAndSendTransaction(tx: ethers.ContractTransaction, wallet: ethers.Wallet | SendTransactionMutateAsync<Config, any>, callbacks?: {
|
37
|
+
onSubmit?: (tx: string) => void | Promise<void>;
|
38
|
+
onFinally?: (status: {
|
39
|
+
status: boolean | null;
|
40
|
+
confirmations: number;
|
41
|
+
txHash: string;
|
42
|
+
isCompleted: boolean;
|
43
|
+
attempts: number;
|
44
|
+
}) => void | Promise<void>;
|
45
|
+
onError?: (error: Error) => void | Promise<void>;
|
46
|
+
}): Promise<{
|
47
|
+
transaction: {
|
48
|
+
hash: string;
|
49
|
+
};
|
50
|
+
status: {
|
51
|
+
status: boolean | null;
|
52
|
+
confirmations: number;
|
53
|
+
isCompleted: boolean;
|
54
|
+
attempts: number;
|
55
|
+
};
|
56
|
+
}>;
|
57
|
+
buildContributeTx(amount: number): Promise<ethers.ContractTransaction>;
|
58
|
+
buildEndSaleTx(): Promise<ethers.ContractTransaction>;
|
59
|
+
buildAddLiquidityTx(): Promise<ethers.ContractTransaction>;
|
60
|
+
buildEnableClaimingTx(): Promise<ethers.ContractTransaction>;
|
61
|
+
buildClaimInitialTx(): Promise<ethers.ContractTransaction>;
|
62
|
+
buildClaimVestedTx(): Promise<ethers.ContractTransaction>;
|
63
|
+
buildUpdateLiquidityTokensTx(liquidityTokens: number): Promise<ethers.ContractTransaction>;
|
64
|
+
buildUpdateLiquidityPercentTx(liquidityPercent: number): Promise<ethers.ContractTransaction>;
|
65
|
+
buildUpdateInitialClaimPercentTx(initialClaimPercent: number): Promise<ethers.ContractTransaction>;
|
66
|
+
buildUpdateVestingDurationTx(vestingDuration: number): Promise<ethers.ContractTransaction>;
|
67
|
+
buildUpdateEarlyParticipationWindowTx(earlyParticipationWindow: number): Promise<ethers.ContractTransaction>;
|
68
|
+
buildWithdrawLPTokensTx(lpToken: string, recipient: string): Promise<ethers.ContractTransaction>;
|
69
|
+
buildWithdrawERC20Tx(token: string, amount: number): Promise<ethers.ContractTransaction>;
|
70
|
+
buildApproveERC20Tx(tokenAddress: string, spender: string, amount: number): Promise<ethers.ContractTransaction>;
|
71
|
+
getSaleInfo(): Promise<SaleInfo>;
|
72
|
+
getUserContribution(user: string): Promise<UserContribution>;
|
73
|
+
getContributorsCount(): Promise<number>;
|
74
|
+
getContributorAt(index: number): Promise<string>;
|
75
|
+
getAllContributors(): Promise<string[]>;
|
76
|
+
getProjectToken(): Promise<string>;
|
77
|
+
getFundingToken(): Promise<string>;
|
78
|
+
getTradingVault(): Promise<string>;
|
79
|
+
getDexRouter(): Promise<string>;
|
80
|
+
getLiquidityTokens(): Promise<number>;
|
81
|
+
getLiquidityPercent(): Promise<number>;
|
82
|
+
getInitialClaimPercent(): Promise<number>;
|
83
|
+
getVestingDuration(): Promise<number>;
|
84
|
+
getVestingStartTime(): Promise<number>;
|
85
|
+
getEarlyParticipationWindow(): Promise<number>;
|
86
|
+
hasOperatorRole(address: string): Promise<boolean>;
|
87
|
+
hasAdminRole(address: string): Promise<boolean>;
|
88
|
+
buildGrantOperatorRoleTx(operator: string): Promise<ethers.ContractTransaction>;
|
89
|
+
buildGrantAdminRoleTx(admin: string): Promise<ethers.ContractTransaction>;
|
90
|
+
getAllowance(tokenAddress: string, owner: string, spender: string): Promise<number>;
|
91
|
+
getContractAddress(): string;
|
92
|
+
getAllEvents(fromBlock: number, toBlock: number, whitelistEvents?: string[]): Promise<any[]>;
|
93
|
+
streamEvents(fromBlock: number, onEvent: (event: any) => Promise<void>, saveLatestBlock: (blockNumber: number) => Promise<void>, batchSize?: number, sleepTime?: number): Promise<void>;
|
94
|
+
formatEventArgs: (event: ParsedFairLaunchEventRaw) => Promise<ParsedFairLaunchEvent>;
|
95
|
+
}
|
@@ -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.FairLaunchSDK=void 0;const e=require("ethers"),i=t(require("./abis/FairLaunch.json")),a=t(require("./contracts.json")),n=require("./utils");exports.FairLaunchSDK=class{constructor(t,r){this.name="FairLaunch",this.isBootstrapped=!1,this._projectToken=null,this._fundingToken=null,this._projectTokenDecimals=null,this._fundingTokenDecimals=null,this.formatEventArgs=async t=>{await this.bootstrap();const{eventName:e,args:i}=t;switch(e){case"Contributed":return{...t,args:{...i,user:i.user.toLowerCase(),amount:Number(i.amount)/10**this._fundingTokenDecimals}};case"SaleEnded":return{...t,args:{...i,totalRaised:Number(i.totalRaised)/10**this._fundingTokenDecimals,tokenPrice:Number(i.tokenPrice)/10**this._fundingTokenDecimals}};case"InitialClaimed":case"VestedClaimed":return{...t,args:{...i,user:i.user.toLowerCase(),amount:Number(i.amount)/10**this._projectTokenDecimals}};case"TradingVaultPositionCreated":return{...t,args:{...i,user:i.user.toLowerCase(),positionId:Number(i.positionId),amount:Number(i.amount)/10**this._fundingTokenDecimals}};case"LiquidityAdded":return{...t,args:{...i,tokenAmount:Number(i.tokenAmount)/10**this._projectTokenDecimals,fundingTokenAmount:Number(i.fundingTokenAmount)/10**this._fundingTokenDecimals}};default:return t}};const o=Array.isArray(t)?t:[t];this.providers=o.map((t=>new e.ethers.JsonRpcProvider(t)));const s=(0,n.getRandomProvider)(this.providers);this.contractAddress=(0,n.resolveContractAddress)(o[0],this.name,a.default,r),this.contract=new e.ethers.Contract(this.contractAddress,i.default.abi,s)}getRandomProvider(){return(0,n.getRandomProvider)(this.providers)}getContractWithRandomProvider(){return new e.ethers.Contract(this.contractAddress,i.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,i)=>t[i])),0===this.providers.length)throw new Error("No active RPC providers available");this._projectToken=await this.contract.projectToken(),this._fundingToken=await this.contract.fundingToken();const[e,i]=await Promise.all([(0,n.getTokenDecimals)(this._projectToken,this.getRandomProvider()),(0,n.getTokenDecimals)(this._fundingToken,this.getRandomProvider())]);this._projectTokenDecimals=e,this._fundingTokenDecimals=i,this.isBootstrapped=!0}async signAndSendTransaction(t,e,i={}){return(0,n.signAndSendTransaction)(t,e,(()=>this.getRandomProvider()),i,this.contract)}async buildContributeTx(t){await this.bootstrap();const i=e.ethers.parseUnits(t.toString(),this._fundingTokenDecimals);return await this.contract.contribute.populateTransaction(i)}async buildEndSaleTx(){return await this.contract.endSale.populateTransaction()}async buildAddLiquidityTx(){return await this.contract.addLiquidity.populateTransaction()}async buildEnableClaimingTx(){return await this.contract.enableClaiming.populateTransaction()}async buildClaimInitialTx(){return await this.contract.claimInitial.populateTransaction()}async buildClaimVestedTx(){return await this.contract.claimVested.populateTransaction()}async buildUpdateLiquidityTokensTx(t){await this.bootstrap();const i=e.ethers.parseUnits(t.toString(),this._projectTokenDecimals);return await this.contract.updateLiquidityTokens.populateTransaction(i)}async buildUpdateLiquidityPercentTx(t){return await this.contract.updateLiquidityPercent.populateTransaction(t)}async buildUpdateInitialClaimPercentTx(t){return await this.contract.updateInitialClaimPercent.populateTransaction(t)}async buildUpdateVestingDurationTx(t){return await this.contract.updateVestingDuration.populateTransaction(t)}async buildUpdateEarlyParticipationWindowTx(t){return await this.contract.updateEarlyParticipationWindow.populateTransaction(t)}async buildWithdrawLPTokensTx(t,e){return await this.contract.withdrawLPTokens.populateTransaction(t,e)}async buildWithdrawERC20Tx(t,i){const a=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),n=await a.decimals(),r=e.ethers.parseUnits(i.toString(),n);return await this.contract.withdrawERC20.populateTransaction(t,r)}async buildApproveERC20Tx(t,i,a){const r=new e.ethers.Contract(t,["function decimals() view returns (uint8)"],this.getRandomProvider()),o=await r.decimals(),s=e.ethers.parseUnits(a.toString(),o);return(0,n.buildApproveERC20Tx)(t,i,s,this.getRandomProvider())}async getSaleInfo(){await this.bootstrap();const[t,e,i,a,n,r,o,s]=await Promise.all([this.contract.startTime(),this.contract.endTime(),this.contract.totalTokensForSale(),this.contract.totalRaised(),this.contract.tokenPrice(),this.contract.saleEnded(),this.contract.claimingEnabled(),this.contract.liquidityAdded()]);return{startTime:Number(t),endTime:Number(e),totalTokensForSale:Number(i)/10**this._projectTokenDecimals,totalRaised:Number(a)/10**this._fundingTokenDecimals,tokenPrice:Number(n)/10**this._fundingTokenDecimals,saleEnded:r,claimingEnabled:o,liquidityAdded:s}}async getUserContribution(t){await this.bootstrap();const e=await this.contract.userContributions(t);return{amount:Number(e.amount)/10**this._fundingTokenDecimals,tokenAllocation:Number(e.tokenAllocation)/10**this._projectTokenDecimals,hasClaimedInitial:e.hasClaimedInitial,vestedClaimed:Number(e.vestedClaimed)/10**this._projectTokenDecimals,tradingVaultId:Number(e.tradingVaultId)}}async getContributorsCount(){return Number(await this.contract.getContributorsCount())}async getContributorAt(t){return await this.contract.getContributorAt(t)}async getAllContributors(){const t=await this.getContributorsCount(),e=[];for(let i=0;i<t;i++)e.push(await this.getContributorAt(i));return e}async getProjectToken(){return this._projectToken||(this._projectToken=await this.contract.projectToken()),this._projectToken}async getFundingToken(){return this._fundingToken||(this._fundingToken=await this.contract.fundingToken()),this._fundingToken}async getTradingVault(){return await this.contract.tradingVault()}async getDexRouter(){return await this.contract.dexRouter()}async getLiquidityTokens(){await this.bootstrap();const t=await this.contract.liquidityTokens();return Number(t)/10**this._projectTokenDecimals}async getLiquidityPercent(){return Number(await this.contract.liquidityPercent())}async getInitialClaimPercent(){return Number(await this.contract.initialClaimPercent())}async getVestingDuration(){return Number(await this.contract.vestingDuration())}async getVestingStartTime(){return Number(await this.contract.vestingStartTime())}async getEarlyParticipationWindow(){return Number(await this.contract.earlyParticipationWindow())}async hasOperatorRole(t){const e=await this.contract.OPERATOR_ROLE();return await this.contract.hasRole(e,t)}async hasAdminRole(t){const e=await this.contract.DEFAULT_ADMIN_ROLE();return await this.contract.hasRole(e,t)}async buildGrantOperatorRoleTx(t){const e=await this.contract.OPERATOR_ROLE();return await this.contract.grantRole.populateTransaction(e,t)}async buildGrantAdminRoleTx(t){const e=await this.contract.DEFAULT_ADMIN_ROLE();return await this.contract.grantRole.populateTransaction(e,t)}async getAllowance(t,e,i){const[a,r]=await Promise.all([(0,n.getTokenAllowance)(t,e,i,this.getRandomProvider()),(0,n.getTokenDecimals)(t,this.getRandomProvider())]);return Number(a)/Math.pow(10,r)}getContractAddress(){return this.contractAddress}async getAllEvents(t,e,i){return await this.bootstrap(),(0,n.getAllEvents)(this.contract,(()=>this.getRandomProvider()),(()=>this.getContractWithRandomProvider()),t,e,i)}async streamEvents(t,e,i,a=1e3,r=5e3){const o=["Contributed","SaleEnded","InitialClaimed","VestedClaimed","ClaimingEnabled","LiquidityAdded","TradingVaultPositionCreated"];return await this.bootstrap(),(0,n.streamEvents)({getProvider:()=>this.getRandomProvider(),getAllEvents:(t,e)=>this.getAllEvents(t,e,o),formatEvent:t=>this.formatEventArgs(t),onEvent:e,saveLatestBlock:i,fromBlock:t,batchSize:a,sleepTime:r})}};
|
package/dist/TradingVault.d.ts
CHANGED
@@ -66,7 +66,7 @@ export declare class TradingVaultSDK {
|
|
66
66
|
buildBatchEmitPriceUpdatedTx(priceDataArray: Array<{
|
67
67
|
price: number;
|
68
68
|
timestamp: number;
|
69
|
-
}>): Promise<
|
69
|
+
}>): Promise<ethers.ContractTransaction>;
|
70
70
|
/**
|
71
71
|
* Builds a raw transaction to batch emit price updated events
|
72
72
|
*
|
@@ -76,7 +76,7 @@ export declare class TradingVaultSDK {
|
|
76
76
|
buildBatchEmitPriceUpdatedTxRaw(priceDataArray: Array<{
|
77
77
|
price: bigint;
|
78
78
|
timestamp: bigint;
|
79
|
-
}>): Promise<
|
79
|
+
}>): Promise<ethers.ContractTransaction>;
|
80
80
|
buildClaimERC20Tx(token: string, amount: number): Promise<ethers.ContractTransaction>;
|
81
81
|
buildCreatePositionTxRaw(amount: bigint, recipient: string): Promise<ethers.ContractTransaction>;
|
82
82
|
buildReducePositionTxRaw(tokenId: bigint, amount: bigint): Promise<ethers.ContractTransaction>;
|
package/dist/TradingVault.js
CHANGED
@@ -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)}};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)}};default:return t}};const o=Array.isArray(t)?t:[t];this.providers=o.map((t=>new e.ethers.JsonRpcProvider(t)));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){const r=await this.getCurrencyDecimals(),a=BigInt(Math.floor(t*Math.pow(10,r)));return this.buildCreatePositionTxRaw(a,e)}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.functions.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){return await this.contract.createPosition.populateTransaction(t,e)}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)}}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}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){const o=["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,o),formatEvent:t=>this.formatEventArgs(t),onEvent:e,saveLatestBlock:r,fromBlock:t,batchSize:a,sleepTime:i})}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)}};
|
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)}};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)}};default:return t}};const o=Array.isArray(t)?t:[t];this.providers=o.map((t=>new e.ethers.JsonRpcProvider(t)));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){const r=await this.getCurrencyDecimals(),a=BigInt(Math.floor(t*Math.pow(10,r)));return this.buildCreatePositionTxRaw(a,e)}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){return await this.contract.createPosition.populateTransaction(t,e)}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)}}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}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){const o=["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,o),formatEvent:t=>this.formatEventArgs(t),onEvent:e,saveLatestBlock:r,fromBlock:t,batchSize:a,sleepTime:i})}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)}};
|