From cd0bc1aa0b08aff6d84c0a305c615b58ed8b5834 Mon Sep 17 00:00:00 2001 From: ChikinDeveloper Date: Sat, 26 Feb 2022 14:17:03 +0100 Subject: [PATCH] Fix getAccountsWithOptionalFeePayer --- .../solana/lib/src/encoder/extensions.dart | 20 ++++++--- packages/solana/test/instruction_test.dart | 43 +++++++++++++++++++ 2 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 packages/solana/test/instruction_test.dart diff --git a/packages/solana/lib/src/encoder/extensions.dart b/packages/solana/lib/src/encoder/extensions.dart index 617a09bd3..7d5d74d2c 100644 --- a/packages/solana/lib/src/encoder/extensions.dart +++ b/packages/solana/lib/src/encoder/extensions.dart @@ -71,14 +71,22 @@ extension InstructionListExt on List { List getAccountsWithOptionalFeePayer({ String? feePayer, }) { + final programIds = []; final accounts = expand( - (Instruction instruction) => [ - ...instruction.accounts, - - /// Append the instruction program id - AccountMeta.readonly(pubKey: instruction.programId, isSigner: false), - ], + (Instruction instruction) { + /// Store instruction programId + if (!programIds.contains(instruction.programId)) { + programIds.add(instruction.programId); + } + return instruction.accounts; + }, ).toList(); + + /// Append programIds to accounts (at the end) + for (final programId in programIds) { + accounts.add(AccountMeta.readonly(pubKey: programId, isSigner: false)); + } + if (feePayer != null) { final index = accounts.indexWhere( (AccountMeta account) => account.pubKey == feePayer, diff --git a/packages/solana/test/instruction_test.dart b/packages/solana/test/instruction_test.dart new file mode 100644 index 000000000..a61b93896 --- /dev/null +++ b/packages/solana/test/instruction_test.dart @@ -0,0 +1,43 @@ +import 'package:solana/encoder.dart'; +import 'package:test/test.dart'; + +void main() { + test('Account metas are correctly sorted', () { + final accounts = _instructionList.getAccountsWithOptionalFeePayer( + feePayer: '9KaA7vEBUdRCcBWxfuMjxYwKfvu8Us3Cg5gkhVFt2LNk'); + for (var i = 0; i < accounts.length; i++) { + expect(accounts[i].pubKey, equals(_expectedResult[i])); + } + }); +} + +final _instructionList = [ + Instruction( + programId: '6KR4qkJN91LGko2gdizheri8LMtCwsJrhtsQt6QPwCi5', + accounts: [ + AccountMeta( + pubKey: 'JBm16mKFNXotwiYjdGuVJcLBeuJdQkT84aNBNhnakToW', + isWriteable: false, + isSigner: false), + ], + data: [], + ), + Instruction( + programId: 'DAz7SnxRL2HRZ2GPigdVRGkoF39bD4Qdv8td5wD3i35u', + accounts: [ + AccountMeta( + pubKey: '2qXtx3xmmmJyA64vrszWAqSXEvYaQNAo1yL4tCxBYPZv', + isWriteable: false, + isSigner: false), + ], + data: [], + ), +]; + +final _expectedResult = [ + '9KaA7vEBUdRCcBWxfuMjxYwKfvu8Us3Cg5gkhVFt2LNk', + 'JBm16mKFNXotwiYjdGuVJcLBeuJdQkT84aNBNhnakToW', + '2qXtx3xmmmJyA64vrszWAqSXEvYaQNAo1yL4tCxBYPZv', + '6KR4qkJN91LGko2gdizheri8LMtCwsJrhtsQt6QPwCi5', + 'DAz7SnxRL2HRZ2GPigdVRGkoF39bD4Qdv8td5wD3i35u', +];