Skip to content

Commit

Permalink
[PLA-1879] FT mutation support for v1010 (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
leonardocustodio committed Jul 11, 2024
1 parent 8f62ff6 commit 7f82a37
Show file tree
Hide file tree
Showing 24 changed files with 198 additions and 115 deletions.
4 changes: 1 addition & 3 deletions .github/workflows/run_tests.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
name: Run Tests
name: Unit & Functional Tests

on:
pull_request:
paths-ignore:
- "**.md"
push:
paths-ignore:
- "**.md"
Expand Down
58 changes: 58 additions & 0 deletions .github/workflows/sast.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
name: Static Application Security Testing

on:
pull_request:
push:
paths-ignore:
- "**.md"

jobs:
test:
runs-on: ubuntu-latest
services:
mysql:
image: mysql:8
env:
MYSQL_DATABASE: platform
MYSQL_ROOT_PASSWORD: password
ports:
- 33306:3306
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
redis:
image: redis:7
ports:
- 6379:6379
options: --entrypoint redis-server
strategy:
fail-fast: true
matrix:
php: [8.2]

name: PHP ${{ matrix.php }}

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, gd, gmp, intl, json, mysql, readline, sodium, bcmath, pcov
tools: composer:v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: Setup problem matchers
run: |
echo "::add-matcher::${{ runner.tool_cache }}/php.json"
echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Install dependencies
run: |
composer install --no-interaction --no-progress
composer dump-autoload
- name: Run Rector
run: |
./vendor/bin/rector process --dry-run
2 changes: 0 additions & 2 deletions .github/workflows/security_checker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ name: Dependencies Security Checker

on:
pull_request:
paths-ignore:
- '**.md'
push:
paths-ignore:
- '**.md'
Expand Down
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"rebing/graphql-laravel": "^9.2",
"spatie/laravel-package-tools": "^1.0",
"spatie/laravel-ray": "^1.0",
"phrity/websocket": "^1.0"
"phrity/websocket": "^1.0",
"rector/rector": "^1.0"
},
"autoload": {
"psr-4": {
Expand All @@ -45,7 +46,8 @@
"scripts": {
"build-sr25519": "cd vendor/gmajor/sr25519-bindings/go && go build -buildmode=c-shared -o sr25519.so . && mv sr25519.so ../src/Crypto/sr25519.so",
"analyse": "vendor/bin/phpstan analyse",
"fix": "vendor/bin/pint",
"dry-fix": "vendor/bin/rector process --dry-run && vendor/bin/pint --test --config ./pint.json",
"fix": "vendor/bin/rector process && vendor/bin/pint --config ./pint.json",
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-html ../../temp/coverage",
"post-autoload-dump": [
Expand Down
17 changes: 17 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;

return RectorConfig::configure()
->withPaths([
__DIR__ . '/config',
__DIR__ . '/lang',
__DIR__ . '/src',
__DIR__ . '/tests',
])
->withPhpSets(php82: true)
->withPreparedSets(deadCode: true)
->withRules([Spatie\Ray\Rector\RemoveRayCallRector::class])
->withTypeCoverageLevel(0);
13 changes: 10 additions & 3 deletions src/GraphQL/Mutations/CreateFuelTankMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ public function resolve(
SerializationServiceInterface $serializationService,
Substrate $blockchainService
) {
$encodedData = $serializationService->encode($this->getMutationName(), static::getEncodableParams(
$method = isRunningLatest() ? $this->getMutationName() . 'V1010' : $this->getMutationName();
$encodedData = $serializationService->encode($method, static::getEncodableParams(
name: $args['name'],
userAccountManagement: $blockchainService->getUserAccountManagementParams($args),
dispatchRules: $blockchainService->getDispatchRulesParamsArray($args),
Expand All @@ -117,17 +118,23 @@ public function resolve(
public static function getEncodableParams(...$params): array
{
$name = Arr::get($params, 'name', '');
$userAccountManagement = Arr::get($params, 'userAccountManagement', null);
$userAccountManagement = Arr::get($params, 'userAccountManagement');
$ruleSets = collect(Arr::get($params, 'dispatchRules', []));
$providesDeposit = Arr::get($params, 'providesDeposit', false);
$accountRules = Arr::get($params, 'accountRules', new AccountRulesParams());

$extra = isRunningLatest() ? [
'coveragePolicy' => $providesDeposit ? 'Fees' : 'FeesAndDeposit',
] : [
'providesDeposit' => $providesDeposit,
];

return [
'descriptor' => [
'name' => HexConverter::stringToHexPrefixed($name),
'userAccountManagement' => $userAccountManagement?->toEncodable(),
'ruleSets' => $ruleSets->map(fn ($ruleSet) => $ruleSet->toEncodable())->toArray(),
'providesDeposit' => $providesDeposit,
...$extra,
'accountRules' => $accountRules?->toEncodable() ?? [],
],
];
Expand Down
35 changes: 27 additions & 8 deletions src/GraphQL/Mutations/DispatchMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
use Enjin\Platform\Rules\MaxBigInt;
use Enjin\Platform\Rules\MinBigInt;
use Enjin\Platform\Rules\ValidSubstrateAddress;
use Enjin\Platform\Services\Serialization\Interfaces\SerializationServiceInterface;
use Enjin\Platform\Facades\TransactionSerializer;
use Enjin\Platform\Support\Account;
use Enjin\Platform\Support\Hex;
use Enjin\Platform\Support\SS58Address;
Expand Down Expand Up @@ -80,7 +80,6 @@ public function args(): array
'paysRemainingFee' => [
'type' => GraphQL::type('Boolean'),
'description' => __('enjin-platform-fuel-tanks::mutation.dispatch.args.paysRemainingFee'),
'defaultValue' => false,
],
...$this->getSigningAccountField(),
...$this->getIdempotencyField(),
Expand All @@ -98,15 +97,11 @@ public function resolve(
$context,
ResolveInfo $resolveInfo,
Closure $getSelectFields,
SerializationServiceInterface $serializationService
) {
$paysRemainingFee = Arr::get($args, 'paysRemainingFee') ? '01' : '00';
$encodedCall = $this->getEncodedCall($args);
$encodedData = $serializationService->encode($this->getMutationName(), static::getEncodableParams(...$args));
$encodedData .= $encodedCall . $paysRemainingFee;
$encodedCall = static::getFuelTankCall($this->getMethodName(), $args);

return Transaction::lazyLoadSelectFields(
DB::transaction(fn () => $this->storeTransaction($args, $encodedData)),
DB::transaction(fn () => $this->storeTransaction($args, $encodedCall)),
$resolveInfo
);
}
Expand All @@ -133,6 +128,30 @@ public static function getEncodedCall($args)
return HexConverter::unPrefix($encodedData);
}

public static function getFuelTankCall($method, $args, ?string $rawCall = null): string
{
$method = isRunningLatest() ? "{$method}V1010" : $method;
$paysRemainingFee = Arr::get($args, 'paysRemainingFee');

$encodedCall = TransactionSerializer::encode($method, static::getEncodableParams(
tankId: $args['tankId'],
ruleSetId: $args['ruleSetId'],
));

$encodedCall .= $rawCall ?: static::getEncodedCall($args);

return $encodedCall . TransactionSerializer::encodeRaw(
isRunningLatest() ? 'OptionDispatchSettingsV1010' : 'OptionDispatchSettings',
['option' => $paysRemainingFee === null ? null :
[
'useNoneOrigin' => false,
'paysRemainingFee' => $paysRemainingFee,
'signature' => null,
],
],
);
}

public static function getEncodableParams(...$params): array
{
$tankId = Arr::get($params, 'tankId', Account::daemonPublicKey());
Expand Down
15 changes: 12 additions & 3 deletions src/GraphQL/Mutations/InsertRuleSetMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,10 @@ public function resolve(
SerializationServiceInterface $serializationService,
Substrate $blockchainService
) {
$method = isRunningLatest() ? $this->getMutationName() . 'V1010' : $this->getMutationName();
$dispatchRules = $blockchainService->getDispatchRulesParams($args['dispatchRules']);
$encodedData = $serializationService->encode(
$this->getMutationName(),
$method,
static::getEncodableParams(
tankId: $args['tankId'],
ruleSetId: $args['ruleSetId'],
Expand All @@ -121,14 +122,22 @@ public static function getEncodableParams(...$params): array
{
$tankId = Arr::get($params, 'tankId', Account::daemonPublicKey());
$ruleSetId = Arr::get($params, 'ruleSetId', 0);
$rules = Arr::get($params, 'dispatchRules', new DispatchRulesParams());
$rules = Arr::get($params, 'dispatchRules', new DispatchRulesParams())->toEncodable();
$extra = isRunningLatest() ? [
'ruleSet' => [
'rules' => $rules,
'requireAccount' => false,
],
] : [
'rules' => $rules,
];

return [
'tankId' => [
'Id' => HexConverter::unPrefix(SS58Address::getPublicKey($tankId)),
],
'ruleSetId' => $ruleSetId,
'rules' => $rules->toEncodable(),
...$extra,
];
}

Expand Down
11 changes: 6 additions & 5 deletions src/GraphQL/Mutations/MutateFuelTankMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ public function resolve(
SerializationServiceInterface $serializationService,
Substrate $blockchainService
) {
$encodedData = $serializationService->encode($this->getMutationName(), static::getEncodableParams(
$method = isRunningLatest() ? $this->getMutationName() . 'V1010' : $this->getMutationName();
$encodedData = $serializationService->encode($method, static::getEncodableParams(
userAccount: $blockchainService->getUserAccountManagementParams(Arr::get($args, 'mutation')),
providesDeposit: Arr::get($args, 'mutation.providesDeposit'),
accountRules: $blockchainService->getAccountRulesParams(Arr::get($args, 'mutation')),
Expand All @@ -102,17 +103,17 @@ public function resolve(
public static function getEncodableParams(...$params): array
{
$tankId = Arr::get($params, 'tankId', Account::daemonPublicKey());
$userAccount = Arr::get($params, 'userAccount', null);
$providesDeposit = Arr::get($params, 'providesDeposit', null);
$accountRules = Arr::get($params, 'accountRules', null);
$userAccount = Arr::get($params, 'userAccount');
$providesDeposit = Arr::get($params, 'providesDeposit');
$accountRules = Arr::get($params, 'accountRules');

return [
'tankId' => [
'Id' => HexConverter::unPrefix(SS58Address::getPublicKey($tankId)),
],
'mutation' => [
'userAccountManagement' => is_array($userAccount) ? ['NoMutation' => null] : ['SomeMutation' => $userAccount?->toEncodable()],
'providesDeposit' => $providesDeposit,
(isRunningLatest() ? 'coveragePolicy' : 'providesDeposit') => $providesDeposit,
'accountRules' => $accountRules?->toEncodable(),
],
];
Expand Down
3 changes: 2 additions & 1 deletion src/GraphQL/Mutations/RemoveAccountRuleDataMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ public function resolve(
Closure $getSelectFields,
SerializationServiceInterface $serializationService
) {
$encodedData = $serializationService->encode($this->getMutationName(), static::getEncodableParams(...$args));
$method = isRunningLatest() ? $this->getMutationName() . 'V1010' : $this->getMutationName();
$encodedData = $serializationService->encode($method, static::getEncodableParams(...$args));

return Transaction::lazyLoadSelectFields(
DB::transaction(fn () => $this->storeTransaction($args, $encodedData)),
Expand Down
30 changes: 13 additions & 17 deletions src/GraphQL/Traits/HasFuelTankValidationRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,13 @@ protected function commonRulesExist(string $attribute, array $args = []): array
"{$attribute}.whitelistedCallers.*" => ['bail', 'distinct', 'max:255', 'filled', new ValidSubstrateAddress()],
"{$attribute}.whitelistedCallers" => ['nullable', 'array', 'min:1'],
"{$attribute}.requireToken.collectionId" => $isArray
? Rule::forEach(function ($value, $key) {
return [
'bail',
'required_with:' . str_replace('collectionId', 'tokenId', $key),
new MinBigInt(),
new MaxBigInt(Hex::MAX_UINT128),
Rule::exists('collections', 'collection_chain_id'),
];
})
? Rule::forEach(fn ($value, $key) => [
'bail',
'required_with:' . str_replace('collectionId', 'tokenId', $key),
new MinBigInt(),
new MaxBigInt(Hex::MAX_UINT128),
Rule::exists('collections', 'collection_chain_id'),
])
: [
"required_with:{$attribute}.requireToken.tokenId",
Rule::exists('collections', 'collection_chain_id'),
Expand Down Expand Up @@ -85,14 +83,12 @@ protected function commonRules(string $attribute, array $args = []): array
"{$attribute}.whitelistedCallers.*" => ['bail', 'distinct', 'max:255', 'filled', new ValidSubstrateAddress()],
"{$attribute}.whitelistedCallers" => ['nullable', 'array', 'min:1'],
"{$attribute}.requireToken.collectionId" => $isArray
? Rule::forEach(function ($value, $key) {
return [
'bail',
'required_with:' . str_replace('collectionId', 'tokenId', $key),
new MinBigInt(),
new MaxBigInt(Hex::MAX_UINT128),
];
})
? Rule::forEach(fn ($value, $key) => [
'bail',
'required_with:' . str_replace('collectionId', 'tokenId', $key),
new MinBigInt(),
new MaxBigInt(Hex::MAX_UINT128),
])
: [
"required_with:{$attribute}.requireToken.tokenId",
],
Expand Down
27 changes: 12 additions & 15 deletions src/Models/Laravel/Traits/EagerLoadSelectFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,16 @@ public static function selectFields(ResolveInfo $resolveInfo, string $query): ar
static::$query = $query;
$queryPlan = $resolveInfo->lookAhead()->queryPlan();

switch ($query) {
case 'GetFuelTanks':
case 'GetFuelTank':
[$select, $with, $withCount] = static::loadFuelTank(
$queryPlan,
$query == 'GetFuelTanks' ? 'edges.fields.node.fields' : '',
[],
null,
true
);

break;
}
[$select, $with, $withCount] = match ($query) {
'GetFuelTanks', 'GetFuelTank' => static::loadFuelTank(
$queryPlan,
$query == 'GetFuelTanks' ? 'edges.fields.node.fields' : '',
[],
null,
true
),
default => [$select, $with, $withCount],
};


return [$select, $with, $withCount];
Expand Down Expand Up @@ -70,7 +67,7 @@ public static function loadFuelTank(

if (!$isParent) {
$with = [
$key => function ($query) use ($select, $args) {
$key => function ($query) use ($select, $args): void {
$query->select(array_unique($select))
->when($cursor = Cursor::fromEncoded(Arr::get($args, 'after')), fn ($q) => $q->where('id', '>', $cursor->parameter('id')))
->orderBy('fuel_tanks.id');
Expand Down Expand Up @@ -170,7 +167,7 @@ public static function loadWallet(

if (!$isParent) {
$with = [
$key => function ($query) use ($select, $args) {
$key => function ($query) use ($select, $args): void {
$query->select($select)
->when(Arr::get($args, 'transactionIds'), fn ($q) => $q->whereIn('transaction_chain_id', $args['transactionIds']))
->when(Arr::get($args, 'transactionHashes'), fn ($q) => $q->whereIn('transaction_chain_hash', $args['transactionIds']))
Expand Down
Loading

0 comments on commit 7f82a37

Please sign in to comment.