Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: enable withdraw all stake endpoint #3662

Merged
8 commits merged into from Dec 16, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions openapi/SwarmCommon.yaml
Expand Up @@ -586,6 +586,18 @@ components:
stakedAmount:
$ref: "#/components/schemas/BigInt"

StakeDepositResponse:
type: object
properties:
txHash:
$ref: "#/components/schemas/TransactionHash"

WithdrawAllStakeResponse:
type: object
properties:
txHash:
$ref: "#/components/schemas/TransactionHash"

SwarmOnlyReference:
oneOf:
- $ref: "#/components/schemas/SwarmAddress"
Expand Down
17 changes: 17 additions & 0 deletions openapi/SwarmDebug.yaml
Expand Up @@ -1056,6 +1056,23 @@ paths:
$ref: "SwarmCommon.yaml#/components/responses/500"
default:
description: Default response
delete:
summary: Withdraw all staked amount.
description: Be aware, this endpoint creates an on-chain transactions and transfers BZZ from the node's Ethereum account and hence directly manipulates the wallet balance.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor: we can either drop the an or use transaction (singular)

tags:
- Staking
parameters:
- $ref: "SwarmCommon.yaml#/components/parameters/GasPriceParameter"
- $ref: "SwarmCommon.yaml#/components/parameters/GasLimitParameter"
responses:
"200":
$ref: "SwarmCommon.yaml#/components/schemas/WithdrawAllStakeResponse"
"400":
$ref: "SwarmCommon.yaml#/components/responses/400"
"500":
$ref: "SwarmCommon.yaml#/components/responses/500"
default:
description: Default response

"/loggers":
get:
Expand Down
1 change: 1 addition & 0 deletions pkg/api/export_test.go
Expand Up @@ -100,6 +100,7 @@ type (
BucketData = bucketData
WalletResponse = walletResponse
GetStakeResponse = getStakeResponse
WithdrawAllStakeResponse = withdrawAllStakeResponse
)

var (
Expand Down
4 changes: 3 additions & 1 deletion pkg/api/router.go
Expand Up @@ -562,8 +562,10 @@ func (s *Service) mountBusinessDebug(restricted bool) {

handle("/stake", web.ChainHandlers(
s.stakingAccessHandler,
s.gasConfigMiddleware("get or withdraw stake"),
web.FinalHandler(jsonhttp.MethodHandler{
"GET": http.HandlerFunc(s.getStakedAmountHandler),
"GET": http.HandlerFunc(s.getStakedAmountHandler),
"DELETE": http.HandlerFunc(s.withdrawAllStakeHandler),
})),
)
}
27 changes: 26 additions & 1 deletion pkg/api/staking.go
Expand Up @@ -6,10 +6,11 @@ package api

import (
"errors"
"github.com/ethersphere/bee/pkg/bigint"
"math/big"
"net/http"

"github.com/ethersphere/bee/pkg/bigint"

"github.com/ethersphere/bee/pkg/jsonhttp"
"github.com/ethersphere/bee/pkg/storageincentives/staking"
"github.com/gorilla/mux"
Expand All @@ -36,6 +37,10 @@ type stakeDepositResponse struct {
TxHash string `json:"txhash"`
}

type withdrawAllStakeResponse struct {
TxHash string `json:"txhash"`
}

func (s *Service) stakingDepositHandler(w http.ResponseWriter, r *http.Request) {
logger := s.logger.WithName("post_stake_deposit").Build()

Expand Down Expand Up @@ -90,3 +95,23 @@ func (s *Service) getStakedAmountHandler(w http.ResponseWriter, r *http.Request)

jsonhttp.OK(w, getStakeResponse{StakedAmount: bigint.Wrap(stakedAmount)})
}

func (s *Service) withdrawAllStakeHandler(w http.ResponseWriter, r *http.Request) {
logger := s.logger.WithName("delete_withdraw_all_stake").Build()

txHash, err := s.stakingContract.WithdrawAllStake(r.Context())
if err != nil {
if errors.Is(err, staking.ErrInsufficientStake) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just wondering: if we withdraw the entire amount of the stake, can we gen the insufficient stake error?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nope, this edge case deals with the fact that we did not have any stake to begin with

logger.Debug("insufficient stake", "overlayAddr", s.overlay, "error", err)
logger.Error(nil, "insufficient stake")
jsonhttp.BadRequest(w, "insufficient stake to withdraw")
return
}
logger.Debug("withdraw stake failed", "error", err)
logger.Error(nil, "withdraw stake failed")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The log message should be the same as the debug message.

jsonhttp.InternalServerError(w, "cannot withdraw stake")
return
}

jsonhttp.OK(w, withdrawAllStakeResponse{TxHash: txHash.String()})
}
72 changes: 70 additions & 2 deletions pkg/api/staking_test.go
Expand Up @@ -7,12 +7,13 @@ package api_test
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/bigint"
"math/big"
"net/http"
"testing"

"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/bigint"

"github.com/ethersphere/bee/pkg/api"
"github.com/ethersphere/bee/pkg/jsonhttp"
"github.com/ethersphere/bee/pkg/jsonhttp/jsonhttptest"
Expand Down Expand Up @@ -170,3 +171,70 @@ func Test_stakingDepositHandler_invalidInputs(t *testing.T) {
})
}
}

func TestWithdrawAllStake(t *testing.T) {
t.Parallel()

txHash := common.HexToHash("0x1234")

t.Run("ok", func(t *testing.T) {
t.Parallel()

contract := stakingContractMock.New(
stakingContractMock.WithWithdrawAllStake(func(ctx context.Context) (common.Hash, error) {
return txHash, nil
}),
)
ts, _, _, _ := newTestServer(t, testServerOptions{DebugAPI: true, StakingContract: contract})
jsonhttptest.Request(t, ts, http.MethodDelete, "/stake", http.StatusOK, jsonhttptest.WithExpectedJSONResponse(
&api.WithdrawAllStakeResponse{TxHash: txHash.String()}))
})

t.Run("with invalid stake amount", func(t *testing.T) {
t.Parallel()

contract := stakingContractMock.New(
stakingContractMock.WithWithdrawAllStake(func(ctx context.Context) (common.Hash, error) {
return common.Hash{}, staking.ErrInsufficientStake
}),
)
ts, _, _, _ := newTestServer(t, testServerOptions{DebugAPI: true, StakingContract: contract})
jsonhttptest.Request(t, ts, http.MethodDelete, "/stake", http.StatusBadRequest,
jsonhttptest.WithExpectedJSONResponse(&jsonhttp.StatusResponse{Code: http.StatusBadRequest, Message: "insufficient stake to withdraw"}))
})

t.Run("internal error", func(t *testing.T) {
t.Parallel()

contract := stakingContractMock.New(
stakingContractMock.WithWithdrawAllStake(func(ctx context.Context) (common.Hash, error) {
return common.Hash{}, fmt.Errorf("some error")
}),
)
ts, _, _, _ := newTestServer(t, testServerOptions{DebugAPI: true, StakingContract: contract})
jsonhttptest.Request(t, ts, http.MethodDelete, "/stake", http.StatusInternalServerError)
jsonhttptest.WithExpectedJSONResponse(&jsonhttp.StatusResponse{Code: http.StatusInternalServerError, Message: "cannot withdraw stake"})
})

t.Run("gas limit header", func(t *testing.T) {
t.Parallel()

contract := stakingContractMock.New(
stakingContractMock.WithWithdrawAllStake(func(ctx context.Context) (common.Hash, error) {
gasLimit := sctx.GetGasLimit(ctx)
if gasLimit != 2000000 {
t.Fatalf("want 2000000, got %d", gasLimit)
}
return txHash, nil
}),
)
ts, _, _, _ := newTestServer(t, testServerOptions{
DebugAPI: true,
StakingContract: contract,
})

jsonhttptest.Request(t, ts, http.MethodDelete, "/stake", http.StatusOK,
jsonhttptest.WithRequestHeader("Gas-Limit", "2000000"),
)
})
}
115 changes: 102 additions & 13 deletions pkg/storageincentives/staking/contract.go
Expand Up @@ -27,15 +27,19 @@ var (

ErrInsufficientStakeAmount = errors.New("insufficient stake amount")
ErrInsufficientFunds = errors.New("insufficient token balance")
ErrInsufficientStake = errors.New("insufficient stake")
ErrNotImplemented = errors.New("not implemented")
ErrNotPaused = errors.New("contract is not paused")

approveDescription = "Approve tokens for stake deposit operations"
depositStakeDescription = "Deposit Stake"
approveDescription = "Approve tokens for stake deposit operations"
depositStakeDescription = "Deposit Stake"
withdrawStakeDescription = "Withdraw stake"
)

type Contract interface {
DepositStake(ctx context.Context, stakedAmount *big.Int) (common.Hash, error)
GetStake(ctx context.Context) (*big.Int, error)
WithdrawAllStake(ctx context.Context) (common.Hash, error)
}

type contract struct {
Expand Down Expand Up @@ -158,42 +162,46 @@ func (c *contract) getStake(ctx context.Context, overlay swarm.Address) (*big.In
if err != nil {
return nil, err
}

if len(results) == 0 {
return nil, errors.New("unexpected empty results")
}

return abi.ConvertType(results[0], new(big.Int)).(*big.Int), nil
}

func (c *contract) DepositStake(ctx context.Context, stakedAmount *big.Int) (txHash common.Hash, err error) {
func (c *contract) DepositStake(ctx context.Context, stakedAmount *big.Int) (common.Hash, error) {
prevStakedAmount, err := c.GetStake(ctx)
if err != nil {
return
return common.Hash{}, err
}

if len(prevStakedAmount.Bits()) == 0 {
if stakedAmount.Cmp(MinimumStakeAmount) == -1 {
err = ErrInsufficientStakeAmount
return
return common.Hash{}, ErrInsufficientStakeAmount
}
}

balance, err := c.getBalance(ctx)
if err != nil {
return
return common.Hash{}, err
}

if balance.Cmp(stakedAmount) < 0 {
err = ErrInsufficientFunds
return
return common.Hash{}, ErrInsufficientFunds
}

_, err = c.sendApproveTransaction(ctx, stakedAmount)
if err != nil {
return
return common.Hash{}, err
}

receipt, err := c.sendDepositStakeTransaction(ctx, c.owner, stakedAmount, c.overlayNonce)
if receipt != nil {
txHash = receipt.TxHash
if err != nil {
return common.Hash{}, err
}
return

return receipt.TxHash, nil
}

func (c *contract) GetStake(ctx context.Context) (*big.Int, error) {
Expand Down Expand Up @@ -222,5 +230,86 @@ func (c *contract) getBalance(ctx context.Context) (*big.Int, error) {
if err != nil {
return nil, err
}

if len(results) == 0 {
return nil, errors.New("unexpected empty results")
}

return abi.ConvertType(results[0], new(big.Int)).(*big.Int), nil
}

func (c *contract) WithdrawAllStake(ctx context.Context) (txHash common.Hash, err error) {
This conversation was marked as resolved.
Show resolved Hide resolved
isPaused, err := c.paused(ctx)
if err != nil {
return
}
if !isPaused {
return common.Hash{}, ErrNotPaused
}

stakedAmount, err := c.getStake(ctx, c.overlay)
if err != nil {
return
}

if stakedAmount.Cmp(big.NewInt(0)) <= 0 {
return common.Hash{}, ErrInsufficientStake
}

_, err = c.sendApproveTransaction(ctx, stakedAmount)
if err != nil {
return common.Hash{}, err
}

receipt, err := c.withdrawFromStake(ctx, stakedAmount)
if err != nil {
return common.Hash{}, err
}
if receipt != nil {
txHash = receipt.TxHash
}
return txHash, nil
}

func (c *contract) withdrawFromStake(ctx context.Context, stakedAmount *big.Int) (*types.Receipt, error) {
var overlayAddr [32]byte
copy(overlayAddr[:], c.overlay.Bytes())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the abi packing needs a [32]byte and not a byte slice

Copy link
Author

@ghost ghost Dec 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nope, it needs byte slice, just checked


callData, err := c.stakingContractABI.Pack("withdrawFromStake", overlayAddr, stakedAmount)
if err != nil {
return nil, err
}

receipt, err := c.sendTransaction(ctx, callData, withdrawStakeDescription)
if err != nil {
return nil, fmt.Errorf("withdraw stake: stakedAmount %d: %w", stakedAmount, err)
}

return receipt, nil
}

func (c *contract) paused(ctx context.Context) (bool, error) {
callData, err := c.stakingContractABI.Pack("paused")
if err != nil {
return false, err
}

result, err := c.transactionService.Call(ctx, &transaction.TxRequest{
To: &c.stakingContractAddress,
Data: callData,
})
if err != nil {
return false, err
}

results, err := c.stakingContractABI.Unpack("paused", result)
if err != nil {
return false, err
}

if len(results) == 0 {
return false, errors.New("unexpected empty results")
}

return results[0].(bool), nil
This conversation was marked as resolved.
Show resolved Hide resolved
}