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

referral/v1 package

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.

Functions

ContractAddress

func ContractAddress() string

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.

Command

gnokey query vm/qeval -remote "http://127.0.0.1:26657" -data "gno.land/r/gnoswap/referral/v1.ContractAddress()"

Result

GetLastOpTimestamp

func GetLastOpTimestamp(addr string) (int64, error)

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.

Param

Command

gnokey query vm/qeval -remote "http://127.0.0.1:26657" -data "gno.land/r/gnoswap/referral/v1.GetLastOpTimestamp()"

Result

GetReferral

func GetReferral(addr string) string

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.

Param

Command

gnokey query vm/qeval -remote "http://127.0.0.1:26657" -data "gno.land/r/gnoswap/referral/v1.GetReferral()"

Result

HasReferral

func HasReferral(addr string) bool

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.

Param

Command

gnokey query vm/qeval -remote "http://127.0.0.1:26657" -data "gno.land/r/gnoswap/referral/v1.HasReferral()"

Result

IsEmpty

func IsEmpty() bool

IsEmpty reports whether the referral keeper contains no referral records.

Returns:

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

Command

gnokey query vm/qeval -remote "http://127.0.0.1:26657" -data "gno.land/r/gnoswap/referral/v1.IsEmpty()"

Result

Render

func Render(path string) string

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

Param

Command

gnokey query vm/qeval -remote "http://127.0.0.1:26657" -data "gno.land/r/gnoswap/referral/v1.Render()"

Result

TryRegister

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

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.

Params

Command

# WARNING: This command is running in an INSECURE mode.
# It is strongly recommended to use a hardware device for signing
# and avoid trusting any computer connected to the internet,
# as your private keys could be exposed.

gnokey maketx call -pkgpath "gno.land/r/gnoswap/referral/v1" -func "TryRegister" -args $'' -args $'' -gas-fee 1000000ugnot -gas-wanted 1_000_000_000 -send "" -chainid "gnoland-1" -remote "http://127.0.0.1:26657" ADDRESSgnokey query -remote "http://127.0.0.1:26657" auth/accounts/ADDRESS
gnokey maketx call -pkgpath "gno.land/r/gnoswap/referral/v1" -func "TryRegister" -args $'' -args $'' -gas-fee 1000000ugnot -gas-wanted 1_000_000_000 -send "" -broadcast=false ADDRESS > call.tx
gnokey sign -tx-path call.tx -chainid "gnoland-1" -account-number ACCOUNTNUMBER -account-sequence SEQUENCENUMBER ADDRESS
gnokey broadcast -remote "http://127.0.0.1:26657" call.tx
  

NewKeeper

func NewKeeper() ReferralKeeper

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

Returns:

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

Command

gnokey query vm/qeval -remote "http://127.0.0.1:26657" -data "gno.land/r/gnoswap/referral/v1.NewKeeper()"

Result