Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile.node
Original file line number Diff line number Diff line change
@@ -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 \
Expand All @@ -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 \
Expand Down
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/cli-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion packages/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
137 changes: 72 additions & 65 deletions packages/node/src/plugins/autostaker/AutostakerPlugin.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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<ContractTransactionReceipt | null>
}
Expand All @@ -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<ContractTransactionReceipt | null> => {
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<SponsorshipID, WeiAmount>
): { 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<AutostakerPluginConfig> {
Expand Down Expand Up @@ -142,33 +163,40 @@ export class AutostakerPlugin extends Plugin<AutostakerPluginConfig> {
})
}

// Broadcasts a transaction corresponding to the action without waiting for it to be mined
private async submitAction(action: Action, signer: SignerWithProvider, txOpts: TransactionOpts): Promise<SubmitActionResult> {
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<SubmitActionsResult> {
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)
})
}

// This will retry the transaction preflight checks, defends against various transient errors
private async submitActionWithRetry(action: Action, signer: SignerWithProvider, txOpts: TransactionOpts): Promise<SubmitActionResult> {
private async submitActionsWithRetry(
reductions: StakeReduction[],
increases: StakeIncrease[],
signer: SignerWithProvider
): Promise<SubmitActionsResult> {
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,
)
Expand Down Expand Up @@ -211,47 +239,26 @@ export class AutostakerPlugin extends Plugin<AutostakerPluginConfig> {
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<SubmitActionResult>[] = []

// 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 })
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
57 changes: 57 additions & 0 deletions packages/sdk/src/contracts/operatorContractUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ContractTransactionReceipt | null> => {
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,
Expand Down
8 changes: 6 additions & 2 deletions packages/sdk/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,12 @@ import {
sponsor,
stake,
unstake,
rebalanceStake,
DeploySponsorshipContractOpts,
getOperatorContract,
TransactionOpts
TransactionOpts,
StakeReduction,
StakeIncrease
} from './contracts/operatorContractUtils'

/**
Expand All @@ -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'
Loading
Loading