|
| 1 | +import { _operatorContractUtils, SignerWithProvider, StreamrClient } from '@streamr/sdk' |
| 2 | +import { collect, Logger, scheduleAtApproximateInterval, TheGraphClient, WeiAmount } from '@streamr/utils' |
| 3 | +import { Schema } from 'ajv' |
| 4 | +import { formatEther, parseEther } from 'ethers' |
| 5 | +import { Plugin } from '../../Plugin' |
| 6 | +import PLUGIN_CONFIG_SCHEMA from './config.schema.json' |
| 7 | +import { adjustStakes } from './payoutProportionalStrategy' |
| 8 | +import { Action, SponsorshipConfig, SponsorshipID } from './types' |
| 9 | + |
| 10 | +export interface AutostakerPluginConfig { |
| 11 | + operatorContractAddress: string |
| 12 | + maxSponsorshipCount: number |
| 13 | + minTransactionDataTokenAmount: number |
| 14 | + maxAcceptableMinOperatorCount: number |
| 15 | + runIntervalInMs: number |
| 16 | +} |
| 17 | + |
| 18 | +interface SponsorshipQueryResultItem { |
| 19 | + id: SponsorshipID |
| 20 | + totalPayoutWeiPerSec: WeiAmount |
| 21 | + operatorCount: number |
| 22 | + maxOperators: number | null |
| 23 | +} |
| 24 | + |
| 25 | +interface StakeQueryResultItem { |
| 26 | + id: string |
| 27 | + sponsorship: { |
| 28 | + id: SponsorshipID |
| 29 | + } |
| 30 | + amountWei: WeiAmount |
| 31 | +} |
| 32 | + |
| 33 | +const logger = new Logger(module) |
| 34 | + |
| 35 | +// 1e12 wei, i.e. one millionth of one DATA token (we can tweak this later if needed) |
| 36 | +const MIN_SPONSORSHIP_TOTAL_PAYOUT_PER_SECOND = 1000000000000n |
| 37 | + |
| 38 | +const fetchMinStakePerSponsorship = async (theGraphClient: TheGraphClient): Promise<bigint> => { |
| 39 | + const queryResult = await theGraphClient.queryEntity<{ network: { minimumStakeWei: string } }>({ |
| 40 | + query: ` |
| 41 | + { |
| 42 | + network (id: "network-entity-id") { |
| 43 | + minimumStakeWei |
| 44 | + } |
| 45 | + } |
| 46 | + ` |
| 47 | + }) |
| 48 | + return BigInt(queryResult.network.minimumStakeWei) |
| 49 | +} |
| 50 | + |
| 51 | +const getStakeOrUnstakeFunction = (action: Action): ( |
| 52 | + operatorOwnerWallet: SignerWithProvider, |
| 53 | + operatorContractAddress: string, |
| 54 | + sponsorshipContractAddress: string, |
| 55 | + amount: WeiAmount |
| 56 | +) => Promise<void> => { |
| 57 | + switch (action.type) { |
| 58 | + case 'stake': |
| 59 | + return _operatorContractUtils.stake |
| 60 | + case 'unstake': |
| 61 | + return _operatorContractUtils.unstake |
| 62 | + default: |
| 63 | + throw new Error('assertion failed') |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +export class AutostakerPlugin extends Plugin<AutostakerPluginConfig> { |
| 68 | + |
| 69 | + private abortController: AbortController = new AbortController() |
| 70 | + |
| 71 | + async start(streamrClient: StreamrClient): Promise<void> { |
| 72 | + logger.info('Start autostaker plugin') |
| 73 | + const minStakePerSponsorship = await fetchMinStakePerSponsorship(streamrClient.getTheGraphClient()) |
| 74 | + scheduleAtApproximateInterval(async () => { |
| 75 | + try { |
| 76 | + await this.runActions(streamrClient, minStakePerSponsorship) |
| 77 | + } catch (err) { |
| 78 | + logger.warn('Error while running autostaker actions', { err }) |
| 79 | + } |
| 80 | + }, this.pluginConfig.runIntervalInMs, 0.1, false, this.abortController.signal) |
| 81 | + } |
| 82 | + |
| 83 | + private async runActions(streamrClient: StreamrClient, minStakePerSponsorship: bigint): Promise<void> { |
| 84 | + logger.info('Run autostaker analysis') |
| 85 | + const provider = (await streamrClient.getSigner()).provider |
| 86 | + const operatorContract = _operatorContractUtils.getOperatorContract(this.pluginConfig.operatorContractAddress) |
| 87 | + .connect(provider) |
| 88 | + const myCurrentStakes = await this.getMyCurrentStakes(streamrClient) |
| 89 | + const stakeableSponsorships = await this.getStakeableSponsorships(myCurrentStakes, streamrClient) |
| 90 | + const myStakedAmount = await operatorContract.totalStakedIntoSponsorshipsWei() |
| 91 | + const myUnstakedAmount = (await operatorContract.valueWithoutEarnings()) - myStakedAmount |
| 92 | + logger.debug('Analysis state', { |
| 93 | + stakeableSponsorships: [...stakeableSponsorships.entries()].map(([sponsorshipId, config]) => ({ |
| 94 | + sponsorshipId, |
| 95 | + payoutPerSec: formatEther(config.payoutPerSec) |
| 96 | + })), |
| 97 | + myCurrentStakes: [...myCurrentStakes.entries()].map(([sponsorshipId, amount]) => ({ |
| 98 | + sponsorshipId, |
| 99 | + amount: formatEther(amount) |
| 100 | + })), |
| 101 | + balance: { |
| 102 | + unstaked: formatEther(myUnstakedAmount), |
| 103 | + staked: formatEther(myStakedAmount) |
| 104 | + } |
| 105 | + }) |
| 106 | + const actions = adjustStakes({ |
| 107 | + myCurrentStakes, |
| 108 | + myUnstakedAmount, |
| 109 | + stakeableSponsorships, |
| 110 | + operatorContractAddress: this.pluginConfig.operatorContractAddress, |
| 111 | + maxSponsorshipCount: this.pluginConfig.maxSponsorshipCount, |
| 112 | + minTransactionAmount: parseEther(String(this.pluginConfig.minTransactionDataTokenAmount)), |
| 113 | + minStakePerSponsorship |
| 114 | + }) |
| 115 | + const signer = await streamrClient.getSigner() |
| 116 | + for (const action of actions) { |
| 117 | + logger.info(`Execute action: ${action.type} ${formatEther(action.amount)} ${action.sponsorshipId}`) |
| 118 | + await getStakeOrUnstakeFunction(action)(signer, |
| 119 | + this.pluginConfig.operatorContractAddress, |
| 120 | + action.sponsorshipId, |
| 121 | + action.amount |
| 122 | + ) |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + private async getStakeableSponsorships( |
| 127 | + stakes: Map<SponsorshipID, WeiAmount>, |
| 128 | + streamrClient: StreamrClient |
| 129 | + ): Promise<Map<SponsorshipID, SponsorshipConfig>> { |
| 130 | + const queryResult = streamrClient.getTheGraphClient().queryEntities<SponsorshipQueryResultItem>((lastId: string, pageSize: number) => { |
| 131 | + // TODO add support spnsorships which have non-zero minimumStakingPeriodSeconds (i.e. implement some loggic in the |
| 132 | + // payoutPropotionalStrategy so that we ensure that unstaking doesn't happen too soon) |
| 133 | + return { |
| 134 | + query: ` |
| 135 | + { |
| 136 | + sponsorships ( |
| 137 | + where: { |
| 138 | + projectedInsolvency_gt: ${Math.floor(Date.now() / 1000)} |
| 139 | + minimumStakingPeriodSeconds: "0" |
| 140 | + minOperators_lte: ${this.pluginConfig.maxAcceptableMinOperatorCount} |
| 141 | + totalPayoutWeiPerSec_gte: "${MIN_SPONSORSHIP_TOTAL_PAYOUT_PER_SECOND.toString()}" |
| 142 | + id_gt: "${lastId}" |
| 143 | + }, |
| 144 | + first: ${pageSize} |
| 145 | + ) { |
| 146 | + id |
| 147 | + totalPayoutWeiPerSec |
| 148 | + operatorCount |
| 149 | + maxOperators |
| 150 | + } |
| 151 | + } |
| 152 | + ` |
| 153 | + } |
| 154 | + }) |
| 155 | + const sponsorships = await collect(queryResult) |
| 156 | + const hasAcceptableOperatorCount = (item: SponsorshipQueryResultItem) => { |
| 157 | + if (stakes.has(item.id)) { |
| 158 | + // this operator has already staked to the sponsorship: keep the sponsorship in the list so that |
| 159 | + // we don't unstake from it |
| 160 | + return true |
| 161 | + } else { |
| 162 | + return (item.maxOperators === null) || (item.operatorCount < item.maxOperators) |
| 163 | + } |
| 164 | + } |
| 165 | + return new Map(sponsorships.filter(hasAcceptableOperatorCount).map( |
| 166 | + (sponsorship) => [sponsorship.id, { |
| 167 | + payoutPerSec: BigInt(sponsorship.totalPayoutWeiPerSec), |
| 168 | + }]) |
| 169 | + ) |
| 170 | + } |
| 171 | + |
| 172 | + private async getMyCurrentStakes(streamrClient: StreamrClient): Promise<Map<SponsorshipID, WeiAmount>> { |
| 173 | + const queryResult = streamrClient.getTheGraphClient().queryEntities<StakeQueryResultItem>((lastId: string, pageSize: number) => { |
| 174 | + return { |
| 175 | + query: ` |
| 176 | + { |
| 177 | + stakes ( |
| 178 | + where: { |
| 179 | + operator: "${this.pluginConfig.operatorContractAddress.toLowerCase()}", |
| 180 | + id_gt: "${lastId}" |
| 181 | + }, |
| 182 | + first: ${pageSize} |
| 183 | + ) { |
| 184 | + id |
| 185 | + sponsorship { |
| 186 | + id |
| 187 | + } |
| 188 | + amountWei |
| 189 | + } |
| 190 | + } |
| 191 | + ` |
| 192 | + } |
| 193 | + }) |
| 194 | + const stakes = await collect(queryResult) |
| 195 | + return new Map(stakes.map((stake) => [stake.sponsorship.id, BigInt(stake.amountWei) ])) |
| 196 | + } |
| 197 | + |
| 198 | + async stop(): Promise<void> { |
| 199 | + logger.info('Stop autostaker plugin') |
| 200 | + this.abortController.abort() |
| 201 | + } |
| 202 | + |
| 203 | + // eslint-disable-next-line class-methods-use-this |
| 204 | + override getConfigSchema(): Schema { |
| 205 | + return PLUGIN_CONFIG_SCHEMA |
| 206 | + } |
| 207 | +} |
0 commit comments