Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

ratelimit source pure

Package ratelimit provides a token-bucket rate limiter for use inside gno.land realms. It holds no chain state itself...

Overview

Package ratelimit provides a token-bucket rate limiter for use inside gno.land realms. It holds no chain state itself -- the importing realm owns a *TokenBucket (typically as a struct field or inside an avl.Tree keyed by caller address) and passes in the current block height on every check, since a pure package can't call chain/runtime itself.

Functions 1

func NewTokenBucket

1func NewTokenBucket(capacity, refillPerBlock, nowBlock int64) *TokenBucket
source

NewTokenBucket creates a bucket starting full (Tokens == capacity). capacity and refillPerBlock must both be positive.

Types 1

type TokenBucket

struct
1type TokenBucket struct {
2	Capacity        int64
3	RefillPerBlock  int64
4	Tokens          int64
5	LastRefillBlock int64
6}
source

TokenBucket implements the classic token-bucket algorithm. Tokens refill linearly with block height and are capped at Capacity.

Methods on TokenBucket

func Allow

method on TokenBucket
1func (b *TokenBucket) Allow(nowBlock int64, cost int64) bool
source

Allow refills the bucket up to nowBlock, then attempts to spend cost tokens. Returns true and deducts cost if there were enough tokens, false (no deduction) otherwise.

func Peek

method on TokenBucket
1func (b *TokenBucket) Peek(nowBlock int64) int64
source

Peek refills the bucket up to nowBlock (mutating LastRefillBlock and Tokens, same as Allow would) and returns the resulting token count, without spending anything. Useful for a read-only "how many do I have right now" view function.

Imports 1

  • math/overflow stdlib

Source Files 2