Class: SolanaRuby::PublicKey

Inherits:
Object
  • Object
show all
Defined in:
lib/solana_ruby/public_key.rb

Constant Summary collapse

PUBLIC_KEY_LENGTH =
32

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ PublicKey

Returns a new instance of PublicKey.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/solana_ruby/public_key.rb', line 10

def initialize(value)
  case value
  when PublicKey
    @bn = value.bn
  when String
    decoded = decode_base58(value)
    validate_length(decoded)
    @bn = to_bn(decoded)
  when Array
    binary = value.pack('C*')
    validate_length(binary)
    @bn = to_bn(binary)
  else
    raise ArgumentError, "Unsupported input type: #{value.class}"
  end
end

Instance Attribute Details

#bnObject (readonly)

Returns the value of attribute bn.



8
9
10
# File 'lib/solana_ruby/public_key.rb', line 8

def bn
  @bn
end

Instance Method Details

#to_base58Object

Converts the public key to Base58



28
29
30
# File 'lib/solana_ruby/public_key.rb', line 28

def to_base58
  Base58.binary_to_base58(to_bytes, :bitcoin)
end

#to_bytesObject

Converts the public key to a binary string



33
34
35
36
37
38
39
40
41
42
# File 'lib/solana_ruby/public_key.rb', line 33

def to_bytes
  padded_bn = @bn.to_s(2) # Binary string from BigNum
  if padded_bn.bytesize < PUBLIC_KEY_LENGTH
    "\x00" * (PUBLIC_KEY_LENGTH - padded_bn.bytesize) + padded_bn
  elsif padded_bn.bytesize > PUBLIC_KEY_LENGTH
    raise "PublicKey byte length exceeds #{PUBLIC_KEY_LENGTH} bytes"
  else
    padded_bn
  end
end