forked from gagliardetto/solana-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instruction_decoder.go
51 lines (48 loc) · 1.7 KB
/
instruction_decoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package solana
import (
"fmt"
bin "github.com/gagliardetto/binary"
)
// DecodeInstructionType decodes instruction at index in the message using the
// provided decoders. Returning the requested type. It's expected that this is
// used in conjunction with typed instructions in the program packages.
func DecodeInstructionType[A interface {
Instruction
Obtain(*bin.VariantDefinition) (bin.TypeID, string, interface{})
}, B any](
expectedProgramID PublicKey,
def *bin.VariantDefinition,
decodeFn func([]*AccountMeta, []byte) (A, error),
) func(*Message, int) (B, error) {
var (
a A
b B
)
return func(msg *Message, index int) (B, error) {
if len(msg.Instructions) <= index {
return b, fmt.Errorf("transaction doesn't have an instruction at index '%d'", index)
}
instruction := msg.Instructions[index]
accs, err := instruction.ResolveInstructionAccounts(msg)
if err != nil {
return b, fmt.Errorf("instruction '%d': failed to resolve accounts: %w", index, err)
}
programID, err := msg.ResolveProgramIDIndex(instruction.ProgramIDIndex)
if err != nil {
return b, fmt.Errorf("instruction '%d': failed to resolve program ID: %w", index, err)
}
if !programID.Equals(expectedProgramID) {
return b, fmt.Errorf("instruction '%d': programID (%s) doesn't match expected value '%s'", index, programID, expectedProgramID)
}
decoded, err := decodeFn(accs, instruction.Data)
if err != nil {
return b, fmt.Errorf("instruction '%d': failed to decode as '%T': %w", index, a, err)
}
_, _, obtained := decoded.Obtain(def)
v, ok := obtained.(B)
if !ok {
return b, fmt.Errorf("instruction '%d': obtained type '%T' doesn't match expected type '%T'", index, obtained, b)
}
return v, nil
}
}