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

v1 source realm

Package referral implements a referral system on Gno. It allows authorized contracts to register, update, or remove r...

Readme View source

Referral

Referral system for tracking user relationships.

Overview

Manages referral relationships between users. Non-removal writes have a 24-hour cooldown per user.

Global Functions

TryRegister(cur realm, addr address, referral string) string

Attempts to register, update, or remove a referral relationship and returns the effective referrer string.

  • An empty referral only reads and returns the user's current referrer. It does not require authorization or emit an event.
  • An authorized non-empty write that fails emits ReferralRegistrationFailed and returns the currently stored referrer.
  • Passing ContractAddress() as referral removes the relationship and returns an empty string. The zero address is not the removal sentinel and is invalid.

GetReferral(addr string) string

Returns the referral address for the given address. Returns empty string if not found.

HasReferral(addr string) bool

Returns true if the given address has a referral.

IsEmpty() bool

Returns true if no referrals exist in the system.

GetLastOpTimestamp(addr string) (int64, error)

Returns the last non-removal registration or update timestamp for the address. Returns ErrNotFound if no such operation has been recorded.

ContractAddress() string

Returns the address of the referral contract. Pass this value as referral to remove an existing relationship.

Gnoweb

Render("") explains the registration interval and removal behavior. Render("address/<address>") shows the current referrer and last registration or update time in UTC. Missing records and unsupported paths return 404.

Usage

Registering or Updating a Referral

 1package example
 2
 3import (
 4    "gno.land/r/gnoswap/referral/v1"
 5)
 6
 7// RegisterUserReferral registers or updates a referral relationship.
 8// The returned string is the effective referrer.
 9func RegisterUserReferral(cur realm, userAddr, referrerAddr address) string {
10    return referral.TryRegister(cross(cur), userAddr, referrerAddr.String())
11}

Removing a Referral

 1package example
 2
 3import (
 4    "gno.land/r/gnoswap/referral/v1"
 5)
 6
 7// RemoveUserReferral removes the referral relationship for a user.
 8func RemoveUserReferral(cur realm, userAddr address) string {
 9    return referral.TryRegister(cross(cur), userAddr, referral.ContractAddress())
10}

Querying Referrals

 1package example
 2
 3import (
 4    "gno.land/r/gnoswap/referral/v1"
 5)
 6
 7// GetUserReferrer returns the referrer address for a user.
 8// Returns empty string if no referral exists.
 9func GetUserReferrer(userAddr string) string {
10    return referral.GetReferral(userAddr)
11}
12
13// CheckUserHasReferral returns true if the user has a registered referral.
14func CheckUserHasReferral(userAddr string) bool {
15    return referral.HasReferral(userAddr)
16}

Rate Limiting

  • Non-removal registrations and updates are limited to one operation per 24 hours per address.
  • Passing the referral contract's own address removes a relationship and bypasses the rate-limit check.
  • Removal does not overwrite the previous non-removal timestamp, so immediate re-registration can still be rejected while that timestamp is within the cooldown.

Events

  • RegisterReferral is emitted for every successful non-empty write, including creation, update, and removal.
  • ReferralRegistrationFailed is emitted when an authorized non-empty write fails.
  • Empty referral queries do not emit events.

Security

  • One referral per address
  • Self-referrals are rejected
  • Non-empty writes require an authorized caller
  • The referral contract's own address is the removal sentinel; the zero address is invalid

Overview

Package referral implements a referral system on Gno. It allows authorized contracts to register, update, or remove referral relationships. A referral link is defined as a mapping from one address (the "user") to another address (the "referrer").

## Overview

The referral package is composed of the following components:

  1. **errors.gno**: Defines error types for invalid addresses, unauthorized callers, self-referrals, rate limits, and missing referrals.
  2. **assert.gno**: Checks whether a caller has an authorized role.
  3. **type.gno**: Defines the ReferralKeeper interface and the contract-address sentinel used to request removal.
  4. **keeper.gno**: Implements ReferralKeeper with BPTree storage. Non-removal registrations and updates have a 24-hour cooldown.
  5. **global_keeper.gno**: Exposes the public API and emits referral events.

## Public API

The package exposes the following public functions:

  • GetReferral(addr string) string: Returns the referrer address for the given user. Returns empty string if not found.
  • HasReferral(addr string) bool: Returns true if the user has a registered referrer.
  • IsEmpty() bool: Returns true if no referral relationships exist.
  • GetLastOpTimestamp(addr string) (int64, error): Returns the last non-removal registration or update timestamp for the user.
  • TryRegister(cur realm, addr address, referral string) string: Empty input reads the stored referral without authorization. A non-empty input registers, updates, or removes a relationship and returns the effective referrer string. Passing ContractAddress() requests removal.

## Workflow

Typical usage of this contract follows these steps:

  1. A caller uses TryRegister to resolve the effective referrer. Empty input only reads; non-empty input must come from an authorized role.
  2. The keeper validates the caller's permissions via assertValidCaller.
  3. Address validation ensures the user address is valid, the referral is valid for registration, and self-referrals are rejected. The contract's own address is the removal sentinel.
  4. The 24-hour rate limit is checked for non-removal registrations and updates. Removal bypasses this check.
  5. Successful non-removal writes store a new timestamp. Successful non-empty writes emit a RegisterReferral event.

## Authorized Callers

Only contracts with the following roles can modify referral data:

  • ROLE_GOVERNANCE: Governance contracts
  • ROLE_GOV_STAKER: Governance staker contracts
  • ROLE_ROUTER: Router contracts
  • ROLE_POSITION: Position manager contracts
  • ROLE_STAKER: Staker contracts
  • ROLE_LAUNCHPAD: Launchpad contracts

## Rate Limiting

To prevent abuse, the system enforces a 24-hour cooldown between non-removal registrations or updates for each address. This means:

  • A new referral can only be registered once per 24 hours per address.
  • Updates are also subject to the same rate limit.
  • Removal via the contract-address sentinel bypasses the rate-limit check.
  • Removal does not overwrite the previous timestamp, so immediate re-registration can still be rejected during the prior cooldown.
  • Attempts that exceed the cooldown return ErrTooManyRequests.

## Events

The package emits the following events:

  • RegisterReferral: Emitted for every successful non-empty write, including creation, update, and removal.
  • ReferralRegistrationFailed: Emitted when an authorized non-empty write fails.
  • Empty referral queries do not emit events.

## Error Handling

The package defines several error types:

  • `ErrInvalidAddress`: Returned when an address format is invalid
  • `ErrSelfReferral`: Returned when attempting to set self as referrer
  • `ErrUnauthorized`: Returned when the caller lacks permission
  • `ErrTooManyRequests`: Returned when rate limit is exceeded (24-hour cooldown)
  • `ErrNotFound`: Returned when attempting to get a non-existent referral
  • `ErrInvalidTime`: Returned when the stored timestamp format is invalid

## Example: Integration with Router Contract

The router contract can register referrals during swap operations:

```go

Example
 1import (
 2    "gno.land/r/gnoswap/referral/v1"
 3)
 4
 5func SwapWithReferral(cur realm, referralCode string, ...) {
 6    // Get the caller address
 7    caller := cur.Previous().Address()
 8
 9    actualReferrer := referral.TryRegister(cross(cur), caller, referralCode)
10
11    // Continue with swap logic...
12}

```

## Example: Checking Referral for Rewards

Other contracts can check referral relationships for reward distribution:

```go

Example
 1import (
 2    "gno.land/r/gnoswap/referral/v1"
 3)
 4
 5func DistributeRewards(user address, amount uint64) {
 6    // Check if user has a referrer
 7    if referral.HasReferral(user.String()) {
 8        referrerAddr := referral.GetReferral(user.String())
 9        // Calculate and distribute referral bonus
10        referrerBonus := amount * referralRate / 100
11        sendReward(address(referrerAddr), referrerBonus)
12    }
13}

```

## Limitations and Constraints

  • A user can have only one referrer at a time.
  • Self-referral is not allowed.
  • Non-removal registrations and updates are rate-limited to once per 24 hours per address.
  • Only callers with an authorized role can perform non-empty writes.
  • The referral contract's own address is the removal sentinel; the zero address is invalid.

## Notes

  • The contract uses RBAC (Role-Based Access Control) for authorization.
  • Rate-limit state persists across transactions.
  • The referral relationship is stored in a BPTree.

Constants 3

const EventRegisterFailed

1const EventRegisterFailed = "ReferralRegistrationFailed"
source

EventRegisterFailed is emitted when an authorized non-empty write fails. Successful non-empty writes emit the RegisterReferral event.

const MinTimeBetweenUpdates

1const (
2	// MinTimeBetweenUpdates is minimum duration between operations (24 hours).
3	MinTimeBetweenUpdates int64 = 24 * 60 * 60
4)
source

Functions 8

func ContractAddress

Action
1func ContractAddress() string
source

ContractAddress returns the address of the referral contract. Use this address as the referral parameter in TryRegister to remove an existing referral.

Returns:

  • address: referral contract address string, used as the removal sentinel.

func GetLastOpTimestamp

Action
1func GetLastOpTimestamp(addr string) (int64, error)
source

GetLastOpTimestamp returns the last non-removal registration or update timestamp for an address.

Parameters:

  • addr: address string whose last non-removal operation is queried.

Returns:

  • timestamp: Unix timestamp of the last successful registration or update.
  • error: nil when a timestamp exists; otherwise an invalid-address or ErrNotFound error.

func GetReferral

Action
1func GetReferral(addr string) string
source

GetReferral returns the referral address string stored for the given address.

Parameters:

  • addr: address string whose referral relationship is queried.

Returns:

  • referral: stored referrer address string, or an empty string when no valid referral is found.

func HasReferral

Action
1func HasReferral(addr string) bool
source

HasReferral reports whether the given address has a stored referral.

Parameters:

  • addr: address string whose referral relationship is checked.

Returns:

  • hasReferral: true when a referral record exists; false when it is absent or invalid.

func IsEmpty

Action
1func IsEmpty() bool
source

IsEmpty reports whether the referral keeper contains no referral records.

Returns:

  • empty: true when the keeper store has zero referral records.

func Render

1func Render(path string) string
source

Render describes referral registration or shows the referral for an address.

func TryRegister

crossing Action
1func TryRegister(cur realm, addr address, referral string) string
source

TryRegister attempts to register, update, or remove a referral.

Parameters:

  • cur: Current realm context; callers use cross(cur) when crossing into this realm.
  • addr: address whose referral relationship is read or changed.
  • referral: empty string for a read, ContractAddress() to remove, or a candidate referrer address string.

Returns:

  • effectiveReferral: stored referrer after the operation or fallback; empty when none is stored.

Empty input is treated as a read and returns the stored referrer without authorization, rate-limit checks, or event emission. Non-empty input requires an authorized caller.

func NewKeeper

Action
1func NewKeeper() ReferralKeeper
source

NewKeeper creates an empty ReferralKeeper backed by independent referral and last-operation BPTrees.

Returns:

  • keeper: new referral store with no relationships or operation timestamps

Types 1

type ReferralKeeper

interface
 1type ReferralKeeper interface {
 2	// register creates or updates a referral relationship between addresses.
 3	// Setting refAddr to the contract's own address removes the referral.
 4	register(addr, refAddr address) (address, error)
 5
 6	// has returns true if a referral exists for the given address.
 7	has(addr address) bool
 8
 9	// get retrieves the referral address for a given address.
10	get(addr address) (address, error)
11
12	// isEmpty returns true if no referrals exist in the system.
13	isEmpty() bool
14
15	// getLastOpTimestamp returns the last operation timestamp for an address.
16	getLastOpTimestamp(addr address) (int64, error)
17}
source

ReferralKeeper defines the interface for managing referral relationships.

Imports 11

Source Files 9