Class: Runar::SDK::RunarContract

Inherits:
Object
  • Object
show all
Defined in:
lib/runar/sdk/contract.rb

Overview

rubocop:disable Naming/AccessorMethodName, Naming/PredicatePrefix

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(artifact, constructor_args) ⇒ RunarContract

Returns a new instance of RunarContract.

Parameters:

  • artifact (RunarArtifact)

    compiled contract artifact

  • constructor_args (Array)

    constructor argument values

Raises:

  • (ArgumentError)

    when arg count does not match the ABI



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/runar/sdk/contract.rb', line 56

def initialize(artifact, constructor_args)
  expected = artifact.abi.constructor_params.length
  actual   = constructor_args.length
  if actual != expected
    raise ArgumentError,
          "RunarContract: expected #{expected} constructor args for " \
          "#{artifact.contract_name}, got #{actual}"
  end

  @artifact         = artifact
  @constructor_args = constructor_args.dup
  @state            = {}
  @code_script      = ''
  @current_utxo     = nil
  @provider         = nil
  @signer           = nil

  init_state_from_constructor_args
end

Instance Attribute Details

#artifactObject (readonly)

Returns the value of attribute artifact.



51
52
53
# File 'lib/runar/sdk/contract.rb', line 51

def artifact
  @artifact
end

Class Method Details

.from_txid(artifact, txid, output_index, provider) ⇒ RunarContract

Reconnect to an existing deployed contract by looking up the transaction on-chain.

rubocop:disable Metrics/AbcSize, Metrics/MethodLength

Parameters:

  • artifact (RunarArtifact)
  • txid (String)

    txid of the deploy transaction

  • output_index (Integer)

    index of the contract output

  • provider (Provider)

Returns:



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/runar/sdk/contract.rb', line 432

def self.from_txid(artifact, txid, output_index, provider)
  tx = provider.get_transaction(txid)
  if output_index >= tx.outputs.length
    raise ArgumentError,
          "RunarContract.from_txid: output index #{output_index} out of range " \
          "(tx has #{tx.outputs.length} outputs)"
  end

  output     = tx.outputs[output_index]
  dummy_args = Array.new(artifact.abi.constructor_params.length, 0)
  contract   = new(artifact, dummy_args)

  stateful = !artifact.state_fields.empty?
  code_script = if stateful
                  last_or = State.find_last_op_return(output.script)
                  last_or != -1 ? output.script[0, last_or] : output.script
                else
                  output.script
                end

  contract.instance_variable_set(:@code_script, code_script)
  contract.instance_variable_set(
    :@current_utxo,
    Utxo.new(txid: txid, output_index: output_index, satoshis: output.satoshis, script: output.script)
  )

  if stateful
    state = State.extract_state_from_script(artifact, output.script)
    contract.instance_variable_set(:@state, state) if state
  end

  contract
end

Instance Method Details

#build_code_scriptString

Build the code script (artifact script with constructor args spliced in).

For each constructor slot, the 1-byte placeholder at byte_offset in the artifact script is replaced with the encoded arg value. Slots are processed in descending byte_offset order so earlier substitutions do not shift the offsets of later ones.

rubocop:disable Metrics/AbcSize, Metrics/MethodLength

Returns:

  • (String)

    hex-encoded code script



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/runar/sdk/contract.rb', line 509

def build_code_script
  script = @artifact.script.dup

  if @artifact.constructor_slots.any?
    sorted_slots = @artifact.constructor_slots.sort_by { |s| -s.byte_offset }
    sorted_slots.each do |slot|
      encoded    = encode_arg(@constructor_args[slot.param_index])
      hex_offset = slot.byte_offset * 2
      script     = "#{script[0, hex_offset]}#{encoded}#{script[hex_offset + 2..]}"
    end
  elsif @artifact.state_fields.empty?
    # Backward compatibility: stateless artifacts without constructorSlots.
    @constructor_args.each { |arg| script += encode_arg(arg) }
  end

  script
end

#build_unlocking_script(method_name, args) ⇒ String

Build the unlocking script for a method call without broadcasting.

Parameters:

  • method_name (String)
  • args (Array)

Returns:

  • (String)

    hex-encoded unlocking script



486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/runar/sdk/contract.rb', line 486

def build_unlocking_script(method_name, args)
  script              = args.map { |a| encode_arg(a) }.join
  public_methods_list = get_public_methods

  if public_methods_list.length > 1
    method_index = public_methods_list.index { |m| m.name == method_name }
    raise ArgumentError, "build_unlocking_script: public method '#{method_name}' not found" unless method_index

    script += State.encode_script_int(method_index)
  end

  script
end

#call(method_name, args = [], provider = nil, signer = nil, options = nil) ⇒ Array(String, TransactionData)

Invoke a public method (spend the contract UTXO).

For stateful contracts, the preimage and k=1 OP_PUSH_TX signature are computed automatically. For methods with Sig params, a 72-byte placeholder is substituted during transaction construction then replaced with a real signature.

Parameters:

  • method_name (String)

    ABI method name

  • args (Array) (defaults to: [])

    user-supplied arguments

  • provider (Provider, nil) (defaults to: nil)

    overrides connected provider

  • signer (Signer, nil) (defaults to: nil)

    overrides connected signer

  • options (CallOptions, nil) (defaults to: nil)

Returns:



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/runar/sdk/contract.rb', line 166

def call(method_name, args = [], provider = nil, signer = nil, options = nil)
  provider = resolve_provider(provider, 'call')
  signer   = resolve_signer(signer, 'call')

  prepared   = prepare_call(method_name, args, provider, signer, options)
  signatures = {}
  prepared.sig_indices.each do |idx|
    subscript = prepared.contract_utxo.script
    if prepared.is_stateful && prepared.code_sep_idx >= 0
      trim_pos  = (prepared.code_sep_idx + 1) * 2
      subscript = subscript[trim_pos..] if trim_pos <= subscript.length
    end
    signatures[idx] = signer.sign(
      prepared.tx_hex, 0,
      subscript,
      prepared.contract_utxo.satoshis
    )
  end

  finalize_call(prepared, signatures, provider)
end

#connect(provider, signer) ⇒ Object

Store provider and signer for use by subsequent deploy/call invocations.

Parameters:



87
88
89
90
# File 'lib/runar/sdk/contract.rb', line 87

def connect(provider, signer)
  @provider = provider
  @signer   = signer
end

#deploy(provider = nil, signer = nil, options = nil) ⇒ Array(String, TransactionData)

Deploy the contract to the blockchain.

Builds the locking script (code + optional state), selects UTXOs, constructs and signs the transaction, broadcasts it, and begins tracking the contract UTXO.

Parameters:

  • provider (Provider, nil) (defaults to: nil)

    overrides connected provider

  • signer (Signer, nil) (defaults to: nil)

    overrides connected signer

  • options (DeployOptions, nil) (defaults to: nil)

    deployment parameters

Returns:



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/runar/sdk/contract.rb', line 102

def deploy(provider = nil, signer = nil, options = nil)
  provider = resolve_provider(provider, 'deploy')
  signer   = resolve_signer(signer, 'deploy')
  opts     = options || DeployOptions.new

  address        = signer.get_address
  change_address = opts.change_address.to_s.empty? ? address : opts.change_address
  locking_script = get_locking_script

  fee_rate  = provider.get_fee_rate
  all_utxos = provider.get_utxos(address)

  raise "RunarContract.deploy: no UTXOs found for #{address}" if all_utxos.empty?

  utxos         = SDK.select_utxos(all_utxos, opts.satoshis, locking_script.length / 2, fee_rate: fee_rate)
  change_script = SDK.build_p2pkh_script(change_address)

  tx_hex, input_count = SDK.build_deploy_transaction(
    locking_script, utxos, opts.satoshis, change_address, change_script, fee_rate: fee_rate
  )

  # Sign all P2PKH funding inputs.
  signed_tx = tx_hex
  pub_key   = signer.get_public_key
  input_count.times do |i|
    utxo      = utxos[i]
    sig       = signer.sign(signed_tx, i, utxo.script, utxo.satoshis)
    unlock    = State.encode_push_data(sig) + State.encode_push_data(pub_key)
    signed_tx = SDK.insert_unlocking_script(signed_tx, i, unlock)
  end

  txid = provider.broadcast(signed_tx)

  @current_utxo = Utxo.new(
    txid: txid, output_index: 0,
    satoshis: opts.satoshis, script: locking_script
  )

  tx = begin
    provider.get_transaction(txid)
  rescue StandardError
    TransactionData.new(
      txid: txid, version: 1,
      outputs: [TxOutput.new(satoshis: opts.satoshis, script: locking_script)],
      raw: signed_tx
    )
  end

  [txid, tx]
end

#finalize_call(prepared, signatures, provider = nil) ⇒ Array(String, TransactionData)

Complete a prepared call by injecting external signatures and broadcasting.

rubocop:disable Metrics/MethodLength

Parameters:

  • prepared (PreparedCall)

    result of prepare_call

  • signatures (Hash<Integer, String>)

    map from arg index to hex signature

  • provider (Provider, nil) (defaults to: nil)

    overrides connected provider

Returns:



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/runar/sdk/contract.rb', line 401

def finalize_call(prepared, signatures, provider = nil)
  provider = resolve_provider(provider, 'finalize_call')

  resolved_args = prepared.resolved_args.dup
  prepared.sig_indices.each { |idx| resolved_args[idx] = signatures[idx] if signatures.key?(idx) }

  primary_unlock = assemble_primary_unlock(prepared, resolved_args)
  final_tx       = SDK.insert_unlocking_script(prepared.tx_hex, 0, primary_unlock)
  txid           = provider.broadcast(final_tx)

  update_tracked_utxo(txid, prepared)

  tx = begin
    provider.get_transaction(txid)
  rescue StandardError
    TransactionData.new(txid: txid, version: 1, raw: final_tx)
  end

  [txid, tx]
end

#get_locking_scriptString

Return the full locking script hex (code script + optional OP_RETURN + state).

Returns:

  • (String)


470
471
472
473
474
475
476
477
478
479
# File 'lib/runar/sdk/contract.rb', line 470

def get_locking_script
  script = @code_script.empty? ? build_code_script : @code_script

  unless @artifact.state_fields.empty?
    state_hex = State.serialize_state(@artifact.state_fields, @state)
    script    = "#{script}6a#{state_hex}" unless state_hex.empty? # OP_RETURN
  end

  script
end

#get_stateHash

Return a copy of the current state.

Returns:

  • (Hash)


531
532
533
# File 'lib/runar/sdk/contract.rb', line 531

def get_state
  @state.dup
end

#get_utxoUtxo?

Return the UTXO currently tracked by this contract, or nil if not deployed.

Returns:



79
80
81
# File 'lib/runar/sdk/contract.rb', line 79

def get_utxo
  @current_utxo
end

#prepare_call(method_name, args = [], provider = nil, signer = nil, options = nil) ⇒ PreparedCall

Prepare a method call without signing the primary contract input’s Sig params. Returns a PreparedCall struct for use with finalize_call.

P2PKH funding inputs ARE signed. Only the primary contract input’s Sig params are left as 72-byte placeholders.

rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

Parameters:

  • method_name (String)
  • args (Array, nil) (defaults to: [])
  • provider (Provider, nil) (defaults to: nil)
  • signer (Signer, nil) (defaults to: nil)
  • options (CallOptions, nil) (defaults to: nil)

Returns:



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/runar/sdk/contract.rb', line 201

def prepare_call(method_name, args = [], provider = nil, signer = nil, options = nil)
  provider = resolve_provider(provider, 'prepare_call')
  signer   = resolve_signer(signer, 'prepare_call')
  args     = Array(args)

  method = find_method(method_name)
  unless method
    raise ArgumentError,
          "RunarContract.prepare_call: method '#{method_name}' not found in #{@artifact.contract_name}"
  end

  is_stateful = !@artifact.state_fields.empty?

  method_needs_change     = method.params.any? { |p| p.name == '_changePKH' }
  method_needs_new_amount = method.params.any? { |p| p.name == '_newAmount' }

  user_params = if is_stateful
                  method.params.reject do |p|
                    p.type == 'SigHashPreimage' ||
                      p.name == '_changePKH' ||
                      p.name == '_changeAmount' ||
                      p.name == '_newAmount'
                  end
                else
                  method.params
                end

  if user_params.length != args.length
    raise ArgumentError,
          "RunarContract.prepare_call: method '#{method_name}' expects " \
          "#{user_params.length} args, got #{args.length}"
  end

  unless @current_utxo
    raise 'RunarContract.prepare_call: contract is not deployed. Call deploy() or from_txid() first.'
  end

  contract_utxo = Utxo.new(
    txid: @current_utxo.txid, output_index: @current_utxo.output_index,
    satoshis: @current_utxo.satoshis, script: @current_utxo.script
  )
  address        = signer.get_address
  opts           = options || CallOptions.new
  change_address = opts.change_address.to_s.empty? ? address : opts.change_address

  extra_input_count = Array(opts.additional_contract_inputs).length
  estimated_inputs  = 1 + extra_input_count + 1
  resolved_args, sig_indices, preimage_index, prevouts_indices =
    resolve_method_args(args, user_params, signer, estimated_inputs: estimated_inputs)

  needs_op_push_tx    = preimage_index >= 0 || is_stateful
  method_selector_hex = compute_method_selector(method_name, is_stateful)
  code_sep_idx        = get_code_sep_index(find_method_index(method_name))

  change_pkh_hex = compute_change_pkh(signer, is_stateful, method_needs_change)

  # Auto-compute new state via ANF interpreter when artifact has ANF IR and
  # no explicit new_state was provided. This mirrors the Python SDK behavior:
  # compute_new_state is called here (where method_name and args are available),
  # not in build_continuation (which has neither).
  if is_stateful && @artifact.anf && opts.new_state.nil?
    named_args = build_named_args(user_params, resolved_args)
    opts = opts.dup
    opts.new_state = ANFInterpreter.compute_new_state(
      @artifact.anf, method_name, @state, named_args
    )
  end

  # Terminal call path: build a transaction with exact outputs, no funding inputs.
  if opts.terminal_outputs && !opts.terminal_outputs.empty?
    return prepare_terminal(
      method_name, resolved_args, signer, opts,
      is_stateful, needs_op_push_tx, method_needs_change,
      sig_indices, preimage_index,
      method_selector_hex, change_pkh_hex, contract_utxo, code_sep_idx
    )
  end

  # Multi-output path: build contract_outputs from opts.outputs when present.
  # Single-output path: fall through to build_continuation.
  has_multi_output = is_stateful && opts.outputs && !Array(opts.outputs).empty?
  contract_outputs = nil
  new_locking_script = ''
  new_satoshis = 0

  if has_multi_output
    code_script = @code_script.empty? ? build_code_script : @code_script
    contract_outputs = Array(opts.outputs).map do |out_spec|
      state_dict = out_spec.is_a?(OutputSpec) ? out_spec.state : (out_spec['state'] || out_spec[:state])
      sats = out_spec.is_a?(OutputSpec) ? out_spec.satoshis : (out_spec['satoshis'] || out_spec[:satoshis] || 1)
      state_hex = State.serialize_state(@artifact.state_fields, state_dict)
      { script: "#{code_script}6a#{state_hex}", satoshis: sats }
    end
  else
    new_locking_script, new_satoshis = build_continuation(is_stateful, opts)
  end

  # Normalise additional contract inputs to Utxo objects.
  extra_contract_utxos = Array(opts.additional_contract_inputs).map do |item|
    case item
    when Utxo then item
    when Hash
      Utxo.new(
        txid: item[:txid] || item['txid'],
        output_index: item[:output_index] || item['output_index'],
        satoshis: item[:satoshis] || item['satoshis'],
        script: item[:script] || item['script']
      )
    else item
    end
  end

  # Resolve per-input args for additional contract inputs.
  raw_per_input_args = Array(opts.additional_contract_input_args)
  resolved_per_input_args = extra_contract_utxos.each_with_index.map do |_, i|
    input_args = (raw_per_input_args[i] || resolved_args).dup
    user_params.each_with_index do |param, j|
      case param.type
      when 'Sig'    then input_args[j] = '00' * 72 if input_args[j].nil?
      when 'PubKey' then input_args[j] = signer.get_public_key if input_args[j].nil?
      end
    end
    input_args
  end

  fee_rate          = provider.get_fee_rate
  change_script     = SDK.build_p2pkh_script(change_address)
  all_funding_utxos = provider.get_utxos(address)
  additional_utxos  = all_funding_utxos.reject do |u|
    u.txid == @current_utxo.txid && u.output_index == @current_utxo.output_index
  end

  unlocking_script = if needs_op_push_tx
                       build_stateful_prefix('00' * 72, method_needs_change) +
                         build_unlocking_script(method_name, resolved_args)
                     else
                       build_unlocking_script(method_name, resolved_args)
                     end

  # Build placeholder unlocking scripts for extra contract inputs.
  extra_unlock_placeholders = extra_contract_utxos.each_with_index.map do |_, i|
    args_for_placeholder = resolved_per_input_args[i] || resolved_args
    build_stateful_prefix('00' * 72, method_needs_change) +
      build_unlocking_script(method_name, args_for_placeholder)
  end

  call_options = {}
  call_options[:contract_outputs] = contract_outputs if contract_outputs
  if extra_contract_utxos.any?
    call_options[:additional_contract_inputs] = extra_contract_utxos.each_with_index.map do |utxo, i|
      { utxo: utxo, unlocking_script: extra_unlock_placeholders[i] }
    end
  end

  tx_hex, _input_count, change_amount = SDK.build_call_transaction(
    contract_utxo, unlocking_script, new_locking_script,
    new_satoshis, change_address, change_script,
    additional_utxos.empty? ? nil : additional_utxos,
    fee_rate: fee_rate,
    options: call_options.empty? ? nil : call_options
  )

  p2pkh_start_idx = 1 + extra_contract_utxos.length
  signed_tx = sign_funding_inputs(tx_hex, additional_utxos, signer, p2pkh_start_idx)

  signed_tx, change_amount, final_op_push_tx_sig, final_preimage =
    compute_preimage_passes(
      signed_tx, contract_utxo, resolved_args, sig_indices,
      method_name, method_needs_change, method_needs_new_amount,
      change_pkh_hex, method_selector_hex, code_sep_idx,
      change_amount, new_satoshis, new_locking_script,
      change_address, change_script, additional_utxos, fee_rate, signer,
      is_stateful, needs_op_push_tx, preimage_index,
      contract_outputs: contract_outputs,
      extra_contract_utxos: extra_contract_utxos,
      resolved_per_input_args: resolved_per_input_args,
      prevouts_indices: prevouts_indices
    )

  sighash = final_preimage.empty? ? '' : Digest::SHA256.hexdigest([final_preimage].pack('H*'))

  build_prepared_call(
    sighash, final_preimage, final_op_push_tx_sig, signed_tx,
    sig_indices, method_name, resolved_args, method_selector_hex,
    is_stateful, needs_op_push_tx, method_needs_change, change_pkh_hex,
    change_amount, method_needs_new_amount, new_satoshis, preimage_index,
    contract_utxo, new_locking_script, code_sep_idx,
    has_multi_output: has_multi_output,
    contract_outputs: contract_outputs || []
  )
end

#set_state(new_state) ⇒ Object

Update state values directly (useful for testing).

Parameters:

  • new_state (Hash)


538
539
540
# File 'lib/runar/sdk/contract.rb', line 538

def set_state(new_state)
  @state.merge!(new_state)
end