Class: Solrengine::Programs::TransactionBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/solrengine/programs/transaction_builder.rb

Instance Method Summary collapse

Constructor Details

#initializeTransactionBuilder

Returns a new instance of TransactionBuilder.



8
9
10
11
12
13
# File 'lib/solrengine/programs/transaction_builder.rb', line 8

def initialize
  @instructions = []
  @signers = [] # Array of { secret_key:, public_key: } hashes
  @fee_payer = nil
  @recent_blockhash = nil
end

Instance Method Details

#add_instruction(instruction) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/solrengine/programs/transaction_builder.rb', line 15

def add_instruction(instruction)
  if instruction.is_a?(Instruction)
    @instructions << instruction.to_instruction
  elsif instruction.is_a?(Hash)
    @instructions << instruction
  else
    raise Error, "Instruction must be a Solrengine::Programs::Instruction or Hash"
  end
  self
end

#add_signer(keypair) ⇒ Object



26
27
28
29
# File 'lib/solrengine/programs/transaction_builder.rb', line 26

def add_signer(keypair)
  @signers << keypair
  self
end

#buildObject

Build the serialized transaction (signatures + message)



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/solrengine/programs/transaction_builder.rb', line 42

def build
  resolve_blockhash! unless @recent_blockhash
  resolve_fee_payer! unless @fee_payer

  message = build_message
  signatures = sign_message(message)

  # Serialize: compact-u16 signature count + signatures + message
  result = BorshTypes.encode_compact_u16(signatures.size)
  signatures.each { |sig| result += sig }
  result += message
  result
end

#set_fee_payer(pubkey) ⇒ Object



31
32
33
34
# File 'lib/solrengine/programs/transaction_builder.rb', line 31

def set_fee_payer(pubkey)
  @fee_payer = pubkey
  self
end

#set_recent_blockhash(blockhash) ⇒ Object



36
37
38
39
# File 'lib/solrengine/programs/transaction_builder.rb', line 36

def set_recent_blockhash(blockhash)
  @recent_blockhash = blockhash
  self
end

#sign_and_send(commitment: "confirmed") ⇒ Object

Build, sign, and send the transaction



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/solrengine/programs/transaction_builder.rb', line 57

def sign_and_send(commitment: "confirmed")
  ensure_signers!

  tx_bytes = build
  tx_base64 = Base64.strict_encode64(tx_bytes)

  result = Solrengine::Rpc.client.request("sendTransaction", [
    tx_base64,
    {
      "encoding" => "base64",
      "skipPreflight" => false,
      "preflightCommitment" => commitment
    }
  ])

  if result["error"]
    raise TransactionError, "Transaction failed: #{result["error"].inspect}"
  end

  result["result"] # Returns the transaction signature
end