-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmetadata-create.sh
More file actions
executable file
·714 lines (620 loc) · 23.9 KB
/
Copy pathmetadata-create.sh
File metadata and controls
executable file
·714 lines (620 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
#!/bin/bash
##################################################
# Default configuration values
INTERSECT_SCHEMAS_BASE="https://intersectmbo.github.io/governance-actions/v1.2.0/schemas"
resolve_context_url() {
case "$1" in
info) echo "${INTERSECT_SCHEMAS_BASE}/info/common.jsonld" ;;
treasury) echo "${INTERSECT_SCHEMAS_BASE}/treasury-withdrawals/common.jsonld" ;;
ppu) echo "${INTERSECT_SCHEMAS_BASE}/parameter-changes/common.jsonld" ;;
hf) echo "${INTERSECT_SCHEMAS_BASE}/hard-fork-initiation/common.jsonld" ;;
committee) echo "${INTERSECT_SCHEMAS_BASE}/update-committee/common.jsonld" ;;
*) print_fail "No @context mapping for --governance-action-type '$1'"; exit 1 ;;
esac
}
##################################################
# Exit immediately if a command exits with a non-zero status,
# treat unset variables as an error, and fail if any command in a pipeline fails
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/messages.sh
source "$SCRIPT_DIR/lib/messages.sh"
# Check if pandoc cli is installed
if ! command -v pandoc >/dev/null 2>&1; then
print_fail "pandoc is not installed or not in your PATH."
exit 1
fi
# Check if cardano-cli is installed (required to query the governance action deposit from chain)
if ! command -v cardano-cli >/dev/null 2>&1; then
print_fail "cardano-cli is not installed or not in your PATH. It is required to query the governance action deposit from the chain."
exit 1
fi
# Usage message
usage() {
printf '%s%sCreate JSON-LD metadata from a Markdown file%s\n\n' "$UNDERLINE" "$BOLD" "$NC"
printf 'Syntax:%s %s %s<.md-file> --governance-action-type%s <info|treasury|ppu|hf> %s--deposit-return-addr%s <stake-address> [%s--inline-context%s]\n' "$BOLD" "$0" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC"
print_usage_option "<.md-file>" "Path to the .md file as input"
print_usage_option "--governance-action-type <info|treasury|ppu|hf>" "Type of governance action"
print_usage_option "--deposit-return-addr <stake-address>" "Stake address for deposit return (bech32)"
print_usage_option "[--inline-context]" "Embed the full @context object in the document instead of referencing the URL"
print_usage_option "-h, --help" "Show this help message and exit"
exit 1
}
# Initialize variables with defaults
input_file=""
governance_action_type=""
deposit_return_address=""
inline_context="false"
# Create temporary files in /tmp/
TEMP_MD=$(mktemp /tmp/metadata_create_md.XXXXXX)
TEMP_OUTPUT_JSON=$(mktemp /tmp/metadata_create_temp.XXXXXX)
TEMP_CONTEXT=$(mktemp /tmp/metadata_create_context.XXXXXX)
TEMP_TITLE=$(mktemp /tmp/metadata_create_title.XXXXXX)
TEMP_ABSTRACT=$(mktemp /tmp/metadata_create_abstract.XXXXXX)
TEMP_MOTIVATION=$(mktemp /tmp/metadata_create_motivation.XXXXXX)
TEMP_RATIONALE=$(mktemp /tmp/metadata_create_rationale.XXXXXX)
TEMP_REFERENCES=$(mktemp /tmp/metadata_create_references.XXXXXX)
TEMP_ONCHAIN=$(mktemp /tmp/metadata_create_onchain.XXXXXX)
# Cleanup function to remove temporary files
cleanup() {
rm -f "$TEMP_MD" "$TEMP_OUTPUT_JSON" "$TEMP_CONTEXT" \
"$TEMP_TITLE" "$TEMP_ABSTRACT" "$TEMP_MOTIVATION" \
"$TEMP_RATIONALE" "$TEMP_REFERENCES" "$TEMP_ONCHAIN"
}
# Set trap to cleanup on any script
trap cleanup EXIT
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--governance-action-type)
if [ -n "${2:-}" ]; then
governance_action_type="$2"
shift 2
else
print_fail "--governance-action-type requires a value"
usage
fi
;;
--deposit-return-addr)
if [ -n "${2:-}" ]; then
deposit_return_address="$2"
shift 2
else
print_fail "--deposit-return-addr requires a value"
usage
fi
;;
--inline-context)
inline_context="true"
shift
;;
-h|--help)
usage
;;
*)
if [ -z "$input_file" ]; then
input_file="$1"
else
print_fail "Input file already specified. Unexpected argument: $1"
usage
fi
shift
;;
esac
done
# If no input file provided, show usage
if [ -z "$input_file" ]; then
print_fail "No input file specified"
usage
fi
# Enforce .md extension — the script parses Markdown H2 sections (## Title, ## Abstract, ...)
if [[ "$input_file" != *.md ]]; then
print_fail "Input file $(fmt_path "$input_file") must be a Markdown file with a .md extension."
print_hint "This script expects a Markdown document structured with H2 sections (## Title, ## Abstract, ## Motivation, ## Rationale, ## References, ## Authors)."
exit 1
fi
# Ensure the input file actually exists
if [ ! -f "$input_file" ]; then
print_fail "Input file $(fmt_path "$input_file") not found."
exit 1
fi
# If no governance action type provided, show usage
if [ -z "$governance_action_type" ]; then
print_fail "--governance-action-type is required"
usage
fi
# If no deposit return address provided, show usage
if [ -z "$deposit_return_address" ]; then
print_fail "--deposit-return-addr is required"
usage
fi
# Validate deposit return address as a Bech32 stake address (mainnet or testnet).
# Cardano stake addresses are 53-54 chars after the prefix; we accept any bech32-ish tail
# and let downstream tooling reject malformed payloads.
if [[ ! "$deposit_return_address" =~ ^(stake1|stake_test1)[a-zA-Z0-9]+$ ]]; then
print_fail "--deposit-return-addr must be a Bech32 stake address (e.g. stake1... or stake_test1...). Got: $(fmt_path "$deposit_return_address")"
exit 1
fi
print_banner "Creating a governance action metadata file from a markdown file"
print_info "This script assumes a basic structure for the markdown file, using H2 headers"
print_info "This script uses CIP169 governance metadata extension with CIP-116 ProposalProcedure format"
# Generate output filename: same directory and name as input, but with .jsonld extension
input_dir=$(dirname "$input_file")
input_basename=$(basename "$input_file")
input_name="${input_basename%.*}"
FINAL_OUTPUT_JSON="$input_dir/$input_name.jsonld"
# Copy the markdown file to temp location for processing
cp "$input_file" "$TEMP_MD"
# Clean up escaped characters in markdown
# Usable sed (for macOS + Linux)
portable_sed() {
# If this returns 0, sed is GNU (Linux); if not, it's BSD (macOS)
if sed --version >/dev/null 2>&1; then
# GNU(linux)
sed -E -i "$1" "$2"
else
# BSD(macOS)
sed -E -i '' "$1" "$2"
fi
}
# Remove extra backslashes before special characters that don't need escaping in JSON
portable_sed 's/\\-/-/g' "$TEMP_MD"
portable_sed 's/\\_/_/g' "$TEMP_MD"
portable_sed 's/\\\./\./g' "$TEMP_MD"
portable_sed 's/\\\?/\?/g' "$TEMP_MD"
portable_sed 's/\\\+/\+/g' "$TEMP_MD"
portable_sed 's/\\\^/\^/g' "$TEMP_MD"
portable_sed 's/\\\$/\\$/g' "$TEMP_MD"
# Fix common markdown escaping issues
portable_sed 's/\\\&/\&/g' "$TEMP_MD"
portable_sed 's/\\\#/#/g' "$TEMP_MD"
portable_sed 's/\\\:/:/g' "$TEMP_MD"
portable_sed 's/\\\;/\;/g' "$TEMP_MD"
# Handle asterisks - only remove backslash if not part of markdown formatting
portable_sed 's/\\\*([^*])/\*\1/g' "$TEMP_MD"
extract_section() {
local start="$1"
local next="$2"
awk "/^${start}\$/,/^${next}\$/" "$TEMP_MD" | sed "1d;\$d"
}
get_section() {
local label="$1"
local next="$2"
extract_section "$label" "$next" \
| jq -Rs .
}
get_section_last() {
local label="$1"
awk "/^${label}\$/ {found=1; next} /^## References$/ {found=0} found" "$TEMP_MD" | jq -Rs .
}
# Preflight: every section the schema marks as required must appear as an H2 in the
# Markdown source. Without this, get_section silently returns an empty string and
# downstream validation fails far from the cause.
require_sections() {
local missing=()
local section
for section in "$@"; do
if ! grep -qE "^${section}\$" "$TEMP_MD"; then
missing+=("$section")
fi
done
if [ "${#missing[@]}" -gt 0 ]; then
print_fail "Markdown source is missing required H2 section(s): ${missing[*]}"
print_hint "Each required section must appear on its own line, exactly as: ## Title / ## Abstract / ## Motivation / ## Rationale"
exit 1
fi
}
# Query the current on-chain governance state once. Both the governance action
# deposit (all action types) and the previously enacted parameter-change action
# id (PPUs only) are derived from it, so it is fetched a single time and passed
# around. Aborts if cardano-cli cannot reach a node.
query_gov_state() {
if ! command -v cardano-cli >/dev/null 2>&1 || [ -z "${CARDANO_NODE_SOCKET_PATH:-}" ]; then
print_fail "cardano-cli with a reachable node (CARDANO_NODE_SOCKET_PATH) is required to query chain state" >&2
exit 1
fi
local gov_state
if ! gov_state=$(cardano-cli conway query gov-state 2>/dev/null); then
print_fail "Failed to query governance state (cardano-cli conway query gov-state)" >&2
exit 1
fi
printf '%s' "$gov_state"
}
# Resolve the previously enacted parameter-change (PParamUpdate) governance
# action id
resolve_ppu_prev_gov_action_id() {
local gov_state="$1"
local prev
prev=$(printf '%s' "$gov_state" \
| jq '.nextRatifyState.nextEnactState.prevGovActionIds.PParamUpdate')
if [ -z "$prev" ]; then
print_fail "Could not read prevGovActionIds.PParamUpdate from gov-state (cardano-cli output may have changed)" >&2
exit 1
fi
if [ "$prev" = "null" ]; then
print_warn "No previously enacted parameter-change action on chain; gov_action_id will be null" >&2
printf 'null'
return 0
fi
# Reshape ledger {txId, govActionIx} into CIP-116 {transaction_id, gov_action_index}.
local reshaped
reshaped=$(printf '%s' "$prev" \
| jq '{ transaction_id: .txId, gov_action_index: (.govActionIx | tostring) }')
print_pass "Resolved previous parameter-change gov_action_id: $(printf '%s' "$reshaped" | jq -c .)" >&2
printf '%s' "$reshaped"
}
# Resolve the guardrails script hash used as the on-chain
resolve_policy_hash() {
local script_hash=""
if command -v cardano-cli >/dev/null 2>&1 && [ -n "${CARDANO_NODE_SOCKET_PATH:-}" ]; then
script_hash=$(cardano-cli conway query constitution 2>/dev/null | jq -r '.script // empty') || script_hash=""
fi
if [ -n "$script_hash" ] && [ "$script_hash" != "null" ]; then
print_pass "Resolved constitution script hash (policy_hash): ${script_hash}" >&2
else
print_fail "policy_hash is required for this governance action type, couldn't be resolved from cardano-cli" >&2
exit 1
fi
printf '%s' "$script_hash"
}
# Resolve the governance action deposit (in lovelace) from the supplied gov-state
resolve_gov_action_deposit() {
local gov_state="$1"
local deposit
deposit=$(printf '%s' "$gov_state" | jq -r '.currentPParams.govActionDeposit // empty')
if [[ "$deposit" =~ ^[0-9]+$ ]]; then
print_pass "Resolved governance action deposit from chain: ${deposit} lovelace" >&2
else
print_fail "governance action deposit couldn't be read from gov-state (.currentPParams.govActionDeposit)" >&2
exit 1
fi
printf '%s' "$deposit"
}
# Extract references from References section
extract_references() {
awk '
BEGIN {
in_refs = 0
ref_count = 0
}
/^## References$/ { in_refs = 1; next }
/^## Authors$/ { in_refs = 0; next }
in_refs {
# Skip empty lines
if ($0 ~ /^\s*$/) next
# Check for markdown link format: * [label](url)
if ($0 ~ /^\* \[.*\]\(.*\)/) {
# Extract label from markdown link [label](url)
label = $0
sub(/^\* \[/, "", label)
sub(/\]\(.*\).*$/, "", label)
# Extract URL from markdown link
uri = $0
sub(/^.*\(/, "", uri)
sub(/\).*$/, "", uri)
# Clean up quotes in label and URI
gsub(/"/, "\\\"", label)
gsub(/"/, "\\\"", uri)
# Add reference
refs[ref_count++] = " {\n \"@type\": \"Other\",\n \"label\": \"" label "\",\n \"uri\": \"" uri "\"\n }"
}
}
END {
print " ["
for (i = 0; i < ref_count; i++) {
printf "%s", refs[i]
if (i < ref_count - 1) print ","
else print ""
}
print " ]"
}
' "$TEMP_MD"
}
# Generate onChain property for info governance action (CIP-116 ProposalProcedure format)
generate_info_onchain() {
cat <<EOF
{
"deposit": "$GOV_ACTION_DEPOSIT",
"reward_account": "$deposit_return_address",
"gov_action": {
"tag": "info_action"
}
}
EOF
}
# Generate onChain property for ppu governance action (CIP-116 ProposalProcedure format)
generate_ppu_onchain() {
jq -n \
--arg deposit "$GOV_ACTION_DEPOSIT" \
--arg reward_account "$deposit_return_address" \
--argjson gov_action_id "$PPU_GOV_ACTION_ID" \
--arg policy_hash "$POLICY_HASH" \
'{
deposit: $deposit,
reward_account: $reward_account,
gov_action: {
tag: "parameter_change_action",
gov_action_id: $gov_action_id,
protocol_param_update: {TODO: "Manually fill in the protocol parameters to update here."},
policy_hash: $policy_hash
}
}'
}
treasury_collect_inputs() {
# Prompt & read address from the TTY
printf 'Please enter withdrawal address: ' >&2
IFS= read -r T_WITHDRAWAL_ADDRESS </dev/tty
# Validate address
if [ -z "$T_WITHDRAWAL_ADDRESS" ]; then
print_fail "Withdrawal address cannot be empty"
exit 1
fi
if [[ ! "$T_WITHDRAWAL_ADDRESS" =~ ^(stake1|stake_test1)[a-zA-Z0-9]{50,60}$ ]]; then
print_fail "Invalid bech32 stake address format"
exit 1
fi
print_pass "Withdrawal address valid format!" >&2
# Try to extract amount from TITLE
print_info "Attempting to extract withdrawal amount from metadata title..." >&2
local _title
_title=$(echo "$TITLE" | jq -r . | tr -d '\n')
T_RAW_ADA=$(echo "$_title" | sed -n -E 's/.*[₳]([0-9,]+).*/\1/p')
if [ -z "$T_RAW_ADA" ]; then
T_RAW_ADA=$(echo "$_title" | sed -n -E 's/.* ([0-9,]+) ADA.*/\1/p')
fi
if [ -z "$T_RAW_ADA" ]; then
T_RAW_ADA=$(echo "$_title" | sed -n -E 's/.* ([0-9,]+) ada.*/\1/p')
fi
# If amount not found in title ask the user
if [ -z "$T_RAW_ADA" ]; then
print_warn "No withdrawal amount found in title."
printf 'Please enter withdrawal amount in ada: ' >&2
IFS= read -r T_RAW_ADA </dev/tty
fi
if [ -z "$T_RAW_ADA" ]; then
print_fail "Withdrawal amount cannot be empty"
exit 1
fi
# Convert ADA -> lovelace
local _lovelace
_lovelace=$(echo "$T_RAW_ADA" | tr -d ',' | awk '
BEGIN{ ok=1 }
{
if ($0 !~ /^[0-9]*\.?[0-9]+$/) ok=0;
amt=$0+0;
if (amt<=0) ok=0;
if (ok==1) printf("%.0f", amt*1000000);
}
END{ if (ok==0) exit 1 }')
if [ $? -ne 0 ] || [ -z "$_lovelace" ] || [[ ! "$_lovelace" =~ ^[0-9]+$ ]]; then
print_fail "Invalid withdrawal amount: ${T_RAW_ADA}"
exit 1
fi
T_LOVELACE="$_lovelace"
print_info "Final confirmation:" >&2
print_info " Amount: ${YELLOW}₳${T_RAW_ADA}${NC} (${T_LOVELACE} lovelace)" >&2
print_info " Address: ${YELLOW}${T_WITHDRAWAL_ADDRESS}${NC}" >&2
# confirm with user
if ! confirm "Is this correct?"; then
print_fail "Cancelled by user"
exit 1
fi
}
generate_treasury_onchain() {
# Collect inputs and log to stderr
treasury_collect_inputs
# Emit ONLY JSON to stdout (CIP-116 ProposalProcedure format)
# Convert withdrawals to rewards array with key-value pairs
# POLICY_HASH is resolved at the top level (see "Resolving policy_hash").
cat <<EOF
{
"deposit": "$GOV_ACTION_DEPOSIT",
"reward_account": "$deposit_return_address",
"gov_action": {
"tag": "treasury_withdrawals_action",
"rewards": [
{
"key": "$T_WITHDRAWAL_ADDRESS",
"value": "$T_LOVELACE"
}
],
"policy_hash": "$POLICY_HASH"
}
}
EOF
}
hf_collect_inputs() {
# Major protocol version
printf 'Please enter target major protocol version: ' >&2
IFS= read -r HF_MAJOR </dev/tty
if [[ ! "$HF_MAJOR" =~ ^[0-9]+$ ]]; then
print_fail "Major protocol version must be a non-negative integer. Got: ${HF_MAJOR}"
exit 1
fi
# Minor protocol version (defaults to 0).
printf 'Please enter target minor protocol version [0]: ' >&2
IFS= read -r HF_MINOR </dev/tty
if [ -z "$HF_MINOR" ]; then
HF_MINOR="0"
fi
if [[ ! "$HF_MINOR" =~ ^[0-9]+$ ]]; then
print_fail "Minor protocol version must be a non-negative integer. Got: ${HF_MINOR}"
exit 1
fi
# Previous hard-fork-initiation action ID
printf 'Please enter previous hard fork action transaction id (64 hex chars): ' >&2
IFS= read -r HF_PREV_TX </dev/tty
if [ -z "$HF_PREV_TX" ]; then
print_fail "Previous hard fork action transaction id is required."
exit 1
fi
if [[ ! "$HF_PREV_TX" =~ ^[0-9a-fA-F]{64}$ ]]; then
print_fail "Previous hard fork transaction id must be 64 hex characters. Got: ${HF_PREV_TX}"
exit 1
fi
printf 'Please enter previous hard fork action gov_action_index [0]: ' >&2
IFS= read -r HF_PREV_IDX </dev/tty
if [ -z "$HF_PREV_IDX" ]; then
HF_PREV_IDX="0"
fi
if [[ ! "$HF_PREV_IDX" =~ ^[0-9]+$ ]]; then
print_fail "gov_action_index must be a non-negative integer. Got: ${HF_PREV_IDX}"
exit 1
fi
print_info "Final confirmation:" >&2
print_info " Target protocol version: ${YELLOW}${HF_MAJOR}.${HF_MINOR}${NC}" >&2
print_info " Previous HF action: ${YELLOW}${HF_PREV_TX}#${HF_PREV_IDX}${NC}" >&2
if ! confirm "Is this correct?"; then
print_fail "Cancelled by user"
exit 1
fi
}
generate_hf_onchain() {
# Collect inputs and log to stderr
hf_collect_inputs
# Emit ONLY JSON to stdout (CIP-116 ProposalProcedure format)
jq -n \
--arg deposit "$GOV_ACTION_DEPOSIT" \
--arg reward_account "$deposit_return_address" \
--arg prev_tx "$HF_PREV_TX" \
--arg prev_idx "$HF_PREV_IDX" \
--argjson major "$HF_MAJOR" \
--argjson minor "$HF_MINOR" \
'{
deposit: $deposit,
reward_account: $reward_account,
gov_action: {
tag: "hard_fork_initiation_action",
gov_action_id: { transaction_id: $prev_tx, gov_action_index: $prev_idx },
protocol_version: { major: $major, minor: $minor }
}
}'
}
# Generate onChain property based on governance action type
generate_onchain_property() {
local action_type="$1"
case "$action_type" in
"info")
generate_info_onchain
;;
"treasury")
generate_treasury_onchain
;;
"ppu")
generate_ppu_onchain
;;
"hf")
generate_hf_onchain
;;
*)
echo "null"
;;
esac
}
# use helper functions to extract sections
print_section "Extracting sections from Markdown"
require_sections "## Title" "## Abstract" "## Motivation" "## Rationale"
TITLE=$(get_section "## Title" "## Abstract")
# clean newlines from title
TITLE=$(echo "$TITLE" | jq -r . | tr -d '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | jq -Rs .)
print_info "Title extracted: ${YELLOW}${TITLE}${NC}"
ABSTRACT=$(get_section "## Abstract" "## Motivation")
MOTIVATION=$(get_section "## Motivation" "## Rationale")
RATIONALE=$(get_section_last "## Rationale")
# Resolving policy_hash
# Treasury withdrawals and parameter changes must carry the guardrails
# (constitution) script hash as their on-chain policy_hash. Resolve it here at
# the top level so a failure reliably aborts the script — resolving inside the
# generator (which runs in a command-substitution subshell) would NOT propagate
# the exit, and we'd silently emit metadata with an empty policy_hash.
POLICY_HASH=""
if [ "$governance_action_type" = "treasury" ] || [ "$governance_action_type" = "ppu" ]; then
POLICY_HASH=$(resolve_policy_hash) || exit 1
fi
# Query the on-chain governance state once; the deposit (all action types) and
# the previous parameter-change action id (PPUs only) are derived from it.
print_section "Querying chain governance state"
GOV_STATE=$(query_gov_state) || exit 1
# Resolve the governance action deposit. Required for every action type — aborts
# if it can't be read from chain.
GOV_ACTION_DEPOSIT=$(resolve_gov_action_deposit "$GOV_STATE") || exit 1
# Resolve the previously enacted parameter-change gov_action_id (PPUs only).
# Resolved here at the top level so a failure reliably aborts the script — doing
# it inside the generator (a command-substitution subshell) would not propagate
# the exit.
PPU_GOV_ACTION_ID="null"
if [ "$governance_action_type" = "ppu" ]; then
PPU_GOV_ACTION_ID=$(resolve_ppu_prev_gov_action_id "$GOV_STATE") || exit 1
fi
# Generate onChain property based on governance action type
print_info "Generating onChain property for $governance_action_type"
ONCHAIN_PROPERTY=$(generate_onchain_property "$governance_action_type")
# Generate references JSON
REFERENCES_JSON=$(extract_references)
# Resolve the @context URL for this governance action type.
print_section "Resolving @context URL"
CONTEXT_URL=$(resolve_context_url "$governance_action_type")
print_info "Using @context: ${YELLOW}${CONTEXT_URL}${NC}"
# Stage the @context payload. By default we leave a JSON `null` sentinel in
# TEMP_CONTEXT and the final jq emits the URL string. With --inline-context, we
# fetch the canonical document and write its inner @context object so the final
# jq embeds it verbatim.
if [ "$inline_context" = "true" ]; then
print_info "Inlining @context (fetching ${YELLOW}${CONTEXT_URL}${NC})"
if ! curl -sSfL "$CONTEXT_URL" | jq -e '."@context"' > "$TEMP_CONTEXT"; then
print_fail "Failed to fetch or parse @context from $CONTEXT_URL"
exit 1
fi
else
echo 'null' > "$TEMP_CONTEXT"
fi
# Build the metadata JSON-LD with CIP-116 ProposalProcedure format onChain property
# Write each value to a temp file to avoid "Argument list too long" with large markdown.
# --slurpfile reads the file from disk and binds it as a 1-element array,
# which is why every variable below is dereferenced with [0].
printf '%s' "$TITLE" > "$TEMP_TITLE"
printf '%s' "$ABSTRACT" > "$TEMP_ABSTRACT"
printf '%s' "$MOTIVATION" > "$TEMP_MOTIVATION"
printf '%s' "$RATIONALE" > "$TEMP_RATIONALE"
printf '%s' "$REFERENCES_JSON" > "$TEMP_REFERENCES"
printf '%s' "$ONCHAIN_PROPERTY" > "$TEMP_ONCHAIN"
jq --arg context_url "$CONTEXT_URL" \
--slurpfile context "$TEMP_CONTEXT" \
--slurpfile title "$TEMP_TITLE" \
--slurpfile abstract "$TEMP_ABSTRACT" \
--slurpfile motivation "$TEMP_MOTIVATION" \
--slurpfile rationale "$TEMP_RATIONALE" \
--slurpfile references "$TEMP_REFERENCES" \
--slurpfile onchain "$TEMP_ONCHAIN" \
'{
"@context": (if $context[0] == null then $context_url else $context[0] end),
"authors": [],
"hashAlgorithm": "blake2b-256",
"body": {
"title": $title[0],
"abstract": $abstract[0],
"motivation": $motivation[0],
"rationale": $rationale[0],
"references": $references[0],
"onChain": $onchain[0]
}
}' <<< '{}' > "$TEMP_OUTPUT_JSON"
print_info "Formatting JSON output"
# Use jq to format the JSON output
jq . "$TEMP_OUTPUT_JSON" > "$FINAL_OUTPUT_JSON"
# Clean up extra newlines at start and end of string fields
print_info "Cleaning up extra newlines"
jq '
.body.title = (.body.title | gsub("^\\n+"; "") | gsub("\\n+$"; "")) |
.body.abstract = (.body.abstract | gsub("^\\n+"; "") | gsub("\\n+$"; "")) |
.body.motivation = (.body.motivation | gsub("^\\n+"; "") | gsub("\\n+$"; "")) |
.body.rationale = (.body.rationale | gsub("^\\n+"; "") | gsub("\\n+$"; ""))
' "$FINAL_OUTPUT_JSON" > "$TEMP_OUTPUT_JSON" && mv "$TEMP_OUTPUT_JSON" "$FINAL_OUTPUT_JSON"
print_section "Summary"
print_pass "JSON-LD metadata created"
print_kv "Input" "$(fmt_path "$input_file")"
print_kv "Output" "$(fmt_path "$FINAL_OUTPUT_JSON")"
print_kv "Type" "$governance_action_type"
print_kv "@context" "$CONTEXT_URL"
print_next "Validate the document (still pre-signing, so use --draft):" \
" ./scripts/metadata-validate.sh '$FINAL_OUTPUT_JSON' --cip108 --cip169 --draft"