Playground
assert.gno
package launchpad
import (
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/launchpad"
)
// assertIsDepositOwner asserts that the caller is the owner of the deposit.
// Panics if the caller is not the owner of the deposit.
func (lp *launchpadV1) assertIsDepositOwner(depositID string, caller address) {
deposit, err := lp.getDeposit(depositID)
if err != nil {
panic(err.Error())
}
if !deposit.IsDepositor(caller) {
panic(makeErrorWithDetails(errInvalidOwner, ufmt.Sprintf("(%s)", caller.String())).Error())
}
}
// assertIsValidAmount panics if the amount is zero.
func assertIsValidAmount(amount int64) {
if amount < minimumDepositAmount {
panic(makeErrorWithDetails(
errInvalidAmount,
ufmt.Sprintf("amount(%d) should greater than minimum deposit amount(%d)", amount, minimumDepositAmount),
))
}
if (amount % minimumDepositAmount) != 0 {
panic(makeErrorWithDetails(
errInvalidAmount,
ufmt.Sprintf("amount(%d) must be a multiple of 1_000_000", amount),
))
}
}
// assertIsDepositNotWithdrawn asserts that the deposit is not withdrawn.
func assertIsDepositNotWithdrawn(deposit launchpad.Deposit) {
if deposit.IsWithdrawn() {
panic(makeErrorWithDetails(errAlreadyCollected, ufmt.Sprintf("(%s)", deposit.ID())))
}
}
// assertIsDepositEnded asserts that the deposit is ended.
func assertIsDepositEnded(deposit launchpad.Deposit, currentTime int64) {
if !deposit.IsEnded(currentTime) {
panic(makeErrorWithDetails(errNotYetEndedProject, ufmt.Sprintf("(%s)", deposit.ID())))
}
}
// assertHasTierReward asserts that the tier has rewards to distribute.
// A zero-rate tier cannot settle rewards, which would lock withdrawals.
func assertHasTierReward(tier *launchpad.ProjectTier) {
if tier.DistributeAmountPerSecondX128().IsZero() {
panic(makeErrorWithDetails(errNoLeftReward, ufmt.Sprintf("(%s)", tier.ID())))
}
}
// assertHasProject asserts that the caller is the owner of at least one project.
// Panics if the caller is not the owner of any project.
func (lp *launchpadV1) assertHasProject(caller address) {
if !lp.store.GetProjectRecipients().Has(caller.String()) {
panic(makeErrorWithDetails(
errInvalidOwner,
ufmt.Sprintf("caller %s is not the owner of any project", caller.String()),
))
}
}
func assertNotImplementYet() {
panic("NotImplementYet")
}
consts.gno
package launchpad
const (
projectTier30 = int64(30)
projectTier90 = int64(90)
projectTier180 = int64(180)
dayTime = int64(24 * 60 * 60) // 86400
minimumDepositAmount = int64(1_000_000)
stringSplitterPad = "*PAD*"
maxProjectConditionCount = 5
projectMinimumStartDelayTime = dayTime * 3 // 3 days
)
// contract paths
const (
GOV_XGNS_PATH string = "gno.land/r/gnoswap/gov/xgns"
GNS_TOKEN_KEY string = "gno.land/r/gnoswap/gns.GNS"
)
// MUST BE IMMUTABLE, DO NOT MODIFY.
var projectTierDurations = []int64{
projectTier30,
projectTier90,
projectTier180,
}
// MUST BE IMMUTABLE, DO NOT MODIFY.
var projectTierDurationTimes = map[int64]int64{
projectTier30: dayTime * projectTier30, // 30 days
projectTier90: dayTime * projectTier90, // 90 days
projectTier180: dayTime * projectTier180, // 180 days
}
// MUST BE IMMUTABLE, DO NOT MODIFY.
var projectTierRewardCollectableDuration = map[int64]int64{
projectTier30: dayTime * 1, // 1 days
projectTier90: dayTime * 1, // 1 days
projectTier180: dayTime * 1, // 1 days
}
deposit.gno
package launchpad
import "gno.land/r/gnoswap/launchpad"
func withdrawDeposit(d launchpad.Deposit, currentHeight, currentTime int64) (launchpad.Deposit, int64) {
d.SetWithdrawn(currentHeight, currentTime)
previousDepositAmount := d.DepositAmount()
d.SetDepositAmount(0)
return d, previousDepositAmount
}
emits.gno
package launchpad
import (
"chain"
"gno.land/p/gnoswap/utils/v1"
"gno.land/r/gnoswap/launchpad"
)
// emitUpdateLaunchpadRewardAccumulation emits the persisted per-tier reward
// accumulation state so that off-chain indexers can consume the authoritative
// accumulator instead of re-deriving it. It must be emitted after every path that
// calls updateRewardPerDepositX128 (deposit/withdraw/collect/admin-reclaim),
// otherwise the off-chain accumulator drifts from the contract.
//
// The reward manager is keyed by projectTierId, so it is included to identify which
// tier's accumulator this update belongs to. totalDepositAmount is the current tier
// deposit total after the stake change (the divisor for the next accumulation delta),
// and distributeAmountPerSecondX128 lets indexers project the accumulator forward.
func emitUpdateLaunchpadRewardAccumulation(projectTierID string, r *launchpad.RewardManager, totalDepositAmount int64) {
chain.Emit(
"UpdateLaunchpadRewardAccumulation",
"projectTierId", projectTierID,
"totalDepositAmount", utils.FormatInt(totalDepositAmount),
"accumulatedRewardPerDepositX128", r.AccumulatedRewardPerDepositX128().ToString(),
"distributeAmountPerSecondX128", r.DistributeAmountPerSecondX128().ToString(),
"accumulatedTime", utils.FormatInt(r.AccumulatedTime()),
)
}
errors.gno
package launchpad
import (
ufmt "gno.land/p/nt/ufmt/v0"
)
const (
errNoLeftReward = "[GNOSWAP-LAUNCHPAD-001] no left reward"
errInvalidAddress = "[GNOSWAP-LAUNCHPAD-002] invalid address"
errDataNotFound = "[GNOSWAP-LAUNCHPAD-003] requested data not found"
errInactiveProject = "[GNOSWAP-LAUNCHPAD-004] project is inactive"
errInvalidInput = "[GNOSWAP-LAUNCHPAD-005] invalid input data"
errDuplicateProject = "[GNOSWAP-LAUNCHPAD-006] cannot create same project in same block"
errInvalidTier = "[GNOSWAP-LAUNCHPAD-007] invalid tier"
errInsufficientBalance = "[GNOSWAP-LAUNCHPAD-008] insufficient balance"
errInvalidData = "[GNOSWAP-LAUNCHPAD-009] invalid data"
errInvalidAmount = "[GNOSWAP-LAUNCHPAD-010] invalid amount"
errInvalidRewardState = "[GNOSWAP-LAUNCHPAD-011] invalid reward state"
errNotExistDeposit = "[GNOSWAP-LAUNCHPAD-012] not exist deposit"
errAlreadyCollected = "[GNOSWAP-LAUNCHPAD-013] already collected"
errInvalidOwner = "[GNOSWAP-LAUNCHPAD-014] invalid owner"
errInvalidTime = "[GNOSWAP-LAUNCHPAD-015] invalid time"
errNotYetEndedProject = "[GNOSWAP-LAUNCHPAD-016] project lock period is not over yet"
errOverflow = "[GNOSWAP-LAUNCHPAD-017] overflow"
errSpoofedRealm = "[GNOSWAP-LAUNCHPAD-018] rlm does not match the current crossing frame"
)
// makeErrorWithDetails creates an error with additional context.
func makeErrorWithDetails(message string, details string) error {
return ufmt.Errorf("%s || %s", message, details)
}
getter.gno
package launchpad
import (
"errors"
"time"
rotree "gno.land/p/nt/bptree/rotree/v0"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/p/gnoswap/uint256/v1"
"gno.land/r/gnoswap/launchpad"
)
// GetProjects returns a read-only view of every project, keyed by project ID.
//
// Returns:
// - projects: read-only tree keyed by project ID; project entries are cloned before being exposed.
func (lp *launchpadV1) GetProjects() *rotree.ReadOnlyTree {
return rotree.Wrap(lp.store.GetProjects(), cloneProjectEntry)
}
// GetProjectName returns the name of a project by its ID.
// Returns empty string and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - name: configured project name; empty when the project is absent.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectName(projectId string) (string, error) {
project, err := lp.getProject(projectId)
if err != nil {
return "", err
}
return project.Name(), nil
}
// GetProjectTokenPath returns the token path of a project by its ID.
// Returns empty string and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - tokenPath: reward-token contract path configured for the project; empty when absent.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectTokenPath(projectId string) (string, error) {
project, err := lp.getProject(projectId)
if err != nil {
return "", err
}
return project.TokenPath(), nil
}
// GetProjectDepositAmount returns the deposit amount of a project by its ID.
// Returns 0 and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - amount: project-level token amount deposited for distribution; zero when absent.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectDepositAmount(projectId string) (int64, error) {
project, err := lp.getProject(projectId)
if err != nil {
return 0, err
}
return project.DepositAmount(), nil
}
// GetProjectRecipient returns the recipient address of a project by its ID.
// Returns empty address and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - recipient: address configured to receive the project's tokens; empty address when absent.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectRecipient(projectId string) (address, error) {
project, err := lp.getProject(projectId)
if err != nil {
return address(""), err
}
return project.Recipient(), nil
}
// GetProjectCondition retrieves a specific condition of a project.
// Returns nil and error if project or condition not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tokenPath: condition-token contract path used as the project's condition key.
//
// Returns:
// - condition: matching project condition; nil when the project or condition is absent.
// - err: nil when found; non-nil when projectId or tokenPath is not present.
func (lp *launchpadV1) GetProjectCondition(projectId string, tokenPath string) (*launchpad.ProjectCondition, error) {
project, err := lp.getProject(projectId)
if err != nil {
return nil, err
}
conditions := project.Conditions()
condition, exists := conditions[tokenPath]
if !exists {
return nil, makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("condition(%s) not found", tokenPath))
}
return condition, nil
}
// GetProjectTiersRatios returns the tiers ratios map of a project by its ID.
// Returns nil and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - ratios: map from tier duration (30, 90, or 180) to its allocation percentage; nil when the project is absent.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectTiersRatios(projectId string) (map[int64]int64, error) {
project, err := lp.getProject(projectId)
if err != nil {
return nil, err
}
return project.TiersRatios(), nil
}
// GetProjectCreatedHeight returns the created height of a project by its ID.
// Returns 0 and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - height: project creation block height; zero when the project is absent.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectCreatedHeight(projectId string) (int64, error) {
project, err := lp.getProject(projectId)
if err != nil {
return 0, err
}
return project.CreatedHeight(), nil
}
// GetProjectCreatedAt returns the created time of a project by its ID.
// Returns 0 and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - createdAt: project creation timestamp in Unix seconds; zero when the project is absent.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectCreatedAt(projectId string) (int64, error) {
project, err := lp.getProject(projectId)
if err != nil {
return 0, err
}
return project.CreatedAt(), nil
}
// GetProjectTier retrieves a specific tier of a project.
// Returns nil and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - projectTier: matching project tier; nil when the project or tier is absent.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTier(projectId string, tier int64) (*launchpad.ProjectTier, error) {
project, err := lp.getProject(projectId)
if err != nil {
return nil, err
}
projectTier, err := getProjectTier(project, tier)
if err != nil {
return nil, err
}
return projectTier, nil
}
// GetProjectTierDistributeAmountPerSecondX128 returns the distribute amount per second (Q128) of a project tier.
// Returns nil and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - amountPerSecondX128: per-second distribution rate encoded as a Q128 fixed-point value; nil when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierDistributeAmountPerSecondX128(projectId string, tier int64) (*uint256.Uint, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return nil, err
}
return projectTier.DistributeAmountPerSecondX128(), nil
}
// GetProjectTierTotalDistributeAmount returns the total distribute amount of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - amount: total token amount allocated for distribution by the tier; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierTotalDistributeAmount(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.TotalDistributeAmount(), nil
}
// GetProjectTierTotalDepositAmount returns the total deposit amount of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - amount: aggregate token amount deposited into the tier; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierTotalDepositAmount(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.TotalDepositAmount(), nil
}
// GetProjectTierTotalWithdrawAmount returns the total withdraw amount of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - amount: aggregate token amount withdrawn from the tier; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierTotalWithdrawAmount(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.TotalWithdrawAmount(), nil
}
// GetProjectTierTotalDepositCount returns the total deposit count of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - count: number of deposits recorded for the tier; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierTotalDepositCount(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.TotalDepositCount(), nil
}
// GetProjectTierTotalWithdrawCount returns the total withdraw count of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - count: number of withdrawals recorded for the tier; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierTotalWithdrawCount(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.TotalWithdrawCount(), nil
}
// GetProjectTierTotalCollectedAmount returns the total collected amount of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - amount: aggregate reward amount collected from the tier; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierTotalCollectedAmount(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.TotalCollectedAmount(), nil
}
// GetProjectTierStartTime returns the start time of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - startTime: tier start timestamp in Unix seconds; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierStartTime(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.StartTime(), nil
}
// GetProjectTierEndTime returns the end time of a project tier.
// Returns 0 and error if project or tier not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - endTime: tier end timestamp in Unix seconds; zero when lookup fails.
// - err: nil when found; non-nil when projectId or tier is not present.
func (lp *launchpadV1) GetProjectTierEndTime(projectId string, tier int64) (int64, error) {
projectTier, err := lp.GetProjectTier(projectId, tier)
if err != nil {
return 0, err
}
return projectTier.EndTime(), nil
}
// GetDepositCount returns the total number of deposits.
//
// Returns:
// - count: number of deposit entries currently stored.
func (lp *launchpadV1) GetDepositCount() int {
deposits := lp.store.GetDeposits()
return deposits.Size()
}
// GetCurrentDepositId returns the current deposit counter value.
//
// Returns:
// - depositID: current int64 deposit counter used to generate subsequent deposit identifiers.
func (lp *launchpadV1) GetCurrentDepositId() int64 {
counter := lp.store.GetDepositCounter()
return counter.Get()
}
// GetProjectTierRewards returns a read-only view of a project tier's reward
// states, keyed by deposit ID. nil is returned when the project tier does not
// exist.
//
// Parameters:
// - projectId: unique launchpad project identifier used to form the tier ID.
// - tier: tier duration in days; launchpad tiers use 30, 90, or 180.
//
// Returns:
// - rewards: read-only tree of reward states keyed by deposit ID; nil when the tier's reward manager lookup fails.
func (lp *launchpadV1) GetProjectTierRewards(projectId string, tier int64) *rotree.ReadOnlyTree {
projectTierID := launchpad.MakeProjectTierID(projectId, tier)
rewardManager, err := lp.getProjectTierRewardManager(projectTierID)
if err != nil {
return nil
}
return rotree.Wrap(rewardManager.Rewards(), cloneRewardStateEntry)
}
// GetDeposit retrieves the value payload of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - deposit: stored deposit value; zero-valued when the entry is missing or has an invalid type.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDeposit(depositId string) (launchpad.Deposit, error) {
return lp.getDepositValue(depositId)
}
// GetDepositProjectID returns the project ID of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - projectID: project identifier recorded on the deposit; empty when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositProjectID(depositId string) (string, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return "", err
}
return deposit.ProjectID(), nil
}
// GetDepositTier returns the tier of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - tier: tier duration recorded on the deposit; zero when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositTier(depositId string) (int64, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return 0, err
}
return deposit.Tier(), nil
}
// GetDepositProjectTierID returns the project tier ID of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - projectTierID: composite project-tier identifier derived from the deposit; empty when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositProjectTierID(depositId string) (string, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return "", err
}
return deposit.ProjectTierID(), nil
}
// GetDepositAmount returns the deposit amount of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - amount: GNS amount recorded on the deposit; zero when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositAmount(depositId string) (int64, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return 0, err
}
return deposit.DepositAmount(), nil
}
// GetDepositWithdrawnHeight returns the withdrawn height of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - withdrawnHeight: withdrawal block height recorded on the deposit; zero when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositWithdrawnHeight(depositId string) (int64, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return 0, err
}
return deposit.WithdrawnHeight(), nil
}
// GetDepositWithdrawnTime returns the withdrawn time of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - withdrawnTime: withdrawal timestamp in Unix seconds; zero when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositWithdrawnTime(depositId string) (int64, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return 0, err
}
return deposit.WithdrawnTime(), nil
}
// GetDepositCreatedHeight returns the created height of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - createdHeight: creation block height recorded on the deposit; zero when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositCreatedHeight(depositId string) (int64, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return 0, err
}
return deposit.CreatedHeight(), nil
}
// GetDepositCreatedAt returns the created time of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - createdAt: creation timestamp in Unix seconds; zero when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositCreatedAt(depositId string) (int64, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return 0, err
}
return deposit.CreatedAt(), nil
}
// GetDepositEndTime returns the end time of a deposit by its ID.
//
// Parameters:
// - depositId: unique deposit identifier to look up.
//
// Returns:
// - endTime: tier end timestamp in Unix seconds; zero when the entry is missing or invalid.
// - err: nil for a valid stored deposit; non-nil when the entry is missing or has an invalid type.
func (lp *launchpadV1) GetDepositEndTime(depositId string) (int64, error) {
deposit, err := lp.getDepositValue(depositId)
if err != nil {
return 0, err
}
return deposit.EndTime(), nil
}
// GetTotalGNSStakedAmount returns the total amount of GNS currently staked across all launchpad deposits.
//
// Returns:
// - amount: aggregate GNS amount currently staked across all launchpad deposits.
func (lp *launchpadV1) GetTotalGNSStakedAmount() int64 {
return lp.store.GetTotalGNSStakedAmount()
}
// GetProjectTierRewardManagerCount returns the total number of reward managers.
//
// Returns:
// - count: number of project-tier reward-manager entries currently stored.
func (lp *launchpadV1) GetProjectTierRewardManagerCount() int {
managers := lp.store.GetProjectTierRewardManagers()
return managers.Size()
}
// GetProjectTierRewardManager retrieves a reward manager by project tier ID.
// Returns nil and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - manager: matching reward manager; nil when no entry exists or its value has an invalid type.
// - err: nil for a valid manager; non-nil when the entry is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardManager(projectTierId string) (*launchpad.RewardManager, error) {
managers := lp.store.GetProjectTierRewardManagers()
value := managers.Get(projectTierId)
if value == nil {
return nil, makeErrorWithDetails(errDataNotFound, "reward manager not found")
}
manager, ok := value.(*launchpad.RewardManager)
if !ok {
return nil, errors.New("invalid reward manager type")
}
return manager, nil
}
// GetProjectTierRewardDistributeAmountPerSecondX128 returns the distribute amount per second (Q128) of a reward manager.
// Returns nil and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - amountPerSecondX128: per-second distribution rate encoded as a Q128 fixed-point value; nil when lookup fails.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardDistributeAmountPerSecondX128(projectTierId string) (*uint256.Uint, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return nil, err
}
return manager.DistributeAmountPerSecondX128(), nil
}
// GetProjectTierRewardAccumulatedRewardPerDepositX128 returns the accumulated reward per deposit (Q128) of a reward manager.
// Returns nil and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - accumulatedRewardPerDepositX128: accumulated reward index per deposited GNS, encoded as Q128; nil when lookup fails.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardAccumulatedRewardPerDepositX128(projectTierId string) (*uint256.Uint, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return nil, err
}
return manager.AccumulatedRewardPerDepositX128(), nil
}
// GetProjectTierRewardTotalDistributeAmount returns the total distribute amount of a reward manager.
// Returns 0 and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - amount: total token amount allocated to the reward manager; zero when lookup fails.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardTotalDistributeAmount(projectTierId string) (int64, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return 0, err
}
return manager.TotalDistributeAmount(), nil
}
// GetProjectTierRewardTotalClaimedAmount returns the total claimed amount of a reward manager.
// Returns 0 and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - amount: total token amount already claimed from the reward manager; zero when lookup fails.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardTotalClaimedAmount(projectTierId string) (int64, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return 0, err
}
return manager.TotalClaimedAmount(), nil
}
// GetProjectTierRewardDistributeStartTime returns the distribute start time of a reward manager.
// Returns 0 and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - startTime: reward distribution start timestamp in Unix seconds; zero when lookup fails.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardDistributeStartTime(projectTierId string) (int64, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return 0, err
}
return manager.DistributeStartTime(), nil
}
// GetProjectTierRewardDistributeEndTime returns the distribute end time of a reward manager.
// Returns 0 and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - endTime: reward distribution end timestamp in Unix seconds; zero when lookup fails.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardDistributeEndTime(projectTierId string) (int64, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return 0, err
}
return manager.DistributeEndTime(), nil
}
// GetProjectTierRewardAccumulatedDistributeAmount returns a legacy reward-manager field.
// The v1 reward paths do not maintain it, so normal reads return zero unless it
// was explicitly set.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - amount: legacy accumulated-distribution amount, normally zero in v1 unless explicitly set.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardAccumulatedDistributeAmount(projectTierId string) (int64, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return 0, err
}
return manager.AccumulatedDistributeAmount(), nil
}
// GetProjectTierRewardAccumulatedTime returns the accumulated time of a reward manager.
// Returns 0 and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - accumulatedTime: timestamp in Unix seconds at which reward accumulation was last updated; zero before an update.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardAccumulatedTime(projectTierId string) (int64, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return 0, err
}
return manager.AccumulatedTime(), nil
}
// GetProjectTierRewardClaimableDuration returns the reward claimable duration of a reward manager.
// Returns 0 and error if reward manager not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager is requested.
//
// Returns:
// - duration: configured period during which rewards remain claimable, in the manager's timestamp units; zero when lookup fails.
// - err: nil when found; non-nil when the reward manager is absent or has an invalid type.
func (lp *launchpadV1) GetProjectTierRewardClaimableDuration(projectTierId string) (int64, error) {
manager, err := lp.GetProjectTierRewardManager(projectTierId)
if err != nil {
return 0, err
}
return manager.RewardClaimableDuration(), nil
}
// GetRewardState retrieves a reward state by project tier ID and deposit ID.
// Returns nil and error if reward manager or reward state not found.
//
// Parameters:
// - projectTierId: composite project-tier identifier whose reward manager contains the state.
// - depositId: unique deposit identifier whose reward state is requested.
//
// Returns:
// - rewardState: matching reward state; nil when the manager or state is absent or has an invalid type.
// - err: nil when found; non-nil when the manager or state is absent or has an invalid type.
func (lp *launchpadV1) GetRewardState(projectTierId string, depositId string) (*launchpad.RewardState, error) {
managers := lp.store.GetProjectTierRewardManagers()
value := managers.Get(projectTierId)
if value == nil {
return nil, makeErrorWithDetails(errDataNotFound, "reward manager not found")
}
manager, ok := value.(*launchpad.RewardManager)
if !ok {
return nil, errors.New("invalid reward manager type")
}
rewards := manager.Rewards()
rewardValue := rewards.Get(depositId)
if rewardValue == nil {
return nil, makeErrorWithDetails(errDataNotFound, "reward state not found")
}
rewardState, ok := rewardValue.(*launchpad.RewardState)
if !ok {
return nil, errors.New("invalid reward state type")
}
return rewardState, nil
}
// GetProjectActiveStatus returns whether a project is currently active.
// Returns false and error if project not found.
//
// Parameters:
// - projectId: unique launchpad project identifier to look up.
//
// Returns:
// - active: true when the project's standard 180-day tier is active at the current Unix time; false when inactive.
// - err: nil when found; non-nil when projectId is not present in state.
func (lp *launchpadV1) GetProjectActiveStatus(projectId string) (bool, error) {
project, err := lp.getProject(projectId)
if err != nil {
return false, err
}
currentTime := time.Now().Unix()
return isProjectActive(project, currentTime), nil
}
getter_utils.gno
package launchpad
import (
"gno.land/r/gnoswap/launchpad"
)
// The functions below are makeEntrySafeFn transformations handed to
// rotree.Wrap. They run on every read through a read-only view, so each one
// returns a value the caller may hold without reaching realm-owned state.
// cloneProjectEntry is the transformation for the project tree. Project is
// mutable and its setters are declared in /r/gnoswap/launchpad, so an external
// holder of the stored pointer could write realm state through it.
//
// Project.Clone leaves the project's maps nil; see it for which lookups read
// them instead.
func cloneProjectEntry(value any) any {
project, ok := value.(*launchpad.Project)
if !ok {
return nil
}
return project.Clone()
}
// cloneRewardStateEntry is the transformation for a project tier's reward
// tree. RewardState is mutable and its setters are declared in
// /r/gnoswap/launchpad, so an external holder of the stored pointer could
// write realm state through it.
func cloneRewardStateEntry(value any) any {
rewardState, ok := value.(*launchpad.RewardState)
if !ok {
return nil
}
return rewardState.Clone()
}
gnomod.toml
module = "gno.land/r/gnoswap/launchpad/v2" gno = "0.9" [addpkg] creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04" height = 1108523 max_deposit = "100000000ugnot"
init.gno
package launchpad
import "gno.land/r/gnoswap/launchpad"
func init(cur realm) {
registerLaunchpadV1(cur)
}
func registerLaunchpadV1(cur realm) {
launchpad.RegisterInitializer(cross(cur), func(_ int, rlm realm, launchpadStore launchpad.ILaunchpadStore) launchpad.ILaunchpad {
err := initStoreData(0, rlm, launchpadStore)
if err != nil {
panic(err)
}
return NewLaunchpadV1(launchpadStore)
})
}
func initStoreData(_ int, rlm realm, launchpadStore launchpad.ILaunchpadStore) error {
if !launchpadStore.HasProjectsKey() {
err := launchpadStore.SetProjects(0, rlm, launchpad.NewBPTreeN(16))
if err != nil {
return err
}
}
if !launchpadStore.HasProjectRecipientsKey() {
err := launchpadStore.SetProjectRecipients(0, rlm, launchpad.NewBPTreeN(16))
if err != nil {
return err
}
}
if !launchpadStore.HasProjectTierRewardManagersKey() {
err := launchpadStore.SetProjectTierRewardManagers(0, rlm, launchpad.NewBPTreeN(16))
if err != nil {
return err
}
}
if !launchpadStore.HasDepositCounterStoreKey() {
err := launchpadStore.SetDepositCounter(0, rlm, launchpad.NewCounter())
if err != nil {
return err
}
}
if !launchpadStore.HasDepositsKey() {
err := launchpadStore.SetDeposits(0, rlm, launchpad.NewBPTreeN(16))
if err != nil {
return err
}
}
if !launchpadStore.HasTotalGNSStakedAmountKey() {
err := launchpadStore.SetTotalGNSStakedAmount(0, rlm, 0)
if err != nil {
return err
}
}
return nil
}
instance.gno
package launchpad
import (
"gno.land/r/gnoswap/launchpad"
)
type launchpadV1 struct {
store launchpad.ILaunchpadStore
}
// NewLaunchpadV1 constructs a version-one launchpad implementation backed by launchpadStore.
//
// Parameters:
// - launchpadStore: store implementation used for all launchpad state reads and writes.
//
// Returns:
// - launchpad: launchpad implementation that delegates persistence to launchpadStore.
func NewLaunchpadV1(launchpadStore launchpad.ILaunchpadStore) launchpad.ILaunchpad {
return &launchpadV1{
store: launchpadStore,
}
}
launchpad_deposit.gno
package launchpad
import (
"chain"
"chain/runtime"
"time"
"gno.land/r/gnoswap/access/v1"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
"gno.land/p/gnoswap/utils/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/emission"
"gno.land/r/gnoswap/gns"
gov_staker "gno.land/r/gnoswap/gov/staker"
"gno.land/r/gnoswap/gov/xgns"
"gno.land/r/gnoswap/halt/v1"
"gno.land/r/gnoswap/launchpad"
"gno.land/r/gnoswap/referral/v1"
)
// DepositGns deposits GNS tokens to a launchpad project tier.
//
// Parameters:
// - _: leading integer discriminator for the forwarded realm call; callers pass 0.
// - rlm: propagated realm context; the implementation validates it is the current realm.
// - targetProjectTierID: project-tier identifier in `{projectID}:{tierDuration}` form.
// - depositAmount: amount of GNS to deposit into the tier.
// - referrer: optional referral address associated with the deposit.
//
// Returns:
// - depositID: identifier assigned to the newly created deposit.
func (lp *launchpadV1) DepositGns(_ int, rlm realm, targetProjectTierID string, depositAmount int64, referrer string) string {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedLaunchpad()
previousRealm := rlm.Previous()
assertIsValidAmount(depositAmount)
emission.MintAndDistributeGns(cross(rlm))
projectID, tierDuration := parseProjectTierID(targetProjectTierID)
caller := previousRealm.Address()
project, err := lp.getProject(projectID)
if err != nil {
panic(err.Error())
}
beforeTotalGNSStakedAmount := lp.store.GetTotalGNSStakedAmount()
deposit, rewardState, isFirstDeposit, distributeAmountPerSecondX128, err := lp.depositGns(
0,
rlm,
project,
tierDuration,
depositAmount,
caller,
)
if err != nil {
panic(err.Error())
}
afterTotalGNSStakedAmount := gnsmath.SafeAddInt64(beforeTotalGNSStakedAmount, depositAmount)
if err := lp.store.SetTotalGNSStakedAmount(0, rlm, afterTotalGNSStakedAmount); err != nil {
panic(err.Error())
}
actualReferrer := referral.TryRegister(cross(rlm), caller, referrer)
if isFirstDeposit {
chain.Emit(
"FirstDepositForProjectTier",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"targetProjectTierId", targetProjectTierID,
"amount", utils.FormatInt(depositAmount),
"depositId", deposit.ID(),
"claimableTime", utils.FormatInt(rewardState.ClaimableTime()),
"tierAmountPerSecondX128", distributeAmountPerSecondX128,
"totalGNSStakedAmount", utils.FormatInt(afterTotalGNSStakedAmount),
"recipient", project.Recipient().String(),
)
}
chain.Emit(
"DepositGns",
"prevAddr", previousRealm.Address().String(),
"prevRealm", previousRealm.PkgPath(),
"targetProjectTierId", targetProjectTierID,
"amount", utils.FormatInt(depositAmount),
"depositId", deposit.ID(),
"claimableTime", utils.FormatInt(rewardState.ClaimableTime()),
"referrer", actualReferrer,
"totalGNSStakedAmount", utils.FormatInt(afterTotalGNSStakedAmount),
"recipient", project.Recipient().String(),
)
launchpadAddress := rlm.Address()
// stake governance token to the project
err = lp.stakeGovernance(0, rlm, project.Recipient(), depositAmount, launchpadAddress, caller)
if err != nil {
panic(err.Error())
}
return deposit.ID()
}
// depositGns deposits GNS to a project tier.
func (lp *launchpadV1) depositGns(
_ int,
rlm realm,
project *launchpad.Project,
tierDuration int64,
depositAmount int64,
callerAddress address,
) (launchpad.Deposit, *launchpad.RewardState, bool, string, error) {
balanceOfFn := func(tokenPath string, caller address) int64 {
if tokenPath == GOV_XGNS_PATH {
return xgns.BalanceOf(caller)
}
return common.BalanceOf(tokenPath, caller)
}
err := checkProjectConditions(project, callerAddress, balanceOfFn)
if err != nil {
return launchpad.DefaultDeposit(), nil, false, "", err
}
projectTier, err := getProjectTier(project, tierDuration)
if err != nil {
return launchpad.DefaultDeposit(), nil, false, "", err
}
currentTime := time.Now().Unix()
currentHeight := runtime.ChainHeight()
if !isTierDepositable(projectTier, currentTime) {
return launchpad.DefaultDeposit(), nil, false, "", makeErrorWithDetails(errInactiveProject, project.ID())
}
assertHasTierReward(projectTier)
depositID := lp.nextDepositID()
deposit := launchpad.MakeDeposit(
depositID,
project.ID(),
tierDuration,
callerAddress,
depositAmount,
currentHeight,
currentTime,
projectTier.EndTime(),
)
// Store a value in the deposits tree and persist later updates explicitly.
deposits := lp.store.GetDeposits()
deposits.Set(depositID, deposit)
rewardManager, err := lp.getProjectTierRewardManager(projectTier.ID())
if err != nil {
return launchpad.DefaultDeposit(), nil, false, "", err
}
isFirstDeposit := !isRewardManagerInitialized(rewardManager)
// update rewards before adding deposit to reward manager
err = updateRewardPerDepositX128(rewardManager, getTierCurrentDepositAmount(projectTier), currentTime)
if err != nil {
return launchpad.DefaultDeposit(), nil, false, "", err
}
// add reward state to reward manager
rewardState := addRewardStateByDeposit(rewardManager, deposit)
// update tier data after adding reward state to reward manager
depositToTier(projectTier, deposit)
project.SetTier(tierDuration, projectTier)
// Save the modified state back
if err := lp.store.SetDeposits(0, rlm, deposits); err != nil {
return launchpad.DefaultDeposit(), nil, false, "", err
}
emitUpdateLaunchpadRewardAccumulation(projectTier.ID(), rewardManager, getTierCurrentDepositAmount(projectTier))
return deposit,
rewardState,
isFirstDeposit,
rewardManager.DistributeAmountPerSecondX128().ToString(),
nil
}
// stakeGovernance stakes governance token to the project.
func (lp *launchpadV1) stakeGovernance(_ int, rlm realm, recipient address, depositAmount int64, launchpadAddress address, callerAddress address) error {
gov_staker.SetAmountByProjectWallet(cross(rlm), recipient, depositAmount, true)
gns.TransferFrom(
cross(rlm),
callerAddress,
launchpadAddress,
depositAmount,
)
return nil
}
launchpad_project.gno
package launchpad
import (
"chain"
"chain/runtime"
"errors"
"strconv"
"strings"
"time"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
"gno.land/p/gnoswap/utils/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/emission"
"gno.land/r/gnoswap/halt/v1"
"gno.land/r/gnoswap/launchpad"
)
// CreateProject creates a new launchpad project with tiered allocations.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the launchpad proxy.
// - name: project name, limited by the project validation rules.
// - tokenPath: reward token contract path whose balance is deposited into the project.
// - recipient: project recipient address recorded for authorization and later collection.
// - depositAmount: amount of reward tokens to deposit into the project.
// - conditionTokens: `*PAD*`-separated token paths for eligibility conditions.
// - conditionAmounts: `*PAD*`-separated minimum balances aligned with conditionTokens.
// - tier30Ratio: percentage of the allocation assigned to the 30-day tier.
// - tier90Ratio: percentage of the allocation assigned to the 90-day tier.
// - tier180Ratio: percentage of the allocation assigned to the 180-day tier.
// - startTime: project start timestamp in Unix seconds, subject to the minimum delay.
//
// Returns:
// - projectID: newly created launchpad project identifier.
//
// Only callable by admin or governance.
func (lp *launchpadV1) CreateProject(
_ int,
rlm realm,
name string,
tokenPath string,
recipient address,
depositAmount int64,
conditionTokens string,
conditionAmounts string,
tier30Ratio int64,
tier90Ratio int64,
tier180Ratio int64,
startTime int64,
) string {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedLaunchpad()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
access.AssertIsAdminOrGovernance(caller)
launchpadAddr := rlm.Address()
currentHeight := runtime.ChainHeight()
currentTime := time.Now().Unix()
params := &createProjectParams{
name: name,
tokenPath: tokenPath,
recipient: recipient,
depositAmount: depositAmount,
conditionTokens: conditionTokens,
conditionAmounts: conditionAmounts,
tier30Ratio: tier30Ratio,
tier90Ratio: tier90Ratio,
tier180Ratio: tier180Ratio,
startTime: startTime,
currentTime: currentTime,
currentHeight: currentHeight,
minimumStartDelayTime: projectMinimumStartDelayTime,
}
// Checks: validate balance before creating project
tokenBalance := common.BalanceOf(tokenPath, caller)
if tokenBalance < depositAmount {
panic(
makeErrorWithDetails(
errInsufficientBalance, ufmt.Sprintf(
"caller(%s) balance(%d) < depositAmount(%d)",
caller.String(), tokenBalance, depositAmount,
),
),
)
}
// Effects: create project and save state
project, err := lp.createProject(0, rlm, params)
if err != nil {
panic(err)
}
// Interactions: transfer tokens
common.SafeGRC20TransferFrom(
0, rlm,
tokenPath,
caller,
launchpadAddr,
depositAmount,
)
tier30, err := getProjectTier(project, projectTier30)
if err != nil {
panic(err)
}
tier90, err := getProjectTier(project, projectTier90)
if err != nil {
panic(err)
}
tier180, err := getProjectTier(project, projectTier180)
if err != nil {
panic(err)
}
conditionEventAttrs := buildConditionEventAttrs(params.conditionTokens, params.conditionAmounts)
eventAttrs := append([]string{
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"name", name,
"tokenPath", tokenPath,
"recipient", recipient.String(),
"depositAmount", utils.FormatInt(depositAmount),
"tier30Ratio", utils.FormatInt(params.tier30Ratio),
"tier90Ratio", utils.FormatInt(params.tier90Ratio),
"tier180Ratio", utils.FormatInt(params.tier180Ratio),
"startTime", utils.FormatInt(params.startTime),
"projectId", project.ID(),
"tier30Amount", utils.FormatInt(tier30.TotalDistributeAmount()),
"tier30EndTime", utils.FormatInt(tier30.EndTime()),
"tier90Amount", utils.FormatInt(tier90.TotalDistributeAmount()),
"tier90EndTime", utils.FormatInt(tier90.EndTime()),
"tier180Amount", utils.FormatInt(tier180.TotalDistributeAmount()),
"tier180EndTime", utils.FormatInt(tier180.EndTime()),
}, conditionEventAttrs...)
chain.Emit(
"CreateProject",
eventAttrs...,
)
return project.ID()
}
// createProject creates a new project with the given parameters.
// This function validates the input parameters, creates the project structure,
// and sets up the project tiers and reward managers.
// Returns the created project and any error.
func (lp *launchpadV1) createProject(_ int, rlm realm, params *createProjectParams) (*launchpad.Project, error) {
if err := params.validate(); err != nil {
return nil, err
}
// create project
project := launchpad.NewProject(
params.name,
params.tokenPath,
params.depositAmount,
params.recipient,
params.currentHeight,
params.currentTime,
)
// Get state components
projects := lp.store.GetProjects()
projectTierRewardManagers := lp.store.GetProjectTierRewardManagers()
// check duplicate project
if projects.Has(project.ID()) {
return nil, makeErrorWithDetails(
errDuplicateProject,
ufmt.Sprintf("project(%s) already exists", project.ID()),
)
}
projectConditions, err := launchpad.NewProjectConditionsWithError(params.conditionTokens, params.conditionAmounts)
if err != nil {
return nil, err
}
for _, condition := range projectConditions {
addProjectCondition(project, condition.TokenPath(), condition)
}
projectTierRatios := map[int64]int64{
projectTier30: params.tier30Ratio,
projectTier90: params.tier90Ratio,
projectTier180: params.tier180Ratio,
}
accumulatedTierDistributeAmount := int64(0)
for _, duration := range projectTierDurations {
rewardCollectableDuration := projectTierRewardCollectableDuration[duration]
tierDurationTime := projectTierDurationTimes[duration]
tierDistributeAmount := gnsmath.SafeMulDivInt64(params.depositAmount, projectTierRatios[duration], 100)
accumulatedTierDistributeAmount = gnsmath.SafeAddInt64(accumulatedTierDistributeAmount, tierDistributeAmount)
// if the last tier, distribute the remaining amount
if duration == projectTier180 {
remainTierDistributeAmount := gnsmath.SafeSubInt64(params.depositAmount, accumulatedTierDistributeAmount)
tierDistributeAmount = gnsmath.SafeAddInt64(tierDistributeAmount, remainTierDistributeAmount)
}
projectTier := newProjectTier(
project.ID(),
duration,
tierDistributeAmount,
params.startTime,
params.startTime+tierDurationTime,
)
addProjectTier(project, duration, projectTier)
projectTierRewardManagers.Set(projectTier.ID(), newRewardManager(
projectTier.TotalDistributeAmount(),
projectTier.StartTime(),
projectTier.EndTime(),
rewardCollectableDuration,
))
}
project.SetTiersRatios(projectTierRatios)
projects.Set(project.ID(), project)
// Save the modified state back
if err := lp.store.SetProjects(0, rlm, projects); err != nil {
return nil, err
}
if err := lp.store.SetProjectTierRewardManagers(0, rlm, projectTierRewardManagers); err != nil {
return nil, err
}
recipients := lp.store.GetProjectRecipients()
recipients.Set(project.Recipient().String(), true)
if err := lp.store.SetProjectRecipients(0, rlm, recipients); err != nil {
return nil, err
}
return project, nil
}
// TransferLeftFromProjectByAdmin transfers the remaining refundable project-token
// balance of an ended project to a specified recipient.
// Only admin can call this function. Amounts reserved for active depositor
// claims are excluded from the transfer.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the launchpad proxy.
// - projectID: ID of the ended project.
// - recipient: address that receives the remaining project-token balance.
//
// Returns:
// - amount: amount of project-token balance transferred to the recipient.
func (lp *launchpadV1) TransferLeftFromProjectByAdmin(_ int, rlm realm, projectID string, recipient address) int64 {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedLaunchpad()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
access.AssertIsAdmin(caller)
currentHeight := runtime.ChainHeight()
currentTime := time.Now().Unix()
project, err := lp.getProject(projectID)
if err != nil {
panic(err)
}
projectLeftReward, err := lp.transferLeftFromProject(0, rlm, project, recipient, currentTime)
if err != nil {
panic(err)
}
tier30, err := getProjectTier(project, projectTier30)
if err != nil {
panic(err)
}
tier90, err := getProjectTier(project, projectTier90)
if err != nil {
panic(err)
}
tier180, err := getProjectTier(project, projectTier180)
if err != nil {
panic(err)
}
chain.Emit(
"TransferLeftFromProjectByAdmin",
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"projectId", projectID,
"recipient", recipient.String(),
"tokenPath", project.TokenPath(),
"leftReward", utils.FormatInt(projectLeftReward),
"tier30Full", utils.FormatInt(tier30.TotalDepositAmount()),
"tier30Left", utils.FormatInt(getCalculatedLeftReward(tier30)),
"tier90Full", utils.FormatInt(tier90.TotalDepositAmount()),
"tier90Left", utils.FormatInt(getCalculatedLeftReward(tier90)),
"tier180Full", utils.FormatInt(tier180.TotalDepositAmount()),
"tier180Left", utils.FormatInt(getCalculatedLeftReward(tier180)),
"currentHeight", utils.FormatInt(currentHeight),
"currentTime", utils.FormatInt(currentTime),
)
return projectLeftReward
}
// transferLeftFromProject transfers the remaining rewards of a project to a specified recipient.
// This function is called by an admin to transfer any unclaimed rewards from a project to a recipient address.
// It validates the project ID, checks the recipient conditions, calculates the remaining rewards, and performs the transfer.
// Returns the amount of rewards transferred to the recipient and any error.
func (lp *launchpadV1) transferLeftFromProject(_ int, rlm realm, project *launchpad.Project, recipient address, currentTime int64) (int64, error) {
if err := validateRefundProject(project, recipient, currentTime); err != nil {
return 0, err
}
emission.MintAndDistributeGns(cross(rlm))
accumTotalDistributeAmount := int64(0)
accumLeftReward := int64(0)
accumCollectedReward := int64(0)
accumCollectableReward := int64(0)
refundableAmountsByTier := make(map[int64]int64)
for duration, tier := range project.Tiers() {
// Settlement uses tier aggregate accounting, never the unbounded
// per-deposit reward tree.
tierCollectableReward := int64(0)
if getTierCurrentDepositCount(tier) > 0 {
var err error
tierCollectableReward, err = lp.applyTierRewardGrowthWithRewards(tier, currentTime)
if err != nil {
return 0, err
}
accumCollectableReward = gnsmath.SafeAddInt64(accumCollectableReward, tierCollectableReward)
}
leftReward := getCalculatedLeftReward(tier)
tierRefundableAmount := gnsmath.SafeSubInt64(leftReward, tierCollectableReward)
if tierRefundableAmount < 0 {
return 0, errors.New(ufmt.Sprintf("tierRefundableAmount(%d) < 0", tierRefundableAmount))
}
refundableAmountsByTier[duration] = tierRefundableAmount
accumLeftReward = gnsmath.SafeAddInt64(accumLeftReward, leftReward)
accumCollectedReward = gnsmath.SafeAddInt64(accumCollectedReward, tier.TotalCollectedAmount())
accumTotalDistributeAmount = gnsmath.SafeAddInt64(accumTotalDistributeAmount, tier.TotalDistributeAmount())
}
if accumLeftReward == 0 {
return 0, errors.New("project has no remaining amount")
}
actualTotalDistributeAmount := gnsmath.SafeAddInt64(accumCollectedReward, accumLeftReward)
if accumTotalDistributeAmount != actualTotalDistributeAmount {
return 0, errors.New(ufmt.Sprintf("accumTotalDistributeAmount(%d) != accumCollectedReward(%d)+accumLeftReward(%d)", accumTotalDistributeAmount, accumCollectedReward, accumLeftReward))
}
// Calculate refundable amount: project remaining minus collectable rewards for remaining depositors
projectLeftReward := accumLeftReward
projectRefundableAmount := gnsmath.SafeSubInt64(projectLeftReward, accumCollectableReward)
if projectRefundableAmount < 0 {
return 0, errors.New(ufmt.Sprintf("projectRefundableAmount(%d) < 0", projectRefundableAmount))
}
if projectRefundableAmount > 0 {
updatedTiers := make(map[int64]*launchpad.ProjectTier)
for duration, tier := range project.Tiers() {
tierRefundableAmount := refundableAmountsByTier[duration]
if tierRefundableAmount > 0 {
tier.SetTotalCollectedAmount(gnsmath.SafeAddInt64(tier.TotalCollectedAmount(), tierRefundableAmount))
}
updatedTiers[duration] = tier
}
project.SetTiers(updatedTiers)
common.SafeGRC20Transfer(0, rlm, project.TokenPath(), recipient, projectRefundableAmount)
}
return projectRefundableAmount, nil
}
// applyTierRewardGrowthWithRewards updates a tier index and returns a
// conservative aggregate reservation for active claims. Rounding dust remains
// in the project instead of risking an under-reserved depositor claim.
func (lp *launchpadV1) applyTierRewardGrowthWithRewards(tier *launchpad.ProjectTier, currentTime int64) (int64, error) {
rewardManager, err := lp.getProjectTierRewardManager(tier.ID())
if err != nil {
return 0, err
}
if err := updateRewardPerDepositX128(rewardManager, getTierCurrentDepositAmount(tier), currentTime); err != nil {
return 0, err
}
emitUpdateLaunchpadRewardAccumulation(tier.ID(), rewardManager, getTierCurrentDepositAmount(tier))
return calculateMaximumClaimableRewardsForActiveDeposits(rewardManager), nil
}
// validateTransferLeft validates the transfer of remaining tokens
func validateRefundProject(project *launchpad.Project, recipient address, currentTime int64) error {
if !recipient.IsValid() {
return errors.New(ufmt.Sprintf("invalid recipient address(%s)", recipient.String()))
}
return validateRefundRemainingAmount(project, currentTime)
}
type createProjectParams struct {
name string
tokenPath string
recipient address
depositAmount int64
conditionTokens string
conditionAmounts string
tier30Ratio int64
tier90Ratio int64
tier180Ratio int64
startTime int64
currentTime int64
currentHeight int64
minimumStartDelayTime int64
}
func (p *createProjectParams) validate() error {
if err := p.validateName(); err != nil {
return err
}
if err := p.validateTokenPath(); err != nil {
return err
}
if err := p.validateRecipient(); err != nil {
return err
}
if err := p.validateDepositAmount(); err != nil {
return err
}
if err := p.validateRatio(); err != nil {
return err
}
if err := p.validateStartTime(p.currentTime, p.minimumStartDelayTime); err != nil {
return err
}
if err := p.validateConditions(); err != nil {
return err
}
return nil
}
// validateName checks if the project name is valid.
func (p *createProjectParams) validateName() error {
if p.name == "" {
return makeErrorWithDetails(errInvalidInput, "project name cannot be empty")
}
if len(p.name) > 100 {
return makeErrorWithDetails(errInvalidInput, "project name is too long")
}
return nil
}
// validateTokenPath validates the token path is not empty and is registered.
func (p *createProjectParams) validateTokenPath() error {
if p.tokenPath == "" {
return makeErrorWithDetails(errInvalidInput, "tokenPath cannot be empty")
}
if err := common.IsRegistered(p.tokenPath); err != nil && !isGovernanceToken(p.tokenPath) {
return makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("tokenPath(%s) not registered", p.tokenPath))
}
return nil
}
// validateRecipient checks if the recipient address is valid.
func (p *createProjectParams) validateRecipient() error {
if !p.recipient.IsValid() {
return makeErrorWithDetails(errInvalidAddress, ufmt.Sprintf("recipient address(%s)", p.recipient.String()))
}
return nil
}
// validateDepositAmount ensures that the deposit amount is greater than zero.
func (p *createProjectParams) validateDepositAmount() error {
if p.depositAmount == 0 {
return makeErrorWithDetails(errInvalidInput, "deposit amount cannot be 0")
}
if p.depositAmount < 0 {
return makeErrorWithDetails(errInvalidInput, "deposit amount cannot be negative")
}
return nil
}
// validateRatio checks if each tier ratio is non-negative and the sum equals 100.
func (p *createProjectParams) validateRatio() error {
if p.tier30Ratio < 0 || p.tier90Ratio < 0 || p.tier180Ratio < 0 {
return makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("tier ratios must be non-negative (30:%d, 90:%d, 180:%d)", p.tier30Ratio, p.tier90Ratio, p.tier180Ratio),
)
}
sum := p.tier30Ratio + p.tier90Ratio + p.tier180Ratio
if sum != 100 {
return makeErrorWithDetails(
errInvalidInput,
ufmt.Sprintf("invalid ratio, sum of all tiers(30:%d, 90:%d, 180:%d) should be 100", p.tier30Ratio, p.tier90Ratio, p.tier180Ratio),
)
}
return nil
}
// validateStartTime checks if the start time is available with minimum delay requirement.
func (p *createProjectParams) validateStartTime(now int64, minimumStartDelayTime int64) error {
availableStartTime := now + minimumStartDelayTime
if p.startTime < availableStartTime {
return makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("start time(%d) must be greater than now(%d)", p.startTime, availableStartTime))
}
return nil
}
func (p *createProjectParams) validateConditions() error {
if p.conditionTokens == "" && p.conditionAmounts == "" {
return nil
}
tokenPaths := strings.Split(p.conditionTokens, stringSplitterPad)
minimumAmounts := strings.Split(p.conditionAmounts, stringSplitterPad)
if len(tokenPaths) != len(minimumAmounts) {
return makeErrorWithDetails(errInvalidInput, "conditionTokens and conditionAmounts are not matched")
}
if len(tokenPaths) > maxProjectConditionCount {
return makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("condition count(%d) exceeds maximum(%d)", len(tokenPaths), maxProjectConditionCount))
}
tokenPathMap := make(map[string]bool)
for _, tokenPath := range tokenPaths {
err := common.IsRegistered(tokenPath)
if err != nil && !isGovernanceToken(tokenPath) {
return makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("tokenPath(%s) not registered", tokenPath))
}
if tokenPathMap[tokenPath] {
return makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("tokenPath(%s) is duplicated", tokenPath))
}
tokenPathMap[tokenPath] = true
}
for _, amountStr := range minimumAmounts {
minimumAmount, err := strconv.ParseInt(amountStr, 10, 64)
if err != nil {
return makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("invalid condition amount(%s)", amountStr))
}
if minimumAmount <= 0 {
return makeErrorWithDetails(errInvalidInput, ufmt.Sprintf("condition amount(%s) is not available", amountStr))
}
}
return nil
}
func isGovernanceToken(tokenPath string) bool {
return tokenPath == GOV_XGNS_PATH
}
launchpad_protocol_fee.gno
package launchpad
import (
"gno.land/r/gnoswap/access/v1"
gov_staker "gno.land/r/gnoswap/gov/staker"
"gno.land/r/gnoswap/halt/v1"
)
// CollectProtocolFee collects protocol fee from gov/staker for project recipient wallets.
// Only project recipients can call this function.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the launchpad proxy; validated before collection.
func (lp *launchpadV1) CollectProtocolFee(_ int, rlm realm) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedWithdraw()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
lp.assertHasProject(caller)
gov_staker.CollectRewardFromLaunchPad(cross(rlm), caller)
}
// CollectEmissionReward collects emission rewards from gov/staker for project recipient wallets.
// Only project recipients can call this function.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the launchpad proxy; validated before collection.
func (lp *launchpadV1) CollectEmissionReward(_ int, rlm realm) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedWithdraw()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
lp.assertHasProject(caller)
gov_staker.CollectEmissionRewardFromLaunchPad(cross(rlm), caller)
}
// CollectProtocolFeeReward collects one token path of protocol fee rewards from gov/staker for project recipient wallets.
// Only project recipients can call this function.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the launchpad proxy; validated before collection.
// - tokenPath: token contract path whose protocol-fee reward is collected.
func (lp *launchpadV1) CollectProtocolFeeReward(_ int, rlm realm, tokenPath string) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedWithdraw()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
lp.assertHasProject(caller)
gov_staker.CollectProtocolFeeRewardFromLaunchPad(cross(rlm), caller, tokenPath)
}
launchpad_reward.gno
package launchpad
import (
"chain"
"chain/runtime"
"time"
"gno.land/r/gnoswap/access/v1"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
"gno.land/p/gnoswap/utils/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/halt/v1"
"gno.land/r/gnoswap/launchpad"
)
// CollectRewardByDepositId collects the claimable project-token reward from a
// specific deposit. The reward becomes claimable one day after deposit creation
// or the tier start, whichever is later, capped at the selected tier's end time.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded unchanged by the launchpad proxy.
// - depositID: ID of the deposit to collect from.
//
// Returns:
// - amount: project-token reward amount collected for the deposit, in the token's base units; failures panic before returning.
//
// Only callable by deposit owner after the claimable time.
func (lp *launchpadV1) CollectRewardByDepositId(_ int, rlm realm, depositID string) int64 {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedWithdraw()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
lp.assertIsDepositOwner(depositID, caller)
deposit := lp.mustGetDeposit(depositID)
targetProjectTierID := deposit.ProjectTierID()
currentHeight := runtime.ChainHeight()
currentTime := time.Now().Unix()
rewardTokenPath, rewardAmount, err := lp.collectDepositReward(0, rlm, deposit, currentHeight, currentTime)
if err != nil {
panic(err)
}
// Transfer reward token to depositor
if rewardAmount > 0 {
common.SafeGRC20Transfer(0, rlm, rewardTokenPath, deposit.Depositor(), rewardAmount)
}
chain.Emit(
"CollectRewardByDepositId",
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"depositId", depositID,
"targetProjectTierId", targetProjectTierID,
"rewardTokenPath", rewardTokenPath,
"amount", utils.FormatInt(rewardAmount),
)
return rewardAmount
}
// collectDepositReward calculates and collects the reward for a deposit.
func (lp *launchpadV1) collectDepositReward(_ int, rlm realm, deposit launchpad.Deposit, currentHeight, currentTime int64) (string, int64, error) {
if currentTime <= 0 {
return "", 0, makeErrorWithDetails(errInvalidTime, "currentTime must be positive")
}
// Get project and tier data
project, err := lp.getProject(deposit.ProjectID())
if err != nil {
return "", 0, err
}
projectTier, err := getProjectTier(project, deposit.Tier())
if err != nil {
return "", 0, err
}
// Get reward manager
rewardManager, err := lp.getProjectTierRewardManager(projectTier.ID())
if err != nil {
return "", 0, err
}
// Update reward state before collection
err = updateRewardPerDepositX128(rewardManager, getTierCurrentDepositAmount(projectTier), currentTime)
if err != nil {
return "", 0, err
}
// Collect reward
rewardAmount, err := collectReward(rewardManager, deposit.ID(), currentTime)
if err != nil {
return "", 0, err
}
// Update total collected amount for the tier
if rewardAmount > 0 {
projectTier.SetTotalCollectedAmount(gnsmath.SafeAddInt64(projectTier.TotalCollectedAmount(), rewardAmount))
project.SetTier(deposit.Tier(), projectTier)
projects := lp.store.GetProjects()
if err := lp.store.SetProjects(0, rlm, projects); err != nil {
return "", 0, err
}
}
emitUpdateLaunchpadRewardAccumulation(projectTier.ID(), rewardManager, getTierCurrentDepositAmount(projectTier))
return project.TokenPath(), rewardAmount, nil
}
launchpad_withdraw.gno
package launchpad
import (
"chain"
"chain/runtime"
"time"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
"gno.land/p/gnoswap/utils/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/common"
"gno.land/r/gnoswap/emission"
"gno.land/r/gnoswap/halt/v1"
"gno.land/r/gnoswap/launchpad"
gov_staker "gno.land/r/gnoswap/gov/staker"
)
// CollectDepositGns withdraws the original GNS deposit after the lock period
// ends. Before returning the principal, it settles any claimable project-token
// reward for the deposit.
//
// Parameters:
// - _: Noncrossing implementation-call discriminator; pass 0.
// - rlm: Current realm context forwarded by the launchpad proxy; a spoofed context panics.
// - depositID: ID of the deposit to withdraw.
//
// Returns:
// - amount: original GNS deposit amount returned to the depositor, in base units.
// - err: always nil; withdrawal failures panic before returning.
//
// Only callable by deposit owner when the current time is strictly after the
// selected tier's end time.
func (lp *launchpadV1) CollectDepositGns(_ int, rlm realm, depositID string) (int64, error) {
access.AssertIsRlmCurrent(0, rlm)
halt.AssertIsNotHaltedWithdraw()
previousRealm := rlm.Previous()
caller := previousRealm.Address()
lp.assertIsDepositOwner(depositID, caller)
deposit := lp.mustGetDeposit(depositID)
targetProjectTierID := deposit.ProjectTierID()
currentHeight := runtime.ChainHeight()
currentTime := time.Now().Unix()
// check deposit state
assertIsDepositNotWithdrawn(deposit)
assertIsDepositEnded(deposit, currentTime)
emission.MintAndDistributeGns(cross(rlm))
// Collect reward before withdrawal
rewardTokenPath, rewardAmount, err := lp.collectDepositReward(0, rlm, deposit, currentHeight, currentTime)
if err != nil {
panic(err)
}
beforeTotalGNSStakedAmount := lp.store.GetTotalGNSStakedAmount()
recipient, withdrawalAmount, err := lp.withdrawDeposit(0, rlm, deposit, runtime.ChainHeight(), currentTime)
if err != nil {
panic(err.Error())
}
afterTotalGNSStakedAmount := gnsmath.SafeSubInt64(beforeTotalGNSStakedAmount, withdrawalAmount)
if err := lp.store.SetTotalGNSStakedAmount(0, rlm, afterTotalGNSStakedAmount); err != nil {
panic(err.Error())
}
// Cross-realm governance update before token transfers
unStakeGovernance(0, rlm, recipient, withdrawalAmount)
// Transfer reward token to depositor
if rewardAmount > 0 {
common.SafeGRC20Transfer(0, rlm, rewardTokenPath, deposit.Depositor(), rewardAmount)
chain.Emit(
"CollectRewardByDepositId",
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"depositId", depositID,
"targetProjectTierId", targetProjectTierID,
"amount", utils.FormatInt(rewardAmount),
)
}
// Transfer the original GNS deposit back to the depositor
common.SafeGRC20Transfer(0, rlm, GNS_TOKEN_KEY, deposit.Depositor(), withdrawalAmount)
chain.Emit(
"CollectDepositGns",
"prevAddr", caller.String(),
"prevRealm", previousRealm.PkgPath(),
"depositId", depositID,
"targetProjectTierId", targetProjectTierID,
"amount", utils.FormatInt(withdrawalAmount),
"totalGNSStakedAmount", utils.FormatInt(afterTotalGNSStakedAmount),
"recipient", recipient.String(),
)
return withdrawalAmount, nil
}
// withdrawDeposit withdraws a deposit and updates the reward manager.
func (lp *launchpadV1) withdrawDeposit(_ int, rlm realm, deposit launchpad.Deposit, currentHeight, currentTime int64) (address, int64, error) {
// Input validation
if currentTime <= 0 {
return "", 0, makeErrorWithDetails(errInvalidTime, "currentTime must be positive")
}
// State validation
if deposit.IsWithdrawn() {
return "", 0, makeErrorWithDetails(errAlreadyCollected, ufmt.Sprintf("(%s)", deposit.ID()))
}
if !deposit.IsEnded(currentTime) {
return "", 0, makeErrorWithDetails(errNotYetEndedProject, ufmt.Sprintf("(%s)", deposit.ID()))
}
// Get project and tier information
project, err := lp.getProject(deposit.ProjectID())
if err != nil {
return "", 0, err
}
projectTier, err := getProjectTier(project, deposit.Tier())
if err != nil {
return "", 0, err
}
// Get reward manager and update rewards before withdrawal
rewardManager, err := lp.getProjectTierRewardManager(projectTier.ID())
if err != nil {
return "", 0, err
}
// Update rewards with current deposit amount
err = updateRewardPerDepositX128(rewardManager, getTierCurrentDepositAmount(projectTier), currentTime)
if err != nil {
return "", 0, err
}
// Process withdrawal from project tier
withdrawToTier(projectTier, deposit)
project.SetTier(deposit.Tier(), projectTier)
// Finalize withdrawal
deposit, withdrawalAmount := withdrawDeposit(deposit, currentHeight, currentTime)
// Remove the reward state and its reserved active claim after withdrawal.
if err := removeRewardState(rewardManager, deposit.ID()); err != nil {
return "", 0, err
}
// Persist the updated value; the caller's deposit value is unchanged.
deposits := lp.store.GetDeposits()
deposits.Set(deposit.ID(), deposit)
// Save the modified state back
if err := lp.store.SetDeposits(0, rlm, deposits); err != nil {
return "", 0, err
}
emitUpdateLaunchpadRewardAccumulation(projectTier.ID(), rewardManager, getTierCurrentDepositAmount(projectTier))
return project.Recipient(), withdrawalAmount, nil
}
// unStakeGovernance removes the staked amount from governance system
func unStakeGovernance(_ int, rlm realm, recipient address, withdrawalAmount int64) {
gov_staker.SetAmountByProjectWallet(cross(rlm), recipient, withdrawalAmount, false)
}
project.gno
package launchpad
import (
"errors"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/launchpad"
)
func isProjectActive(p *launchpad.Project, currentTime int64) bool {
return getStandardTier(p).IsActivated(currentTime)
}
func isProjectEnded(p *launchpad.Project, currentTime int64) bool {
return getStandardTier(p).IsEnded(currentTime)
}
func getProjectRemainingAmount(p *launchpad.Project) int64 {
remainingAmount := int64(0)
for _, tier := range p.Tiers() {
remainingAmount = gnsmath.SafeAddInt64(remainingAmount, getCalculatedLeftReward(tier))
}
return remainingAmount
}
func checkProjectConditions(p *launchpad.Project, caller address, balanceOfFunc func(tokenPath string, caller address) int64) error {
conditions := p.Conditions()
if conditions == nil {
return makeErrorWithDetails(errInvalidData, "conditions is nil")
}
for _, condition := range conditions {
// xGNS(or GNS) may have a zero condition
if !condition.IsAvailable() {
continue
}
tokenPath := condition.TokenPath()
balance := balanceOfFunc(tokenPath, caller)
if err := condition.CheckBalanceCondition(tokenPath, balance); err != nil {
return err
}
}
return nil
}
func getProjectTier(p *launchpad.Project, duration int64) (*launchpad.ProjectTier, error) {
tier, err := p.GetTier(duration)
if err != nil {
return nil, makeErrorWithDetails(errDataNotFound, err.Error())
}
return tier, nil
}
func getStandardTier(p *launchpad.Project) *launchpad.ProjectTier {
projectTier, err := p.GetTier(projectTier180)
if err != nil {
panic(makeErrorWithDetails(errDataNotFound, err.Error()))
}
return projectTier
}
func validateRefundRemainingAmount(p *launchpad.Project, currentTime int64) error {
if !isProjectEnded(p, currentTime) {
return errors.New(
ufmt.Sprintf("project not ended yet(current:%d, endTime: %d)", currentTime, getStandardTier(p).EndTime()),
)
}
if getProjectRemainingAmount(p) == 0 {
return errors.New(
ufmt.Sprintf("project has no remaining amount"),
)
}
return nil
}
func addProjectTier(p *launchpad.Project, tierDuration int64, projectTier *launchpad.ProjectTier) {
p.SetTier(tierDuration, projectTier)
}
func addProjectCondition(p *launchpad.Project, tokenPath string, condition *launchpad.ProjectCondition) {
p.SetCondition(tokenPath, condition)
}
project_tier.gno
package launchpad
import (
"errors"
"gno.land/r/gnoswap/launchpad"
"gno.land/p/gnoswap/consts/v1"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
)
func getTierCurrentDepositCount(t *launchpad.ProjectTier) int64 {
return gnsmath.SafeSubInt64(t.TotalDepositCount(), t.TotalWithdrawCount())
}
func getTierCurrentDepositAmount(t *launchpad.ProjectTier) int64 {
return gnsmath.SafeSubInt64(t.TotalDepositAmount(), t.TotalWithdrawAmount())
}
func getCalculatedLeftReward(t *launchpad.ProjectTier) int64 {
return gnsmath.SafeSubInt64(t.TotalDistributeAmount(), t.TotalCollectedAmount())
}
// isTierDepositable allows deposits from project creation until the tier ends.
func isTierDepositable(t *launchpad.ProjectTier, currentTime int64) bool {
return currentTime < t.EndTime()
}
func depositToTier(t *launchpad.ProjectTier, deposit launchpad.Deposit) {
totalDepositAmount := gnsmath.SafeAddInt64(t.TotalDepositAmount(), deposit.DepositAmount())
totalDepositCount := gnsmath.SafeAddInt64(t.TotalDepositCount(), 1)
t.SetTotalDepositAmount(totalDepositAmount)
t.SetTotalDepositCount(totalDepositCount)
}
func withdrawToTier(t *launchpad.ProjectTier, deposit launchpad.Deposit) {
totalWithdrawAmount := gnsmath.SafeAddInt64(t.TotalWithdrawAmount(), deposit.DepositAmount())
totalWithdrawCount := gnsmath.SafeAddInt64(t.TotalWithdrawCount(), 1)
t.SetTotalWithdrawAmount(totalWithdrawAmount)
t.SetTotalWithdrawCount(totalWithdrawCount)
}
func updateTierDistributeAmountPerSecond(t *launchpad.ProjectTier) {
// Use time duration instead of block count
distributeTimeDuration := t.EndTime() - t.StartTime()
if distributeTimeDuration <= 0 {
return
}
totalDistributeAmountX128, overflow := u256.Zero().MulOverflow(u256.NewUintFromInt64(t.TotalDistributeAmount()), consts.Q128())
if overflow {
panic(errors.New(errOverflow))
}
// Divide by time duration in seconds
distributeAmountPerSecondX128 := u256.Zero().Div(totalDistributeAmountX128, u256.NewUintFromInt64(distributeTimeDuration))
t.SetDistributeAmountPerSecondX128(distributeAmountPerSecondX128)
}
// newProjectTier returns a pointer to a new ProjectTier with the given values.
func newProjectTier(
projectID string,
tierDuration int64,
totalDistributeAmount int64,
startTime int64,
endTime int64,
) *launchpad.ProjectTier {
tier := launchpad.NewProjectTier(projectID, tierDuration, totalDistributeAmount, startTime, endTime)
updateTierDistributeAmountPerSecond(tier)
return tier
}
render.gno
package launchpad
import (
"chain"
"strings"
prbac "gno.land/p/gnoswap/rbac/v1"
"gno.land/p/moul/md/v0"
"gno.land/p/moul/mdtable/v0"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/access/v1"
"gno.land/r/gnoswap/halt/v1"
launchpadRoot "gno.land/r/gnoswap/launchpad"
)
func (l *launchpadV1) Render(path string) string {
if path != "" {
return "404\n"
}
implementation := launchpadRoot.GetImplementationPackagePath()
out := md.H1("Gnoswap Launchpad")
out += md.Paragraph(
"All GNS amounts use the token's six-decimal base units. Project reward amounts\n" +
"use the project token's own base units.",
)
out += md.H2("Implementation and access")
implementationTable := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Realm address", md.InlineCode(chain.PackageAddress("gno.land/r/gnoswap/launchpad").String())},
{"Active implementation", md.Link(implementation, strings.TrimPrefix(implementation, "gno.land"))},
{"Launchpad operations halted", ufmt.Sprintf("%t", halt.IsHaltedLaunchpad())},
{"Withdrawal operations halted", ufmt.Sprintf("%t", halt.IsHaltedWithdraw())},
{"Project creation role (admin)", renderLaunchpadRole(prbac.ROLE_ADMIN)},
{"Project creation role (governance)", renderLaunchpadRole(prbac.ROLE_GOVERNANCE)},
},
}
out += implementationTable.String()
out += md.H2("Deposit accounting and configuration")
accountingTable := mdtable.Table{
Headers: []string{"Field", "Value"},
Rows: [][]string{
{"Stored project records", ufmt.Sprintf("%d", l.store.GetProjects().Size())},
{"Stored unique project-recipient records", ufmt.Sprintf("%d", l.store.GetProjectRecipients().Size())},
{"Stored project-tier reward-manager records", ufmt.Sprintf("%d", l.store.GetProjectTierRewardManagers().Size())},
{"Stored deposit records (including withdrawn)", ufmt.Sprintf("%d", l.store.GetDeposits().Size())},
{"Deposit ID counter (allocated IDs)", ufmt.Sprintf("%d", l.store.GetDepositCounter().Get())},
{"Current GNS staked amount (base units; 6 decimals)", ufmt.Sprintf("%d", l.store.GetTotalGNSStakedAmount())},
{"Minimum GNS deposit (base units; 6 decimals)", ufmt.Sprintf("%d", minimumDepositAmount)},
{"Minimum project start delay (seconds)", ufmt.Sprintf("%d", projectMinimumStartDelayTime)},
{"Project tiers (days)", "30 / 90 / 180"},
{"Reward claimable duration (seconds)", ufmt.Sprintf("%d", projectTierRewardCollectableDuration[projectTier30])},
},
}
out += accountingTable.String()
return out
}
func renderLaunchpadRole(role prbac.SystemRole) string {
addr, ok := access.GetAddress(role.String())
if !ok || addr == address("") {
return "Unassigned"
}
return md.InlineCode(addr.String())
}
reward_manager.gno
package launchpad
import (
"errors"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/launchpad"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
)
// Helper functions for RewardManager
func isRewardManagerInitialized(r *launchpad.RewardManager) bool {
return r.Rewards().Size() > 0
}
// isPreDepositRewardRefundable reports whether rewards accrued without any
// deposit are left unallocated. newRewardManager marks this by starting the
// accumulated time at the distribute start time.
func isPreDepositRewardRefundable(r *launchpad.RewardManager) bool {
return r.AccumulatedTime() > 0
}
func getDepositRewardState(r *launchpad.RewardManager, depositId string) (*launchpad.RewardState, error) {
rewardStateI := r.Rewards().Get(depositId)
if rewardStateI == nil {
return nil, makeErrorWithDetails(errNotExistDeposit, ufmt.Sprintf("(%s)", depositId))
}
rewardState, ok := rewardStateI.(*launchpad.RewardState)
if !ok {
return nil, ufmt.Errorf("failed to cast rewardState to *launchpad.RewardState: %T", rewardStateI)
}
return rewardState, nil
}
func calculateRewardPerDepositX128(r *launchpad.RewardManager, rewardPerSecondX128 *u256.Uint, totalStaked int64, currentTime int64) (*u256.Uint, error) {
accumulatedTime := r.AccumulatedTime()
if r.DistributeStartTime() > accumulatedTime {
accumulatedTime = r.DistributeStartTime()
}
// not started yet
if currentTime < accumulatedTime {
return u256.Zero(), nil
}
// past distribute end time
if accumulatedTime > r.DistributeEndTime() {
return u256.Zero(), nil
}
// past distribute end time, set to distribute end time
if currentTime > r.DistributeEndTime() {
currentTime = r.DistributeEndTime()
}
if rewardPerSecondX128.IsZero() {
return nil, makeErrorWithDetails(
errNoLeftReward,
ufmt.Sprintf("rewardPerSecond(%d)", rewardPerSecondX128),
)
}
// no left reward
if totalStaked == 0 {
return u256.Zero(), nil
}
// timeDuration * rewardPerSecond / totalStaked
timeDuration := currentTime - accumulatedTime
rewardPerDepositX128 := u256.MulDiv(
u256.NewUintFromInt64(timeDuration),
rewardPerSecondX128,
u256.NewUintFromInt64(totalStaked),
)
return rewardPerDepositX128, nil
}
func addRewardStateByDeposit(r *launchpad.RewardManager, deposit launchpad.Deposit) *launchpad.RewardState {
// Pre-start deposits accrue rewards from the distribute start time.
adjustedDistributeStartTime := deposit.CreatedAt()
if adjustedDistributeStartTime < r.DistributeStartTime() {
adjustedDistributeStartTime = r.DistributeStartTime()
}
claimableTime := adjustedDistributeStartTime + r.RewardClaimableDuration()
if claimableTime > r.DistributeEndTime() {
claimableTime = r.DistributeEndTime()
}
rewardState := launchpad.NewRewardState(
r.AccumulatedRewardPerDepositX128().Clone(),
deposit.DepositAmount(),
adjustedDistributeStartTime,
r.DistributeEndTime(),
claimableTime,
)
// if the first deposit, set the distribute start time
if !isRewardManagerInitialized(r) {
rewardState.SetDistributeStartTime(r.DistributeStartTime())
rewardState.SetDistributeEndTime(r.DistributeEndTime())
rewardState.SetAccumulatedTime(r.DistributeStartTime())
rewardState.SetPriceDebtX128(u256.Zero())
}
return addRewardState(r, deposit, rewardState)
}
func addRewardState(r *launchpad.RewardManager, deposit launchpad.Deposit, rewardState *launchpad.RewardState) *launchpad.RewardState {
addActiveRewardState(r, rewardState)
r.SetReward(deposit.ID(), rewardState)
return rewardState
}
func removeRewardState(r *launchpad.RewardManager, depositId string) error {
rewardState, err := getDepositRewardState(r, depositId)
if err != nil {
return err
}
removeActiveRewardState(r, rewardState)
r.RemoveReward(depositId)
return nil
}
func addActiveRewardState(r *launchpad.RewardManager, rewardState *launchpad.RewardState) {
debt, overflow := u256.Zero().MulOverflow(
rewardState.PriceDebtX128(),
u256.NewUintFromInt64(rewardState.DepositAmount()),
)
if overflow {
panic(errors.New(errOverflow))
}
r.SetActiveDepositAmount(gnsmath.SafeAddInt64(r.ActiveDepositAmount(), rewardState.DepositAmount()))
r.SetActivePriceDebtX128(u256.Zero().Add(r.ActivePriceDebtX128(), debt))
}
func removeActiveRewardState(r *launchpad.RewardManager, rewardState *launchpad.RewardState) {
debt, overflow := u256.Zero().MulOverflow(
rewardState.PriceDebtX128(),
u256.NewUintFromInt64(rewardState.DepositAmount()),
)
if overflow {
panic(errors.New(errOverflow))
}
r.SetActiveDepositAmount(gnsmath.SafeSubInt64(r.ActiveDepositAmount(), rewardState.DepositAmount()))
r.SetActiveClaimedAmount(gnsmath.SafeSubInt64(r.ActiveClaimedAmount(), rewardState.ClaimedAmount()))
r.SetActivePriceDebtX128(u256.Zero().Sub(r.ActivePriceDebtX128(), debt))
}
func addRewardPerDepositX128(r *launchpad.RewardManager, rewardPerDepositX128 *u256.Uint, currentTime int64) error {
if rewardPerDepositX128.IsZero() {
return nil
}
if r.AccumulatedTime() > currentTime || r.DistributeStartTime() > currentTime {
return nil
}
if currentTime > r.DistributeEndTime() {
currentTime = r.DistributeEndTime()
}
accumulated := u256.Zero().Add(r.AccumulatedRewardPerDepositX128(), rewardPerDepositX128)
r.SetAccumulatedRewardPerDepositX128(accumulated)
r.SetAccumulatedTime(currentTime)
return nil
}
// updateRewardPerDepositX128 updates the reward per deposit state.
// This function calculates and updates the accumulated reward per deposit
// based on the current total deposit amount and time.
//
// Parameters:
// - totalDepositAmount (int64): Current total deposit amount
// - time (int64): Current timestamp
//
// Returns:
// - error: If the update fails
func updateRewardPerDepositX128(r *launchpad.RewardManager, totalDepositAmount int64, currentTime int64) error {
if currentTime <= 0 {
return makeErrorWithDetails(errInvalidTime, "time must be positive")
}
// Calculate and update rewards
rewardPerDepositX128, err := calculateRewardPerDepositX128(
r,
r.DistributeAmountPerSecondX128(),
totalDepositAmount,
currentTime,
)
if err != nil {
return err
}
// Without deposits, only advance the accumulated time so that the rewards
// of this period stay refundable instead of going to the next depositor.
if totalDepositAmount == 0 && isPreDepositRewardRefundable(r) {
if currentTime > r.DistributeEndTime() {
currentTime = r.DistributeEndTime()
}
if currentTime > r.AccumulatedTime() {
r.SetAccumulatedTime(currentTime)
}
return nil
}
err = addRewardPerDepositX128(r, rewardPerDepositX128, currentTime)
if err != nil {
return err
}
return nil
}
func updateDistributeAmountPerSecondX128(r *launchpad.RewardManager, totalDistributeAmount int64, distributeStartTime int64, distributeEndTime int64) {
// Use time duration for per-second calculation
timeDuration := distributeEndTime - distributeStartTime
if timeDuration <= 0 {
return
}
totalDistributeAmountX128 := u256.Zero().Lsh(
u256.NewUintFromInt64(totalDistributeAmount),
128,
)
// Divide by time duration in seconds
amountPerSecondX128 := u256.Zero().Div(
totalDistributeAmountX128,
u256.NewUintFromInt64(timeDuration),
)
r.SetDistributeAmountPerSecondX128(amountPerSecondX128)
r.SetDistributeStartTime(distributeStartTime)
r.SetDistributeEndTime(distributeEndTime)
}
// collectReward processes the reward collection for a specific deposit.
// This function ensures that the reward collection is valid and updates
// the claimed amount accordingly.
//
// Parameters:
// - depositId (string): The ID of the deposit
// - currentTime (int64): Current timestamp
//
// Returns:
// - int64: The amount of reward collected
// - error: If the collection fails
func collectReward(r *launchpad.RewardManager, depositId string, currentTime int64) (int64, error) {
if currentTime < r.AccumulatedTime() {
return 0, makeErrorWithDetails(
errInvalidRewardState,
ufmt.Sprintf("currentTime %d is less than AccumulatedTime %d", currentTime, r.AccumulatedTime()),
)
}
rewardState, err := getDepositRewardState(r, depositId)
if err != nil {
return 0, err
}
if !isRewardStateClaimable(rewardState, currentTime) {
return 0, makeErrorWithDetails(
errInvalidRewardState,
ufmt.Sprintf("currentTime %d is less than claimableTime %d", currentTime, rewardState.ClaimableTime()),
)
}
if currentTime < rewardState.DistributeStartTime() {
return 0, makeErrorWithDetails(
errInvalidRewardState,
ufmt.Sprintf("currentTime %d is less than DistributeStartTime %d", currentTime, rewardState.DistributeStartTime()),
)
}
claimableReward := calculateClaimableReward(rewardState, r.AccumulatedRewardPerDepositX128())
if claimableReward == 0 {
return 0, nil
}
rewardState.SetClaimedAmount(rewardState.ClaimedAmount() + claimableReward)
rewards := r.Rewards()
rewards.Set(depositId, rewardState)
r.SetRewards(rewards)
r.SetTotalClaimedAmount(r.TotalClaimedAmount() + claimableReward)
r.SetActiveClaimedAmount(gnsmath.SafeAddInt64(r.ActiveClaimedAmount(), claimableReward))
return claimableReward, nil
}
// newRewardManager returns a pointer to a new RewardManager with the given values.
func newRewardManager(
totalDistributeAmount int64,
distributeStartTime int64,
distributeEndTime int64,
rewardCollectableDuration int64,
) *launchpad.RewardManager {
manager := launchpad.NewRewardManager(totalDistributeAmount, distributeStartTime, distributeEndTime, rewardCollectableDuration)
updateDistributeAmountPerSecondX128(manager, totalDistributeAmount, distributeStartTime, distributeEndTime)
manager.SetAccumulatedTime(distributeStartTime)
return manager
}
// calculateMaximumClaimableRewardsForActiveDeposits reserves every active
// claim without traversing the attacker-controlled reward tree. Aggregating
// before Q128 truncation retains rounding dust but cannot under-reserve claims.
func calculateMaximumClaimableRewardsForActiveDeposits(r *launchpad.RewardManager) int64 {
reward, overflow := u256.Zero().MulOverflow(
r.AccumulatedRewardPerDepositX128(),
u256.NewUintFromInt64(r.ActiveDepositAmount()),
)
if overflow {
panic(errors.New(errOverflow))
}
reward = reward.Sub(reward, r.ActivePriceDebtX128()).Rsh(reward, 128)
totalReward := gnsmath.SafeConvertToInt64(reward)
if totalReward <= r.ActiveClaimedAmount() {
return 0
}
return gnsmath.SafeSubInt64(totalReward, r.ActiveClaimedAmount())
}
reward_state.gno
package launchpad
import (
"errors"
"gno.land/r/gnoswap/launchpad"
gnsmath "gno.land/p/gnoswap/gnsmath/v1"
u256 "gno.land/p/gnoswap/uint256/v1"
)
// Helper functions for RewardState
func isRewardStateClaimable(r *launchpad.RewardState, currentTime int64) bool {
return currentTime >= r.ClaimableTime()
}
// calculateReward calculates the total reward amount based on
// the accumulated reward per deposit.
// Returns the total reward amount.
func calculateReward(r *launchpad.RewardState, accumRewardPerDepositX128 *u256.Uint) int64 {
if accumRewardPerDepositX128 == nil || r.PriceDebtX128() == nil {
return 0
}
actualRewardPerDepositX128 := u256.Zero().Sub(accumRewardPerDepositX128, r.PriceDebtX128())
if actualRewardPerDepositX128.IsZero() {
return 0
}
reward, overflow := u256.Zero().MulOverflow(actualRewardPerDepositX128, u256.NewUintFromInt64(r.DepositAmount()))
if overflow {
panic(errors.New(errOverflow))
}
reward = reward.Rsh(reward, 128)
return gnsmath.SafeConvertToInt64(reward)
}
// calculateClaimableReward calculates the amount of reward that can be claimed
// based on the current accumulated reward per deposit.
// Returns the amount of reward that can be claimed.
func calculateClaimableReward(r *launchpad.RewardState, accumRewardPerDepositX128 *u256.Uint) int64 {
if accumRewardPerDepositX128 == nil {
return 0
}
reward := calculateReward(r, accumRewardPerDepositX128)
claimedAmount := r.ClaimedAmount()
if reward <= claimedAmount {
return 0
}
return reward - claimedAmount
}
state.gno
package launchpad
import (
"errors"
ufmt "gno.land/p/nt/ufmt/v0"
"gno.land/r/gnoswap/launchpad"
)
// Helper functions that access state through launchpadState
func (lp *launchpadV1) getProject(projectID string) (*launchpad.Project, error) {
projects := lp.store.GetProjects()
project := projects.Get(projectID)
if project == nil {
return nil, makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("project(%s) not found", projectID))
}
p, ok := project.(*launchpad.Project)
if !ok {
return nil, makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("project(%s) not found", projectID))
}
return p, nil
}
func (lp *launchpadV1) getProjectTier(projectID string, tierDuration int64) (*launchpad.ProjectTier, error) {
project, err := lp.getProject(projectID)
if err != nil {
return nil, err
}
tier, err := project.GetTier(tierDuration)
if err != nil {
return nil, makeErrorWithDetails(errDataNotFound, err.Error())
}
return tier, nil
}
func (lp *launchpadV1) getProjectTierRewardManager(projectTierID string) (*launchpad.RewardManager, error) {
managers := lp.store.GetProjectTierRewardManagers()
rewardManager := managers.Get(projectTierID)
if rewardManager == nil {
return nil, makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("reward manager(%s) not found", projectTierID))
}
manager, ok := rewardManager.(*launchpad.RewardManager)
if !ok {
return nil, makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("reward manager(%s) not found", projectTierID))
}
return manager, nil
}
func (lp *launchpadV1) getDepositValue(depositId string) (launchpad.Deposit, error) {
deposits := lp.store.GetDeposits()
value := deposits.Get(depositId)
if value == nil {
return launchpad.DefaultDeposit(), errors.New("deposit not found")
}
deposit, ok := value.(launchpad.Deposit)
if !ok {
return launchpad.DefaultDeposit(), errors.New("invalid deposit type")
}
return deposit, nil
}
func (lp *launchpadV1) getDeposit(depositID string) (launchpad.Deposit, error) {
deposits := lp.store.GetDeposits()
depositI := deposits.Get(depositID)
if depositI == nil {
return launchpad.DefaultDeposit(), makeErrorWithDetails(errNotExistDeposit, ufmt.Sprintf("(%s)", depositID))
}
deposit, ok := depositI.(launchpad.Deposit)
if !ok {
return launchpad.DefaultDeposit(), makeErrorWithDetails(errDataNotFound, ufmt.Sprintf("deposit(%s) not found", depositID))
}
return deposit, nil
}
func (lp *launchpadV1) mustGetDeposit(depositID string) launchpad.Deposit {
deposit, err := lp.getDeposit(depositID)
if err != nil {
panic(err)
}
return deposit
}
// nextDepositID increments and returns the next unique deposit ID.
// This is used when creating new deposits.
func (lp *launchpadV1) nextDepositID() string {
return lp.store.NextDepositID()
}
utils.gno
package launchpad
import (
"math"
"strconv"
"strings"
ufmt "gno.land/p/nt/ufmt/v0"
)
const (
MAX_INT64 = math.MaxInt64
MIN_INT64 = math.MinInt64
)
func buildConditionEventAttrs(conditionTokens string, conditionAmounts string) []string {
if conditionTokens == "" {
return []string{}
}
tokenPaths := strings.Split(conditionTokens, stringSplitterPad)
amounts := strings.Split(conditionAmounts, stringSplitterPad)
eventAttrs := make([]string, 0, len(tokenPaths)*2)
for index, tokenPath := range tokenPaths {
eventAttrs = append(eventAttrs, ufmt.Sprintf("conditionsTokens[%d]", index))
eventAttrs = append(eventAttrs, tokenPath+stringSplitterPad+amounts[index])
}
return eventAttrs
}
// parseProjectTierID parses a project tier ID into its project ID and duration.
// Returns the project ID {tokenPath}:{createdHeight} and the duration of the project tier (30, 90, 180).
func parseProjectTierID(projectTierID string) (string, int64) {
parts := strings.Split(projectTierID, ":")
if len(parts) != 3 {
panic(makeErrorWithDetails(
errInvalidData,
ufmt.Sprintf("(%s)", projectTierID),
))
}
projectID := parts[0] + ":" + parts[1]
tierDuration, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil {
panic(makeErrorWithDetails(
errInvalidData,
ufmt.Sprintf("(%s)", projectTierID),
))
}
// Validate tier duration
if tierDuration != projectTier30 && tierDuration != projectTier90 && tierDuration != projectTier180 {
panic(makeErrorWithDetails(
errInvalidTier,
ufmt.Sprintf("pool type(%d) is not available", tierDuration),
))
}
return projectID, tierDuration
}