Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: sort popular collections by volume #612

Merged
merged 6 commits into from
Jan 22, 2024
Merged
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
11 changes: 6 additions & 5 deletions app/Http/Controllers/CollectionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use App\Enums\Chain;
use App\Enums\CurrencyCode;
use App\Enums\NftTransferType;
use App\Enums\Period;
use App\Enums\TokenType;
use App\Enums\TraitDisplayType;
use App\Http\Controllers\Traits\HasCollectionFilters;
Expand Down Expand Up @@ -149,15 +150,15 @@ private function getPopularCollections(Request $request): Paginator

$currency = $user ? $user->currency() : CurrencyCode::USD;

$volumeColumn = match ($request->query('period')) {
'7d' => 'avg_volume_7d',
'30d' => 'avg_volume_30d',
default => 'avg_volume_1d',
$period = match ($request->query('period')) {
'7d' => Period::WEEK,
'30d' => Period::MONTH,
default => Period::DAY,
};

/** @var Paginator<PopularCollectionData> $collections */
$collections = Collection::query()
->when($request->query('sort') !== 'floor-price', fn ($q) => $q->orderByWithNulls($volumeColumn.'::numeric', 'desc'))
->when($request->query('sort') !== 'floor-price', fn ($q) => $q->orderByVolume($period))
->filterByChainId($chainId)
->orderByFloorPrice('desc', $currency)
->with([
Expand Down
9 changes: 8 additions & 1 deletion app/Http/Controllers/PopularCollectionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use App\Data\Collections\CollectionStatsData;
use App\Enums\Chain;
use App\Enums\CurrencyCode;
use App\Enums\Period;
use App\Http\Controllers\Traits\HasCollectionFilters;
use App\Models\Collection;
use App\Models\Nft;
Expand Down Expand Up @@ -42,9 +43,15 @@ public function index(Request $request): Response|JsonResponse|RedirectResponse

$sortDirection = in_array($request->query('direction'), ['asc', 'desc']) ? $request->query('direction') : $defaultSortDirection;

$period = match ($request->query('period')) {
'7d' => Period::WEEK,
'30d' => Period::MONTH,
default => Period::DAY,
};

$collections = Collection::query()
->searchByName($request->get('query'))
->when($sortBy === null, fn ($q) => $q->orderBy('volume', 'desc')) // @TODO handle top sorting
->when($sortBy === null, fn ($q) => $q->orderByVolume($period))
->when($sortBy === 'name', fn ($q) => $q->orderByName($sortDirection))
->when($sortBy === 'value', fn ($q) => $q->orderByValue(null, $sortDirection, $currency))
->when($sortBy === 'floor-price', fn ($q) => $q->orderByFloorPrice($sortDirection, $currency))
Expand Down
21 changes: 3 additions & 18 deletions app/Models/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
use App\Enums\TokenType;
use App\Models\Traits\BelongsToNetwork;
use App\Models\Traits\HasFloorPriceHistory;
use App\Models\Traits\HasVolume;
use App\Models\Traits\HasWalletVotes;
use App\Models\Traits\Reportable;
use App\Notifications\CollectionReport;
use App\Support\BlacklistedCollections;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
Expand Down Expand Up @@ -43,7 +43,8 @@
*/
class Collection extends Model
{
use BelongsToNetwork, HasEagerLimit, HasFactory, HasFloorPriceHistory, HasSlug, HasWalletVotes, Reportable, SoftDeletes;
use BelongsToNetwork, HasEagerLimit, HasFactory, HasFloorPriceHistory,
HasSlug, HasVolume, HasWalletVotes, Reportable, SoftDeletes;

const TWITTER_URL = 'https://x.com/';

Expand Down Expand Up @@ -702,22 +703,6 @@ public static function getFiatValueSum(): array
);
}

/**
* @return HasMany<TradingVolume>
*/
public function volumes(): HasMany
{
return $this->hasMany(TradingVolume::class);
}

public function averageVolumeSince(Carbon $date): string
{
return $this->volumes()
->selectRaw('avg(volume::numeric) as aggregate')
->where('created_at', '>', $date)
->value('aggregate');
}

/**
* Modify the query to apply ORDER BY, but with respect to NULL values.
* If direction is ascending, the query will order NULL values first,
Expand Down
65 changes: 65 additions & 0 deletions app/Models/Traits/HasVolume.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

namespace App\Models\Traits;

use App\Enums\Period;
use App\Models\TradingVolume;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany;

trait HasVolume
{
/**
* @return HasMany<TradingVolume>
*/
public function volumes(): HasMany
{
return $this->hasMany(TradingVolume::class);
}

/**
* Calculate the average collection volume since the given time period.
*/
public function averageVolumeSince(Carbon $date): string
{
return $this->volumes()
->selectRaw('avg(volume::numeric) as aggregate')
->where('created_at', '>', $date)
->value('aggregate');
}

/**
* Get the collection volume, but respecting the volume in the given period.
* If no period is provided, get the total collection volume.
*/
public function getVolume(?Period $period = null): ?string
{
return match ($period) {
Period::DAY => $this->avg_volume_1d,
Period::WEEK => $this->avg_volume_7d,
Period::MONTH => $this->avg_volume_30d,
default => $this->total_volume,
};
}

/**
* Scope the query to order the collections by the volume, but respecting the volume in the given period.
*
* @param Builder<self> $query
* @return Builder<self>
*/
public function scopeOrderByVolume(Builder $query, ?Period $period = null): Builder
{
$column = match ($period) {
Period::DAY => 'avg_volume_1d',
Period::WEEK => 'avg_volume_7d',
Period::MONTH => 'avg_volume_30d',
default => 'total_volume',
};

return $query->orderByWithNulls($column.'::numeric', 'desc');
}
}
15 changes: 15 additions & 0 deletions tests/App/Models/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Enums\CurrencyCode;
use App\Enums\NftTransferType;
use App\Enums\Period;
use App\Jobs\ResetCollectionRanking;
use App\Models\Article;
use App\Models\Collection;
Expand Down Expand Up @@ -1525,6 +1526,20 @@
]);
});

it('can get volume based on the period', function () {
$collection = Collection::factory()->create([
'total_volume' => '1',
'avg_volume_1d' => '2',
'avg_volume_7d' => '3',
'avg_volume_30d' => '4',
]);

expect($collection->getVolume())->toBe('1');
expect($collection->getVolume(Period::DAY))->toBe('2');
expect($collection->getVolume(Period::WEEK))->toBe('3');
expect($collection->getVolume(Period::MONTH))->toBe('4');
});

it('can get native token for a network', function () {
$token = Token::factory()->matic()->create([
'is_native_token' => true,
Expand Down
Loading