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: averages aggregate include multipayment #1185

Open
wants to merge 7 commits into
base: mainsail-develop
Choose a base branch
from
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
32 changes: 32 additions & 0 deletions app/Models/Scopes/MultiPaymentTotalAmountScope.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace App\Models\Scopes;

use App\Enums\ContractMethod;
use App\Facades\Network;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\DB;

final class MultiPaymentTotalAmountScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
// Ignore next line as the `joinSubLateral` works as intended since it is a macro method.
// @phpstan-ignore-next-line
$builder->joinSubLateral(function ($query) {
$query->select('recipient_amount', 'is_multipayment')
->from(function ($query) {
$query->selectRaw('CAST(encode(SUBSTRING(transactions.data, 69, 32), \'hex\') AS int) as tx_count')
->selectRaw('CASE WHEN recipient_address = ? AND encode(SUBSTRING(data FROM 1 FOR 4), \'hex\') = ? THEN TRUE ELSE FALSE END as is_multipayment', [Network::knownContract('multipayment'), ContractMethod::multiPayment()]);
}, 'd')
->joinSubLateral(function ($query) {
$query->selectRaw('SUM(CASE WHEN is_multipayment THEN (\'0x\' || encode(substring(transactions.data, 69 + ((tx_count + 1) * 32) + (n * 32), 32), \'hex\'))::float::numeric ELSE 0 END) as recipient_amount')
->from(DB::raw('generate_series(1, CASE WHEN is_multipayment THEN CAST(encode(SUBSTRING(transactions.data, 69 + ((tx_count + 1) * 32), 32), \'hex\') AS int) ELSE 0 END) n'));
}, 'recipient_amounts_nested', 'is_multipayment', '=', DB::raw('true'), 'left outer');
}, 'recipient_amounts', 'is_multipayment', '=', DB::raw('true'), 'left outer');
}
}
18 changes: 18 additions & 0 deletions app/Providers/EloquentServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
use App\Repositories\WalletRepositoryWithCache;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\ServiceProvider;
use LogicException;

Expand Down Expand Up @@ -48,6 +50,22 @@ private function registerScopes(): void

return $query;
});

QueryBuilder::macro('joinSubLateral', function ($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false) {
/** @var QueryBuilder $this */

/** @var array $subQuery */
$subQuery = $this->createSub($query);

$query = $subQuery[0];
$bindings = $subQuery[1];

$expression = 'LATERAL ('.$query.') as '.$this->grammar->wrapTable($as);

$this->addBinding($bindings, 'join');

return $this->join(new Expression($expression), $first, $operator, $second, $type, $where);
});
}

private function registerRepositories(): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace App\Services\Transactions\Aggregates\Historical;

use App\Models\Scopes\MultiPaymentTotalAmountScope;
use App\Models\Transaction;
use App\Services\BigNumber;
use App\Services\Timestamp;
use ArkEcosystem\Crypto\Utils\UnitConverter;
Expand All @@ -14,20 +16,19 @@ final class AveragesAggregate
{
public function aggregate(): array
{
$data = (array) DB::connection('explorer')
->query()
->select([
/** @var object{count: int, fee: int, amount: BigNumber} */
$data = Transaction::select([
DB::raw('COUNT(*) as count'),
DB::raw('SUM(amount) as amount'),
DB::raw('SUM(gas_price * COALESCE(receipts.gas_used, 0)) as fee'),
DB::raw('SUM(amount) + COALESCE(SUM(recipient_amount), 0) as amount'),
])
->from('transactions')
->join('receipts', 'transactions.id', '=', 'receipts.id')
->withScope(MultiPaymentTotalAmountScope::class)
->first();

$daysSinceEpoch = Timestamp::daysSinceEpoch();

if ($data['count'] === 0) {
if ($data->count === 0) {
return [
'count' => 0,
'amount' => 0,
Expand All @@ -36,10 +37,10 @@ public function aggregate(): array
}

return [
'count' => (int) round($data['count'] / $daysSinceEpoch),
'amount' => (int) round(($data['amount'] / config('currencies.notation.crypto', 1e18)) / $daysSinceEpoch),
'count' => (int) round($data->count / $daysSinceEpoch),
'amount' => (int) round(($data->amount->toFloat()) / $daysSinceEpoch),
'fee' => UnitConverter::formatUnits(
(string) BigNumber::new($data['fee'])->valueOf()->dividedBy($daysSinceEpoch, null, RoundingMode::DOWN),
(string) BigNumber::new($data->fee)->valueOf()->dividedBy($daysSinceEpoch, null, RoundingMode::DOWN),
'gwei'
),
];
Expand Down
1 change: 1 addition & 0 deletions database/factories/TransactionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ public function multiPayment(array $recipients, array $amounts): Factory

return $this->withPayload($payload)
->state(fn () => [
'amount' => 0,
'recipient_address' => Network::knownContract('multipayment'),
]);
}
Expand Down
15 changes: 8 additions & 7 deletions tests/Feature/Http/Livewire/Stats/InsightsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,8 @@
]);

Transaction::factory(4)
->multiPayment([faker()->wallet['address']], [BigNumber::new(1 * 1e18)])
->multiPayment([faker()->wallet['address']], [BigNumber::new(1000 * 1e18)])
->create([
'amount' => 3000 * 1e18,
'gas_price' => 11 * 1e18,
]);

Expand All @@ -145,7 +144,7 @@
expect(Transaction::count())->toBe(9);

$transactionCount = (int) round(9 / 2);
$totalAmount = (int) round(((3000 * 4) + (3 * 2000)) / 2);
$totalAmount = (int) round(((1000 * 4) + (3 * 2000)) / 2);
$totalFees = (int) round(((9 * 2) + (10 * 3) + (11 * 4)) / 2);

Artisan::call('explorer:cache-transactions');
Expand All @@ -166,6 +165,8 @@
trans('pages.statistics.insights.transactions.header.unvote'),
trans('pages.statistics.insights.transactions.header.validator_registration'),
trans('pages.statistics.insights.transactions.header.validator_resignation'),
trans('pages.statistics.insights.transactions.header.username_registration'),
trans('pages.statistics.insights.transactions.header.username_resignation'),
trans('pages.statistics.insights.transactions.header.transactions'),
$transactionCount,
trans('pages.statistics.insights.transactions.header.transaction_volume'),
Expand Down Expand Up @@ -276,10 +277,10 @@

Livewire::test(Insights::class)
->assertSeeInOrder([
// trans('pages.statistics.insights.validators.header.most_unique_voters'),
// $walletMostUnique->address,
// trans('pages.statistics.insights.validators.header.least_unique_voters'),
// $walletLeastUnique->address,
trans('pages.statistics.insights.validators.header.most_unique_voters'),
$walletMostUnique->address,
trans('pages.statistics.insights.validators.header.least_unique_voters'),
$walletLeastUnique->address,
trans('pages.statistics.insights.validators.header.oldest_active_validator'),
$walletOldestActive->address,
trans('pages.statistics.insights.validators.header.newest_active_validator'),
Expand Down
5 changes: 2 additions & 3 deletions tests/Unit/Console/Commands/CacheTransactionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function stubNetwork(): void
]);

Transaction::factory(4)
->multiPayment(['0x5c038505a35f9D20435EDafa79A4F8Bbc643BB86'], [BigNumber::new(3000 * 1e9)])
->multiPayment(['0x5c038505a35f9D20435EDafa79A4F8Bbc643BB86'], [BigNumber::new(3000 * 1e18)])
->create([
'amount' => 0,
'gas_price' => 11,
Expand All @@ -71,8 +71,7 @@ function stubNetwork(): void
expect(Transaction::count())->toBe(10);

$transactionCount = (int) round(10 / 2);
// TODO: include multipayment (4 * 3000) - https://app.clickup.com/t/86dvdvux1
$totalAmount = (int) round(((3 * 2000) + 9000) / 2);
$totalAmount = (int) round(((3 * 2000) + 9000 + (4 * 3000)) / 2);
$totalFees = round((9 * 2) + (10 * 3) + (11 * 4) + 10) / 2;

Artisan::call('explorer:cache-transactions');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

use App\Contracts\Network as NetworkContract;
use App\Models\Transaction;
use App\Models\Wallet;
use App\Services\BigNumber;
use App\Services\Transactions\Aggregates\Historical\AveragesAggregate;
use Carbon\Carbon;
use Tests\Feature\Http\Livewire\__stubs\NetworkStub;

it('should return count', function () {
it('should return count for non-multipayment', function () {
$daysSinceEpoch = 2;
$networkStub = new NetworkStub(true, Carbon::now()->subDay($daysSinceEpoch));

Expand All @@ -22,16 +24,74 @@

$transactionCount = 12;

Transaction::factory($transactionCount)
Transaction::factory(6)
->withReceipt()
->create([
'amount' => 10 * 1e18,
'amount' => 20 * 1e18,
'gas_price' => 25,
]);

Transaction::factory(6)
->withReceipt()
->unvote()
->create([
'amount' => 0 * 1e18,
'gas_price' => 25,
]);

expect(Transaction::count())->toBe($transactionCount);

expect((new AveragesAggregate())->aggregate())->toBe([
'count' => $transactionCount / $daysSinceEpoch,
'amount' => 60,
'amount' => 120 / $daysSinceEpoch,
'fee' => (((25 * 21000) * $transactionCount) / $daysSinceEpoch) / 1e9,
]);
});

it('should return count for multipayment', function () {
$daysSinceEpoch = 2;
$networkStub = new NetworkStub(true, Carbon::now()->subDay($daysSinceEpoch));

app()->singleton(NetworkContract::class, fn () => $networkStub);

expect((new AveragesAggregate())->aggregate())->toBe([
'count' => 0,
'amount' => 0,
'fee' => 0,
]);

$transactionCount = 4;

Transaction::factory(2)
->withReceipt()
->create([
'amount' => 10 * 1e18,
'gas_price' => 25,
]);

$recipient = Wallet::factory()->create();

Transaction::factory()
->withReceipt()
->multiPayment([$recipient->address], [BigNumber::new(14 * 1e18)])
->create([
'amount' => 0,
'gas_price' => 25,
]);

Transaction::factory()
->withReceipt()
->multiPayment([$recipient->address, $recipient->address], [BigNumber::new(14 * 1e18), BigNumber::new(14 * 1e18)])
->create([
'amount' => 0,
'gas_price' => 25,
]);

expect(Transaction::count())->toBe($transactionCount);

expect((new AveragesAggregate())->aggregate())->toBe([
'count' => (int) round($transactionCount / $daysSinceEpoch),
'amount' => 62 / $daysSinceEpoch,
'fee' => (((25 * 21000) * $transactionCount) / $daysSinceEpoch) / 1e9,
]);
});