diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dedb653e7..615c2b140e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,8 @@ Changes before Tatum release are not documented in this file. #### Changed +- Autostaker plugin executes all unstake and stake actions of a run atomically in a single `rebalanceStake` transaction instead of one transaction per action + #### Deprecated #### Removed diff --git a/Dockerfile.node b/Dockerfile.node index fcdedd6ace..814038034c 100644 --- a/Dockerfile.node +++ b/Dockerfile.node @@ -1,5 +1,5 @@ ARG NODE_VERSION=22 -FROM node:${NODE_VERSION}-bullseye AS build +FROM node:${NODE_VERSION}-bookworm AS build WORKDIR /usr/src/network COPY . . RUN --mount=type=cache,target=/root/.npm \ @@ -15,7 +15,7 @@ RUN --mount=type=cache,target=/root/.npm \ npm run prune-pkg -- @streamr/node RUN cd packages/node; for file in dist/bin/*.js; do ln -s "../$file" "bin/$(basename "$file")"; done -FROM node:${NODE_VERSION}-bullseye-slim +FROM node:${NODE_VERSION}-bookworm-slim ARG NODE_ENV ENV NODE_ENV=${NODE_ENV:-production} RUN apt-get update && apt-get --assume-yes --no-install-recommends install \ diff --git a/package-lock.json b/package-lock.json index 66e46ca7a2..3d663f64e6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7139,9 +7139,9 @@ "link": true }, "node_modules/@streamr/network-contracts": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/@streamr/network-contracts/-/network-contracts-9.1.0.tgz", - "integrity": "sha512-OW+eJQOpcColPvPjJQ0Udaee4AlN2wTZwK7Hj6Vq59qdGWYv9FSxv+kSrYAbBvjuHvTkjH8UkbI1kYVPX2pm7A==", + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/@streamr/network-contracts/-/network-contracts-9.2.0.tgz", + "integrity": "sha512-g3PhbTn/eKE2t1jFgKthlkjMECDtlxCZK/T2UTgXF9g2TeGWM06pQq5I4UXttbdendLIXXTaDAK0Bu06Cs3m4w==", "license": "STREAMR NETWORK OPEN SOURCE LICENSE" }, "node_modules/@streamr/node": { @@ -28468,7 +28468,7 @@ "dependencies": { "@streamr/config": "^5.9.3", "@streamr/dht": "103.3.2", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/sdk": "103.3.2", "@streamr/trackerless-network": "103.3.2", "@streamr/utils": "103.3.2", @@ -28772,7 +28772,7 @@ }, "devDependencies": { "@inquirer/testing": "^2.1.51", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/test-utils": "103.3.2", "@types/cors": "^2.8.19", "@types/express": "^5.0.1", @@ -28921,7 +28921,7 @@ "@protobuf-ts/runtime-rpc": "^2.8.2", "@streamr/config": "^5.9.3", "@streamr/dht": "103.3.2", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/proto-rpc": "103.3.2", "@streamr/trackerless-network": "103.3.2", "@streamr/utils": "103.3.2", @@ -29080,7 +29080,7 @@ "license": "Apache-2.0", "dependencies": { "@streamr/config": "^5.9.3", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/utils": "103.3.2", "cors": "^2.8.5", "ethers": "^6.13.0", diff --git a/packages/cli-tools/package.json b/packages/cli-tools/package.json index f38fbb336b..1499b36ce4 100644 --- a/packages/cli-tools/package.json +++ b/packages/cli-tools/package.json @@ -34,7 +34,7 @@ "dependencies": { "@streamr/config": "^5.9.3", "@streamr/dht": "103.3.2", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/sdk": "103.3.2", "@streamr/trackerless-network": "103.3.2", "@streamr/utils": "103.3.2", diff --git a/packages/node/package.json b/packages/node/package.json index be70d136a4..66bd77eb70 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -64,7 +64,7 @@ }, "devDependencies": { "@inquirer/testing": "^2.1.51", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/test-utils": "103.3.2", "@types/cors": "^2.8.19", "@types/express": "^5.0.1", diff --git a/packages/node/src/plugins/autostaker/AutostakerPlugin.ts b/packages/node/src/plugins/autostaker/AutostakerPlugin.ts index 4de5fca51c..2fe74ca4e0 100644 --- a/packages/node/src/plugins/autostaker/AutostakerPlugin.ts +++ b/packages/node/src/plugins/autostaker/AutostakerPlugin.ts @@ -1,4 +1,11 @@ -import { _operatorContractUtils, type SignerWithProvider, type SponsorshipCreatedEvent, StreamrClient, type TransactionOpts } from '@streamr/sdk' +import { + _operatorContractUtils, + type SignerWithProvider, + type SponsorshipCreatedEvent, + type StakeIncrease, + type StakeReduction, + StreamrClient +} from '@streamr/sdk' import { collect, Logger, retry, scheduleAtApproximateInterval, TheGraphClient, toEthereumAddress, WeiAmount } from '@streamr/utils' import { Schema } from 'ajv' import { ContractTransactionReceipt, ContractTransactionResponse, formatEther, parseEther } from 'ethers' @@ -52,10 +59,9 @@ const logger = new Logger('AutostakerPlugin') const MIN_SPONSORSHIP_TOTAL_PAYOUT_PER_SECOND = 1000000000000n const ACTION_SUBMIT_RETRY_COUNT = 5 const ACTION_SUBMIT_RETRY_DELAY_MS = 5000 -const ACTION_GAS_LIMIT = 750000n const TRANSACTION_TIMEOUT = 180 * 1000 -interface SubmitActionResult { +interface SubmitActionsResult { txResponse: ContractTransactionResponse txReceiptPromise: Promise } @@ -73,23 +79,38 @@ const fetchMinStakePerSponsorship = async (theGraphClient: TheGraphClient): Prom return BigInt(queryResult.network.minimumStakeWei) } -const getStakeOrUnstakeFunction = (action: Action): ( - operatorOwnerWallet: SignerWithProvider, - operatorContractAddress: string, - sponsorshipContractAddress: string, - amount: WeiAmount, - txOpts: TransactionOpts, - onSubmit: (tx: ContractTransactionResponse) => void, - transactionTimeout?: number -) => Promise => { - switch (action.type) { - case 'stake': - return _operatorContractUtils.stake - case 'unstake': - return _operatorContractUtils.unstake - default: - throw new Error('assertion failed') +/* + * Converts the actions to the parameters of the Operator contract's `rebalanceStake` function: + * unstake actions are expressed as the stake to leave in the sponsorship, and stake actions as the amount to add. + */ +const toRebalanceParams = ( + actions: Action[], + myCurrentStakes: Map +): { reductions: StakeReduction[], increases: StakeIncrease[] } => { + const reductions: StakeReduction[] = [] + const increases: StakeIncrease[] = [] + for (const action of actions) { + switch (action.type) { + case 'unstake': { + const currentAmount = myCurrentStakes.get(action.sponsorshipId) + if (currentAmount === undefined) { + throw new Error(`assertion failed: no current stake for sponsorship ${action.sponsorshipId}`) + } + const targetAmount = currentAmount - action.amount + if (targetAmount < 0n) { + throw new Error(`assertion failed: unstake amount exceeds current stake for sponsorship ${action.sponsorshipId}`) + } + reductions.push({ sponsorshipContractAddress: action.sponsorshipId, targetAmount }) + break + } + case 'stake': + increases.push({ sponsorshipContractAddress: action.sponsorshipId, amount: action.amount }) + break + default: + throw new Error('assertion failed') + } } + return { reductions, increases } } export class AutostakerPlugin extends Plugin { @@ -142,19 +163,22 @@ export class AutostakerPlugin extends Plugin { }) } - // Broadcasts a transaction corresponding to the action without waiting for it to be mined - private async submitAction(action: Action, signer: SignerWithProvider, txOpts: TransactionOpts): Promise { - logger.info(`Execute action: ${action.type} ${formatEther(action.amount)} ${action.sponsorshipId}`) - const stakeOrUnstakeFunction = getStakeOrUnstakeFunction(action) + // Broadcasts a single transaction which executes all the actions atomically, without waiting for it to be mined + private async submitActions( + reductions: StakeReduction[], + increases: StakeIncrease[], + signer: SignerWithProvider + ): Promise { return new Promise((resolve, reject) => { - const txReceiptPromise = stakeOrUnstakeFunction(signer, + const txReceiptPromise = _operatorContractUtils.rebalanceStake( + signer, this.pluginConfig.operatorContractAddress, - action.sponsorshipId, - action.amount, - txOpts, - // resolve on the onSubmit callback (=tx is broadcasted) instead of when the stakeOrUnstakeFunction resolves (=tx is mined) + reductions, + increases, + {}, + // resolve on the onSubmit callback (=tx is broadcasted) instead of when rebalanceStake resolves (=tx is mined) (txResponse) => resolve({ txResponse, txReceiptPromise }), - TRANSACTION_TIMEOUT + TRANSACTION_TIMEOUT ) // Propagate errors that occur before onSubmit is called txReceiptPromise.catch(reject) @@ -162,13 +186,17 @@ export class AutostakerPlugin extends Plugin { } // This will retry the transaction preflight checks, defends against various transient errors - private async submitActionWithRetry(action: Action, signer: SignerWithProvider, txOpts: TransactionOpts): Promise { + private async submitActionsWithRetry( + reductions: StakeReduction[], + increases: StakeIncrease[], + signer: SignerWithProvider + ): Promise { return await retry( - () => this.submitAction(action, signer, txOpts), + () => this.submitActions(reductions, increases, signer), (message, error) => { logger.error(message, { error }) }, - `Submit action to ${action.type} ${formatEther(action.amount)} from ${action.sponsorshipId}`, + `Submit rebalance transaction (${reductions.length} unstake actions, ${increases.length} stake actions)`, ACTION_SUBMIT_RETRY_COUNT, ACTION_SUBMIT_RETRY_DELAY_MS, ) @@ -211,47 +239,26 @@ export class AutostakerPlugin extends Plugin { logger.info('Analysis done, no actions to execute') return } - logger.info(`Analysis done, proceeding to execute plan with ${actions.length} actions`, { + logger.info(`Analysis done, proceeding to execute plan with ${actions.length} actions in one transaction`, { actions: actions.map((a) => ({ ...a, amount: formatEther(a.amount) })) }) - // Ensure that all unstake actions are executed before any stake actions to ensure sufficient liquidity - const orderedActions = [ - ...actions.filter((a) => a.type === 'unstake'), - ...actions.filter((a) => a.type === 'stake') - ] - const allSubmitActionPromises: Promise[] = [] - - // Set nonce explicitly, because ethers tends to mess up nonce if we submit - // multiple transactions in quick succession - const address = await signer.getAddress() - let nonce = await signer.provider.getTransactionCount(address) - - // Broadcast each action but don't wait for them to be mined - for (const action of orderedActions) { - const submitActionPromise = this.submitActionWithRetry(action, signer, { - // Use a fixed gas limit - gas estimation of stake transactions would fails - // with "not enough balance", because we first need to unstake before we stake - gasLimit: ACTION_GAS_LIMIT, - // Explicit nonce - nonce: nonce++, - }) - allSubmitActionPromises.push(submitActionPromise) - } - - const allReceiptPromises = allSubmitActionPromises.map(async (p) => (await p).txReceiptPromise) + // All actions are executed atomically in a single `rebalanceStake` transaction: the contract first reduces + // the stakes (which ensures sufficient liquidity) and then stakes into the sponsorships. If any of the + // actions can't be executed (e.g. a sponsorship is full), the whole transaction fails and no stake is touched. + const { reductions, increases } = toRebalanceParams(actions, myCurrentStakes) + const { txResponse, txReceiptPromise } = await this.submitActionsWithRetry(reductions, increases, signer) + logger.info('Rebalance transaction submitted, waiting for it to be mined', { tx: txResponse.hash }) - // Wait for all transactions to be mined (don't stop waiting if some of them fail) // Note that if the actual submitted transaction errors, it won't get retried. This should be rare. - const settledResults = await Promise.allSettled(allReceiptPromises) - const successfulResults = settledResults.filter((r) => r.status === 'fulfilled') - const failedResults = settledResults.filter((r) => r.status === 'rejected') - logger.info(`All actions finished. Successful actions: ${successfulResults.length}, Failed actions: ${failedResults.length}`) - if (failedResults.length > 0) { - logger.error('Failed to execute some actions:', { failedResults }) + try { + const receipt = await txReceiptPromise + logger.info(`All ${actions.length} actions executed successfully`, { tx: receipt?.hash }) + } catch (err) { + logger.error('Failed to execute actions', { tx: txResponse.hash, err }) } } diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 562068ec18..6f221c9f22 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -90,7 +90,7 @@ "@protobuf-ts/runtime-rpc": "^2.8.2", "@streamr/config": "^5.9.3", "@streamr/dht": "103.3.2", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/proto-rpc": "103.3.2", "@streamr/trackerless-network": "103.3.2", "@streamr/utils": "103.3.2", diff --git a/packages/sdk/src/contracts/operatorContractUtils.ts b/packages/sdk/src/contracts/operatorContractUtils.ts index 35b8002731..ff5af3e272 100644 --- a/packages/sdk/src/contracts/operatorContractUtils.ts +++ b/packages/sdk/src/contracts/operatorContractUtils.ts @@ -230,6 +230,63 @@ export const unstake = async ( } } +/** + * @deprecated + * @hidden + */ +export interface StakeReduction { + sponsorshipContractAddress: string + // the stake to leave in the sponsorship (zero means unstake completely) + targetAmount: WeiAmount +} + +/** + * @deprecated + * @hidden + */ +export interface StakeIncrease { + sponsorshipContractAddress: string + amount: WeiAmount +} + +/** + * Reduces stake in some sponsorships and stakes into others atomically, in one transaction. + * The transaction fails fast (before any stake is touched) if one of the sponsorships to stake into is already full. + */ +export const rebalanceStake = async ( + staker: SignerWithProvider, + operatorContractAddress: string, + reductions: StakeReduction[], + increases: StakeIncrease[], + txOpts: TransactionOpts = {}, + onSubmit: (tx: ContractTransactionResponse) => void = () => {}, + transactionTimeout?: number +): Promise => { + logger.debug('Rebalance stake', { + reductions: reductions.map((r) => ({ ...r, targetAmount: formatEther(r.targetAmount) })), + increases: increases.map((i) => ({ ...i, amount: formatEther(i.amount) })) + }) + const operatorContract = getOperatorContract(operatorContractAddress).connect(staker) + const tx = await operatorContract.rebalanceStake( + reductions.map((r) => r.sponsorshipContractAddress), + reductions.map((r) => r.targetAmount), + increases.map((i) => i.sponsorshipContractAddress), + increases.map((i) => i.amount), + txOpts + ) + logger.debug('Rebalance stake: transaction submitted', { tx: tx.hash, nonce: tx.nonce }) + onSubmit(tx) + logger.debug('Rebalance stake: waiting for transaction to be mined', { tx: tx.hash, timeout: transactionTimeout }) + try { + const receipt = await tx.wait(undefined, transactionTimeout) + logger.debug('Rebalance stake: confirmation received', { receipt: receipt?.hash }) + return receipt + } catch (error) { + logger.error(`Rebalance stake: error waiting for tx to be mined`, { tx: tx.hash, error }) + throw error + } +} + export const sponsor = async ( sponsorer: SignerWithProvider, sponsorshipContractAddress: string, diff --git a/packages/sdk/src/exports.ts b/packages/sdk/src/exports.ts index 2a9549451e..1987786034 100644 --- a/packages/sdk/src/exports.ts +++ b/packages/sdk/src/exports.ts @@ -111,9 +111,12 @@ import { sponsor, stake, unstake, + rebalanceStake, DeploySponsorshipContractOpts, getOperatorContract, - TransactionOpts + TransactionOpts, + StakeReduction, + StakeIncrease } from './contracts/operatorContractUtils' /** @@ -128,11 +131,12 @@ const _operatorContractUtils = { sponsor, stake, unstake, + rebalanceStake, deployOperatorContract, getOperatorContract, } export { _operatorContractUtils } -export type { DeployOperatorContractOpts, DeploySponsorshipContractOpts, TransactionOpts } +export type { DeployOperatorContractOpts, DeploySponsorshipContractOpts, TransactionOpts, StakeReduction, StakeIncrease } export type { IceServer, PeerDescriptor, PortRange } from '@streamr/dht' export type { AbstractSigner, Eip1193Provider, Overrides } from 'ethers' diff --git a/packages/sdk/test/end-to-end/operatorContractUtils.test.ts b/packages/sdk/test/end-to-end/operatorContractUtils.test.ts index 98fbc58718..f9efd2df2c 100644 --- a/packages/sdk/test/end-to-end/operatorContractUtils.test.ts +++ b/packages/sdk/test/end-to-end/operatorContractUtils.test.ts @@ -105,4 +105,44 @@ describeOnlyInNodeJs('operatorContractUtils', () => { ) expect(await sponsorshipContract.stakedWei(operatorContract.getAddress())).toBe(parseEther('7000')) }) + + it('rebalanceStake', async () => { + const operator = await createTestWallet({ gas: true, tokens: true }) + const operatorContract = await _operatorContractUtils.deployOperatorContract({ + deployer: operator, + environmentId: 'dev2' + }) + const operatorContractAddress = await operatorContract.getAddress() + const deploySponsorship = async () => { + const stream = await createTestStream(createTestClient((await createTestWallet({ gas: true })).privateKey), module) + return _operatorContractUtils.deploySponsorshipContract({ + streamId: stream.id, + deployer: operator, + earningsPerSecond: 123n, + environmentId: 'dev2' + }) + } + const sponsorship1 = await deploySponsorship() + const sponsorship2 = await deploySponsorship() + const sponsorship3 = await deploySponsorship() + await _operatorContractUtils.delegate(operator, operatorContractAddress, parseEther('20000')) + await _operatorContractUtils.stake(operator, operatorContractAddress, await sponsorship1.getAddress(), parseEther('10000')) + await _operatorContractUtils.stake(operator, operatorContractAddress, await sponsorship2.getAddress(), parseEther('10000')) + + // reduce stake in sponsorship1, unstake completely from sponsorship2, stake into sponsorship3 + await _operatorContractUtils.rebalanceStake( + operator, + operatorContractAddress, + [ + { sponsorshipContractAddress: await sponsorship1.getAddress(), targetAmount: parseEther('6000') }, + { sponsorshipContractAddress: await sponsorship2.getAddress(), targetAmount: 0n } + ], + [ + { sponsorshipContractAddress: await sponsorship3.getAddress(), amount: parseEther('14000') } + ] + ) + expect(await sponsorship1.stakedWei(operatorContractAddress)).toBe(parseEther('6000')) + expect(await sponsorship2.stakedWei(operatorContractAddress)).toBe(0n) + expect(await sponsorship3.stakedWei(operatorContractAddress)).toBe(parseEther('14000')) + }) }) diff --git a/packages/test-utils/package.json b/packages/test-utils/package.json index 527313c99f..cda5d87071 100644 --- a/packages/test-utils/package.json +++ b/packages/test-utils/package.json @@ -64,7 +64,7 @@ "license": "Apache-2.0", "dependencies": { "@streamr/config": "^5.9.3", - "@streamr/network-contracts": "^9.1.0", + "@streamr/network-contracts": "^9.2.0", "@streamr/utils": "103.3.2", "cors": "^2.8.5", "ethers": "^6.13.0",