Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions api/dbv1/get_undisbursed_challenges.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions api/dbv1/queries/get_undisbursed_challenges.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ SELECT
user_challenges.specifier,
user_challenges.amount
FROM user_challenges
JOIN challenges ON challenges.id = user_challenges.challenge_id AND challenges.active
JOIN users ON users.user_id = user_challenges.user_id
-- Anti-join the raw table by (challenge_id, specifier); the v_challenge_disbursements
-- view drops disbursements whose recipient wallet doesn't resolve to a user.
Expand All @@ -14,6 +15,8 @@ LEFT JOIN sol_reward_disbursements AS challenge_disbursements
AND challenge_disbursements.specifier = user_challenges.specifier
WHERE
challenge_disbursements.challenge_id IS NULL
AND user_challenges.challenge_id IN ('tt', 'tut')
AND users.is_current AND NOT users.is_deactivated
AND user_challenges.is_complete
AND user_challenges.user_id = @user_id
AND (@challenge_id::text = '' OR user_challenges.challenge_id = @challenge_id)
Expand Down
11 changes: 11 additions & 0 deletions api/rewards_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package api

import "github.com/gofiber/fiber/v2"

func isTrendingReward(id string) bool { return id == "tt" || id == "tut" }

// Keep retired routes explicit for older clients, before any code consumption,
// pool creation, signing or Solana transaction submission.
func programmableRewardsDisabled(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusGone, "Programmable rewards are no longer supported")
}
49 changes: 49 additions & 0 deletions api/rewards_policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package api

import (
"bytes"
"context"
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/require"
"net/http/httptest"
"os"
"testing"
)

func TestRetiredRewardClaimsRejectBeforeDependencies(t *testing.T) {
server := &ApiServer{} // No database, key or Solana client may be needed.
app := fiber.New()
app.Post("/rewards/claim", server.v1ClaimRewards)
for _, id := range []string{"e", "tp", "dvl", "rbig1", "unknown"} {
req := httptest.NewRequest("POST", "/rewards/claim", bytes.NewBufferString(`{"userId":"L50xn","challengeId":"`+id+`"}`))
req.Header.Set("Content-Type", "application/json")
res, err := app.Test(req)
require.NoError(t, err)
require.Equal(t, 410, res.StatusCode)
res.Body.Close()
}
}

func TestProgrammableRewardRoutesRetired(t *testing.T) {
app := testAppWithFixtures(t)
for _, path := range []string{"/v1/rewards/code", "/v1/coins/mint/redeem", "/v1/coins/mint/redeem/code"} {
status, _ := testPost(t, app, path, []byte(`{}`), nil)
require.Equal(t, 410, status)
}
}

func TestRetiredChallengeDoesNotGenerateNotification(t *testing.T) {
app := testAppWithFixtures(t)
ctx := context.Background()
function, err := os.ReadFile("../ddl/functions/handle_user_challenges.sql")
require.NoError(t, err)
_, err = app.pool.Exec(ctx, string(function))
require.NoError(t, err)
_, err = app.pool.Exec(ctx, `INSERT INTO user_challenges (challenge_id,user_id,specifier,is_complete,current_step_count,amount,completed_at,completed_blocknumber)
VALUES ('e',402,'retirement-test',true,1,1,now(),200)`)
require.NoError(t, err)
var count int
err = app.pool.QueryRow(ctx, "SELECT COUNT(*) FROM notification WHERE data->>'specifier' = 'retirement-test'").Scan(&count)
require.NoError(t, err)
require.Zero(t, count)
}
10 changes: 5 additions & 5 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ func NewApiServer(config config.Config) *ApiServer {

// Rewards
g.Post("/rewards/claim", app.v1ClaimRewards)
g.Post("/rewards/code", app.v1CreateRewardCode)
g.Post("/rewards/code", programmableRewardsDisabled)

// Prizes
g.Get("/prizes", app.v1Prizes)
Expand Down Expand Up @@ -753,10 +753,10 @@ func NewApiServer(config config.Config) *ApiServer {
g.Get("/coins/:mint/insights", app.v1CoinInsights)
g.Get("/coins/:mint/members", app.v1CoinsMembers)
g.Get("/coins/:mint/members/count", app.v1CoinMembersCount)
g.Get("/coins/:mint/redeem", app.v1CoinsRedeem)
g.Get("/coins/:mint/redeem/:code", app.v1CoinsRedeemCode)
g.Post("/coins/:mint/redeem", app.requireAuthMiddleware, app.requireWriteScope, app.v1CoinsPostRedeem)
g.Post("/coins/:mint/redeem/:code", app.requireAuthMiddleware, app.requireWriteScope, app.v1CoinsPostRedeem)
g.Get("/coins/:mint/redeem", programmableRewardsDisabled)
g.Get("/coins/:mint/redeem/:code", programmableRewardsDisabled)
g.Post("/coins/:mint/redeem", programmableRewardsDisabled)
g.Post("/coins/:mint/redeem/:code", programmableRewardsDisabled)
g.Post("/coins", app.v1CreateCoin)
g.Post("/coins/:mint", app.v1UpdateCoin)

Expand Down
3 changes: 3 additions & 0 deletions api/v1_challenges_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ func weeklyPoolWindowStartAt(now time.Time) time.Time {
}

func (app *ApiServer) v1ChallengesInfo(c *fiber.Ctx) error {
if !isTrendingReward(c.Params("challengeId")) {
return fiber.NewError(fiber.StatusGone, "User challenges are no longer supported")
}
params := GetChallengesInfoQueryParams{}
if err := app.ParseAndValidateQueryParams(c, &params); err != nil {
return err
Expand Down
14 changes: 7 additions & 7 deletions api/v1_challenges_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func TestV1ChallengesInfo(t *testing.T) {
fixtures := database.FixtureMap{
"challenges": {
{
"id": "challenge-aggregate",
"id": "tt",
"type": "aggregate",
"amount": "100000000",
"active": true,
Expand All @@ -31,7 +31,7 @@ func TestV1ChallengesInfo(t *testing.T) {
},
"sol_reward_disbursements": {
{
"challenge_id": "challenge-aggregate",
"challenge_id": "tt",
"specifier": "spec-a",
"signature": "sig-a",
"instruction_index": 0,
Expand All @@ -45,28 +45,28 @@ func TestV1ChallengesInfo(t *testing.T) {

database.Seed(app.pool.Replicas[0], fixtures)

status, body := testGet(t, app, "/v1/challenges/challenge-aggregate/info")
status, body := testGet(t, app, "/v1/challenges/tt/info")
assert.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{
"data.challenge_id": "challenge-aggregate",
"data.challenge_id": "tt",
"data.type": "aggregate",
"data.amount": "100000000",
"data.weekly_pool": 100,
"data.weekly_pool_remaining": 98,
})

status, body = testGet(t, app, "/v1/challenges/challenge-aggregate/info?weekly_pool_min_amount=99")
status, body = testGet(t, app, "/v1/challenges/tt/info?weekly_pool_min_amount=99")
assert.Equal(t, 500, status)
jsonAssert(t, body, map[string]any{
"data.challenge_id": "challenge-aggregate",
"data.challenge_id": "tt",
"data.weekly_pool_remaining": 98,
})
}

func TestV1ChallengesInfoInvalidWeeklyPoolMinAmount(t *testing.T) {
app := emptyTestApp(t)

status, body := testGet(t, app, "/v1/challenges/any/info?weekly_pool_min_amount=-1")
status, body := testGet(t, app, "/v1/challenges/tt/info?weekly_pool_min_amount=-1")
assert.Equal(t, 400, status)
jsonAssert(t, body, map[string]any{
"error": "weekly_pool_min_amount is invalid",
Expand Down
28 changes: 3 additions & 25 deletions api/v1_challenges_undisbursed.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,13 @@
package api

import (
"fmt"
"strings"
"time"

"api.audius.co/trashid"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
)

// openRewards are challenge IDs available to unverified users
var openRewards = []string{
"dvl", // daily volume rewards
"t", // tastemaker
"tp", // trending playlists
"tt", // trending
"tut", // trending underground
"b", // audio match buy (from verified user)
"rd", // referred (by verified user)
"w", // remix contest winner (from verified user)
"cs", // cosign (from verified user)
}

type GetUndisbursedChallengesQueryParams struct {
ChallengeID string `query:"challenge_id"`
CompletedBlocknumber int `query:"completed_blocknumber"`
Expand All @@ -41,13 +26,7 @@ func (app *ApiServer) v1ChallengesUndisbursed(c *fiber.Ctx) error {
return err
}

openRewardsPlaceholders := make([]string, len(openRewards))
for i, reward := range openRewards {
openRewardsPlaceholders[i] = fmt.Sprintf("'%s'", reward)
}
openRewardsInClause := strings.Join(openRewardsPlaceholders, ", ")

sql := fmt.Sprintf(`
sql := `
-- Get Undisbursed Challenges
SELECT user_challenges.challenge_id,
user_challenges.user_id,
Expand All @@ -71,21 +50,20 @@ func (app *ApiServer) v1ChallengesUndisbursed(c *fiber.Ctx) error {
WHERE challenge_disbursements.challenge_id IS NULL
AND user_challenges.is_complete
AND challenges.active
AND user_challenges.challenge_id IN ('tt', 'tut')
AND users.is_current
AND NOT users.is_deactivated
AND (@user_id = 0 OR user_challenges.user_id = @user_id)
AND (@completed_blocknumber = 0 OR user_challenges.completed_blocknumber > @completed_blocknumber)
AND (@challenge_id = '' OR user_challenges.challenge_id = @challenge_id)
-- Filter by verification status: unverified users only see openRewards, verified users see all
AND (users.is_verified = true OR user_challenges.challenge_id IN (%s))
ORDER BY
user_challenges.user_id ASC,
user_challenges.challenge_id ASC,
user_challenges.completed_blocknumber ASC
LIMIT COALESCE(@limit, 100)
OFFSET @offset
;
`, openRewardsInClause)
`

rows, err := app.pool.Query(c.Context(), sql, pgx.NamedArgs{
"user_id": userId,
Expand Down
101 changes: 39 additions & 62 deletions api/v1_challenges_undisbursed_test.go
Original file line number Diff line number Diff line change
@@ -1,72 +1,49 @@
package api

import (
"api.audius.co/api/dbv1"
"context"
"github.com/stretchr/testify/require"
"testing"

"github.com/stretchr/testify/assert"
)

func TestGetUndisbursedChallenges(t *testing.T) {
func TestTrendingOnlyUndisbursed(t *testing.T) {
app := testAppWithFixtures(t)

// Set all users as verified so they can see all challenges
ctx := context.Background()
_, err := app.pool.Exec(ctx, `UPDATE users SET is_verified = true WHERE is_current = true`)
assert.NoError(t, err)

// Test basic functionality with no parameters
status, body := testGet(t, app, "/v1/challenges/undisbursed")
assert.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{
"data.0.challenge_id": "e",
"data.0.user_id": "eP7kD",
"data.0.specifier": "def",
"data.0.amount": "3",
"data.0.handle": "challenges_finished_streak",
"data.0.wallet": "0x001",
"data.0.cooldown_days": 0,
})

// Test filtering by user_id
status, body = testGetWithWallet(t, app,
"/v1/challenges/undisbursed?user_id=L50xn",
"0x8A2c4dcb2Eb9c2C5bc6E28310E4B07011D230C0A",
)
assert.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{
"data.0.user_id": "L50xn",
})

// Test filtering by user_id with path parameter
status, body = testGet(t, app, "/v1/challenges/undisbursed/L50xn")
assert.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{
"data.0.user_id": "L50xn",
})

// Test filtering by challenge_id
status, body = testGet(t, app, "/v1/challenges/undisbursed?challenge_id=f")
assert.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{
"data.0.challenge_id": "f",
})

// Test pagination with limit and offset
status, body = testGet(t, app, "/v1/challenges/undisbursed?limit=1&offset=1")
assert.Equal(t, 200, status)
// Verify we get the second item
jsonAssert(t, body, map[string]any{
"data.0.user_id": "L50xn",
})

// Test invalid parameters
status, _ = testGet(t, app, "/v1/challenges/undisbursed?limit=invalid")
assert.Equal(t, 400, status)

status, _ = testGet(t, app, "/v1/challenges/undisbursed?offset=invalid")
assert.Equal(t, 400, status)

status, _ = testGet(t, app, "/v1/challenges/undisbursed?completed_blocknumber=invalid")
assert.Equal(t, 400, status)
_, err := app.pool.Exec(ctx, `
INSERT INTO challenges (id,type,amount,active,step_count,cooldown_days) VALUES
('tt','trending','1000',true,1,0), ('tut','trending','1000',true,1,0)
ON CONFLICT (id) DO UPDATE SET active = true;
INSERT INTO user_challenges (challenge_id,user_id,specifier,is_complete,current_step_count,amount,completed_blocknumber,completed_at)
VALUES ('tt',402,'2026-11-13:1',true,1,1000,200,now()), ('tut',402,'2026-11-13:6',true,1,100,200,now());
`)
require.NoError(t, err)
// Omitted IDs must not let a claim-all request pay old challenge fixtures.
rows, err := app.queries.GetUndisbursedChallenges(ctx, dbv1.GetUndisbursedChallengesParams{UserID: 402})
require.NoError(t, err)
require.Len(t, rows, 2)
for _, row := range rows {
require.True(t, isTrendingReward(row.ChallengeID))
}
// Explicit retired IDs are excluded at the SQL boundary as well.
rows, err = app.queries.GetUndisbursedChallenges(ctx, dbv1.GetUndisbursedChallengesParams{UserID: 402, ChallengeID: "e"})
require.NoError(t, err)
require.Empty(t, rows)
status, body := testGet(t, app, "/v1/challenges/undisbursed?challenge_id=tt&completed_blocknumber=199")
require.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{"data.#": float64(1), "data.0.specifier": "2026-11-13:1"})
status, body = testGet(t, app, "/v1/challenges/undisbursed?challenge_id=e")
require.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{"data.#": float64(0)})
// Active flags and payments must apply to both listing and actual claiming.
_, err = app.pool.Exec(ctx, `UPDATE challenges SET active = false WHERE id = 'tt';
INSERT INTO sol_reward_disbursements (signature,instruction_index,amount,slot,user_bank,challenge_id,specifier,recipient_eth_address)
VALUES ('paid-tut',0,10000000000,1,'test-bank','tut','2026-11-13:6','0x0000000000000000000000000000000000000001');`)
require.NoError(t, err)
rows, err = app.queries.GetUndisbursedChallenges(ctx, dbv1.GetUndisbursedChallengesParams{UserID: 402})
require.NoError(t, err)
require.Empty(t, rows)
status, body = testGet(t, app, "/v1/challenges/undisbursed")
require.Equal(t, 200, status)
jsonAssert(t, body, map[string]any{"data.#": float64(0)})
}
3 changes: 3 additions & 0 deletions api/v1_claim_rewards.go
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,9 @@ func (app *ApiServer) v1ClaimRewards(c *fiber.Ctx) error {
hashId := body.UserID
challengeId := body.ChallengeID
specifier := body.Specifier
if challengeId != "" && !isTrendingReward(challengeId) {
return fiber.NewError(fiber.StatusGone, "Only trending rewards can be claimed")
}

if hashId == "" {
return fiber.NewError(fiber.StatusBadRequest, "Missing user ID")
Expand Down
Loading