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
23 changes: 23 additions & 0 deletions config/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,38 @@ const (
OpERC721Mint = "erc721_mint"
// OpDisperseEther is Disperse disperseEtherFixed(address[]).
OpDisperseEther = "disperse_ether"
// OpSwapAToB is AMM swapAToB(uint256), the A-for-B leg of a pair.
OpSwapAToB = "swap_a_to_b"
// OpSwapBToA is AMM swapBToA(uint256), the B-for-A leg.
OpSwapBToA = "swap_b_to_a"
)

// StorageRWOperations is the operation set the storagerw scenario draws from.
var StorageRWOperations = NewOperationSet(OpRmw, OpRead, OpWrite)

// AMMOperations is the operation set the amm scenario draws from: both legs of
// one pair, so a profile can weight the direction. A profile that sets no mix
// draws the first name for every transaction, which is one direction — the
// contract holds its reserves between a floor and a ceiling, so that run prices
// the same at its end as at its start.
var AMMOperations = NewOperationSet(OpSwapAToB, OpSwapBToA)

// scenarioOperations maps a scenario's wire name, lowercased, to the operations
// it supports. A scenario absent from the table supports none.
var scenarioOperations = map[string]*OperationSet{
"storagerw": StorageRWOperations,
"amm": AMMOperations,
}

// OperationNamesFor returns every operation a scenario can draw, or nil if it
// draws none. It is exported so a test can check the whole vocabulary a
// scenario reaches the metrics with, rather than only its default.
func OperationNamesFor(scenario string) []string {
set := operationsFor(scenario)
if set == nil {
return nil
}
return set.Names()
}

// operationsFor returns the operations a scenario supports, or nil if it
Expand Down
586 changes: 586 additions & 0 deletions generator/bindings/AMM.go

Large diffs are not rendered by default.

118 changes: 118 additions & 0 deletions generator/contracts/AMM.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title AMM
/// @notice A constant-product swap with the storage and gas shape of a
/// UniswapV2 pair, sized for load generation rather than for correctness.
///
/// A swap here touches what a real pair touches: both reserves, the caller's
/// balance in each token, and an event. That is the cost this contract exists
/// to reproduce. What it does not reproduce is the economics — there is no
/// router, no fee split to an LP, no price oracle and no minimum-output check.
///
/// Nothing reverts on bookkeeping, which is the same choice StorageRWv1.sol
/// makes. The balances wrap instead of checking, because nothing reads them
/// back and a load generator that fails on its own accounting stops measuring
/// the chain. The arithmetic on lines outside the unchecked block stays
/// checked: it reverts only on an input the scenario never sends, and a silent
/// wrap there would price a swap from garbage.
///
/// Every swap writes the same four slots, so after a caller's first swap the
/// cost of its thousandth is the cost of its second.
contract AMM {
uint256 public reserveA;
uint256 public reserveB;

/// @dev The reserve a swap restores an exhausted side to.
uint256 public constant RESERVE_FLOOR = 1_000_000 * 10**18;

/// @dev The reserve above which a swap restores a side to the floor. A run
/// drives one pair for its whole length and only ever adds to the input
/// side, so without a ceiling the price walks away from where it started:
/// measured, the output halves every 100,000 swaps. With it the reserves
/// saw-tooth and the price holds for any run length.
///
/// A swap clamps a reserve as it reads it and writes the result after, so a
/// side settles within one swap's size of each bound rather than exactly on
/// it. Measured over 40 swaps of a tenth of the floor, the input side stayed
/// in [1.1x, 2.1x] of the floor.
///
/// The ceiling is also what keeps one oversized call from ending the pair.
/// A swap of 1e49 leaves the input reserve at 1e49, which without a ceiling
/// prices every later swap at nothing; measured, the next ordinary swap
/// instead resets that side to the floor and pays out in full.
uint256 public constant RESERVE_CEIL = 2 * RESERVE_FLOOR;

mapping(address => uint256) private _balanceA;
mapping(address => uint256) private _balanceB;

event Swap(address indexed sender, bool indexed aToB, uint256 amountIn, uint256 amountOut);

constructor() {
reserveA = RESERVE_FLOOR;
reserveB = RESERVE_FLOOR;
}

function balanceOfA(address account) public view returns (uint256) {
return _balanceA[account];
}

function balanceOfB(address account) public view returns (uint256) {
return _balanceB[account];
}

/// @notice Swap amountIn of token A for token B.
function swapAToB(uint256 amountIn) public returns (uint256) {
return _swap(true, amountIn);
}

/// @notice Swap amountIn of token B for token A.
function swapBToA(uint256 amountIn) public returns (uint256) {
return _swap(false, amountIn);
}

function _swap(bool aToB, uint256 amountIn) private returns (uint256) {
uint256 reserveIn = aToB ? reserveA : reserveB;
uint256 reserveOut = aToB ? reserveB : reserveA;

// Hold both sides between the floor and the ceiling. See RESERVE_CEIL.
if (reserveIn < RESERVE_FLOOR || reserveIn > RESERVE_CEIL) {
reserveIn = RESERVE_FLOOR;
}
if (reserveOut < RESERVE_FLOOR || reserveOut > RESERVE_CEIL) {
reserveOut = RESERVE_FLOOR;
}

// x*y=k with the 0.3% fee UniswapV2 charges, so the arithmetic is the
// same width and the same number of operations.
uint256 amountInWithFee = amountIn * 997;
uint256 numerator = amountInWithFee * reserveOut;
uint256 denominator = reserveIn * 1000 + amountInWithFee;
uint256 amountOut = numerator / denominator;

mapping(address => uint256) storage balIn = aToB ? _balanceA : _balanceB;
mapping(address => uint256) storage balOut = aToB ? _balanceB : _balanceA;

// Wrap rather than revert, and rather than credit a short caller. A
// credit that restores the slot to what it held leaves it at zero for a
// caller that started there, and a zero-to-non-zero write costs four
// times one that changes a slot already holding a value. Under the
// default mix, which draws one direction, that cold write would land on
// every swap the run makes rather than on the first.
unchecked {
balIn[msg.sender] = balIn[msg.sender] - amountIn;
balOut[msg.sender] = balOut[msg.sender] + amountOut;
}

if (aToB) {
reserveA = reserveIn + amountIn;
reserveB = reserveOut - amountOut;
} else {
reserveB = reserveIn + amountIn;
reserveA = reserveOut - amountOut;
}

emit Swap(msg.sender, aToB, amountIn, amountOut);
return amountOut;
}
}
136 changes: 136 additions & 0 deletions generator/scenarios/AMM.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package scenarios

import (
"fmt"
"math/big"
mrand "math/rand/v2"

"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"

"github.com/sei-protocol/sei-load/config"
"github.com/sei-protocol/sei-load/generator/bindings"
"github.com/sei-protocol/sei-load/types"
)

const AMM = "amm"

// ammSwapGas bounds one swap.
//
// The number is a required gas limit read from eth_estimateGas, not a receipt's
// GasUsed. GasUsed is what the chain charges after the refund lands at the end
// of execution; a transaction still has to be provisioned for the peak before
// it. Sizing this constant from a receipt once put it 20% under the limit the
// same swap needed, which fails every transaction and burns the whole limit.
//
// Two shapes, measured over six accounts against the deployed binding on a
// chain running the default storage gas costs:
//
// - 79,988, an account's first swap. It writes the account's balance in both
// tokens from zero, and a zero to non-zero storage write costs four times
// one that changes a slot already holding a value.
// - 45,177, every later swap by that account. The balances wrap rather than
// return to zero, so the slots stay non-zero for the rest of the run.
//
// One limit has to cover the higher shape, so a run in steady state declares
// about 44% more gas than it spends. A chain that admits transactions against
// their declared limit reserves that difference for gas no swap uses, which
// costs the throughput a profile can reach. Priming both slots during prewarm
// would let this drop near the lower shape; that needs a transaction class the
// prewarm path does not have yet, and PLT-1093 carries it.
//
// The calibration assumes the chain charges the default 20,000 for a zero to
// non-zero storage write. Sei sets that as a chain parameter, and pacific-1 and
// atlantic-2 charge about 74,700, which puts the first shape near 185,000
// there. Every hard-coded limit in this package has the same exposure, so
// PLT-1092 covers the package rather than this constant.
//
// Estimating per transaction would put an eth_estimateGas on the send path,
// which is the load this tool exists to avoid adding.
const ammSwapGas = 85_000

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[suggestion] This limit is calibrated for the default 20,000 SSTORE_SET, and the comment above it states that pacific-1 and atlantic-2 charge ~74,700, putting an account's first swap near 185,000. On those chains every account's first swap will land with a failed status and burn the full 85,000, and with trackReceipts defaulting to false the run reports each one as sent — the exact silent failure mode the ERC721 change in this PR fixes.

I understand the exposure is package-wide and PLT-1092 covers it, so this need not block. But a brand-new scenario shipping a limit already known to fail on the two main public chains is worth at least a guard rather than only a comment: e.g. a one-time eth_estimateGas at deploy/bind time to size the constant (off the per-tx send path), or a startup warning when the scenario runs against a chain whose SSTORE_SET is above the default.


// ammSwapAmount is the input every swap sends.
//
// It is fixed rather than drawn, because drawing it would buy no gas coverage.
// Measured across the steady shape, a swap needed 45,141 gas at 1e6 and 45,201
// at 1e23: sixty gas over seventeen orders of magnitude, and all of it the
// calldata bytes of the larger number rather than execution.
//
// The one amount that does change the shape is zero, which makes the output zero
// and turns the payout write into a write of the value already there. The
// scenario never sends it.
//
// A draw would also cost a draw from the run's single PRNG, which every other
// scenario's replay at the same seed depends on.
var ammSwapAmount = new(big.Int).Mul(big.NewInt(10), big.NewInt(1e18))

// AMMScenario drives a constant-product pair, which is the shape most of a DeFi
// workload's transactions have.
type AMMScenario struct {
*ContractScenarioBase[bindings.AMM]
contract *bindings.AMM
operations *config.OperationPicker
}

// NewAMMScenario creates a new AMM scenario.
func NewAMMScenario(cfg config.Scenario) TxGenerator {
scenario := &AMMScenario{
operations: config.AMMOperations.Picker(cfg.Operations),
}
scenario.ContractScenarioBase = NewContractScenarioBase[bindings.AMM](scenario, cfg)
return scenario
}

// Name returns the name of the scenario.
func (s *AMMScenario) Name() string {
return AMM
}

// Operation returns the scenario's default operation.
func (s *AMMScenario) Operation() string {
return config.OpSwapAToB
}

// DeployContract implements ContractDeployer. AMM seeds both reserves in its
// constructor and takes no arguments.
func (s *AMMScenario) DeployContract(opts *bind.TransactOpts, client *ethclient.Client) (common.Address, *ethtypes.Transaction, error) {
address, tx, _, err := bindings.DeployAMM(opts, client)
return address, tx, err
}

// GetBindFunc implements ContractDeployer.
func (s *AMMScenario) GetBindFunc() ContractBindFunc[bindings.AMM] {
return bindings.NewAMM
}

// SetContract implements ContractDeployer.
func (s *AMMScenario) SetContract(contract *bindings.AMM) {
s.contract = contract
}

// CreateContractTransaction implements ContractDeployer - builds one swap in the
// direction the operation mix drew.
func (s *AMMScenario) CreateContractTransaction(rng *mrand.Rand, auth *bind.TransactOpts, scenario *types.TxScenario) (*ethtypes.Transaction, error) {
auth.GasLimit = ammSwapGas

// The draw is part of the replay contract. One draw today, so there is no
// order to get wrong; a second axis must land after this one, because every
// scenario shares the run's PRNG and a reordered draw shifts every later
// one at the same seed.
op := s.operations.Select(rng)
scenario.Operation = op

switch op {
case config.OpSwapAToB:
return s.contract.SwapAToB(auth, ammSwapAmount)
case config.OpSwapBToA:
return s.contract.SwapBToA(auth, ammSwapAmount)
default:
// A name added to the set with no call here would otherwise be stamped
// into the metric and sent as the other leg, so the dimension would say
// one thing while the chain saw another.
return nil, fmt.Errorf("amm: no call for operation %q", op)
}
}
Loading
Loading