Class: BSV::Script::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/bsv/script/builder.rb

Overview

Fluent builder for constructing scripts incrementally.

Provides a chainable API for building scripts from opcodes and data pushes, as an alternative to the template constructors on Script.

Examples:

Build a custom script

script = BSV::Script::Script.builder
  .push_op(:OP_DUP)
  .push_op(:OP_HASH160)
  .push_data(pubkey_hash)
  .push_op(:OP_EQUALVERIFY)
  .push_op(:OP_CHECKSIG)
  .build

Instance Method Summary collapse

Constructor Details

#initializeBuilder

Returns a new instance of Builder.



19
20
21
# File 'lib/bsv/script/builder.rb', line 19

def initialize
  @chunks = []
end

Instance Method Details

#buildScript

Finalise and return the constructed Script.

Returns:

  • (Script)

    the built script



54
55
56
# File 'lib/bsv/script/builder.rb', line 54

def build
  Script.from_chunks(@chunks)
end

#push_data(data) ⇒ self

Push raw binary data (automatically selects PUSHDATA encoding).

Parameters:

  • data (String)

    binary data to push

Returns:

  • (self)

    for chaining



37
38
39
40
41
# File 'lib/bsv/script/builder.rb', line 37

def push_data(data)
  bytes = data.b
  @chunks << Chunk.new(opcode: push_opcode_for(bytes.bytesize), data: bytes)
  self
end

#push_hex(hex) ⇒ self

Push hex-encoded data.

Parameters:

  • hex (String)

    hex-encoded data to push

Returns:

  • (self)

    for chaining



47
48
49
# File 'lib/bsv/script/builder.rb', line 47

def push_hex(hex)
  push_data(BSV::Primitives::Hex.decode(hex, name: 'hex data'))
end

#push_op(opcode) ⇒ self

Push an opcode onto the script.

Parameters:

  • opcode (Symbol, Integer)

    opcode name (e.g. :OP_DUP) or byte value

Returns:

  • (self)

    for chaining



27
28
29
30
31
# File 'lib/bsv/script/builder.rb', line 27

def push_op(opcode)
  code = opcode.is_a?(Symbol) ? Opcodes.const_get(opcode) : opcode
  @chunks << Chunk.new(opcode: code)
  self
end