#!/usr/bin/env bash set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" SKILL_ROOT="$(dirname "$SCRIPT_DIR")" source "$SCRIPT_DIR/_common.sh" : "${BTC_NETWORK:=testnet}" : "${BTC_FEE_RATE:=5}" : "${OP_RETURN_PREFIX:=VM}" : "${LABEL:=btc-anchor}" main() { confirm_gate flag="$(net_flag)" mkdir -p "$SKILL_ROOT/outputs/runs" ts="$(date -Iseconds | tr ':' '-')" run_dir="$SKILL_ROOT/outputs/runs/${LABEL}_${ts}" mkdir -p "$run_dir" root_hex="$(read_root_hex)" echo "$root_hex" > "$run_dir/root_hex.txt" prefix_hex="$(ascii_to_hex "$OP_RETURN_PREFIX")" payload="${prefix_hex}${root_hex}" payload="${payload:0:160}" echo "$payload" > "$run_dir/op_return_hex.txt" # 1) create raw tx with single OP_RETURN output (no inputs yet) raw="$(bitcoin-cli $flag createrawtransaction "[]" "{\"data\":\"$payload\"}")" # 2) fund via PSBT funded="$(bitcoin-cli $flag walletcreatefundedpsbt "[]" "{\"data\":\"$payload\"}" 0 "{\"fee_rate\":$BTC_FEE_RATE}")" psbt="$(echo "$funded" | jq -r '.psbt')" [[ -n "$psbt" && "$psbt" != "null" ]] || die "walletcreatefundedpsbt did not return psbt" # 3) process (sign) psbt processed="$(bitcoin-cli $flag walletprocesspsbt "$psbt")" psbt2="$(echo "$processed" | jq -r '.psbt')" # 4) finalize finalized="$(bitcoin-cli $flag finalizepsbt "$psbt2")" hex="$(echo "$finalized" | jq -r '.hex')" complete="$(echo "$finalized" | jq -r '.complete')" [[ "$complete" == "true" ]] || die "finalizepsbt not complete" echo "$hex" > "$run_dir/rawtx.hex" # 5) send txid="$(bitcoin-cli $flag sendrawtransaction "$hex")" [[ -n "$txid" ]] || die "Failed to send tx" echo "$txid" > "$run_dir/txid.txt" # proof cat > "$run_dir/PROOF.json" < "$SKILL_ROOT/outputs/last_run_dir.txt" log_info "Anchored on BTC ($BTC_NETWORK). txid=$txid" log_info "Run dir: $run_dir" } main "$@"