Repository navigation
Expand file tree
/
Copy patheject-examples
More file actions
executable file
·443 lines (380 loc) · 14 KB
/
Copy patheject-examples
File metadata and controls
executable file
·443 lines (380 loc) · 14 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
#!/usr/bin/env bash
#
# eject-examples — create standalone sbt projects from Scalus examples.
#
# Usage:
# ./eject-examples --all <target-dir>
# ./eject-examples --only <name> [<name> ...] <target-dir>
# ./eject-examples --list
#
# Each ejected project is a self-contained sbt build that depends on published
# Scalus artifacts, configures the Scalus compiler plugin, and enables
# ScalusSbtPlugin (so `sbt blueprint` and `sbt deploy` work out of the box).
set -euo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
EXAMPLES_ROOT="$SCRIPT_DIR/scalus-examples/jvm/src/main/scala/scalus/examples"
TESTS_ROOT="$SCRIPT_DIR/scalus-examples/jvm/src/test/scala/scalus/examples"
# Known good version (update on tagged releases).
SCALUS_VERSION="0.18.2"
# Ejected projects target sbt 2.0.0 (where `test` is cached and `testFull` runs
# uncached, like sbt 1.x `test`). Pinned independently of the monorepo, which
# still builds on sbt 1.x — so we must NOT read it from project/build.properties.
SBT_VERSION="2.0.0"
SCALA_VERSION="3.3.8"
EXCLUDED_EXAMPLES="cape setbench buidlerfest linkedlist bilinearAccumulator platform"
# Examples that need sources from other examples bundled in.
# Format: "example:dep1,dep2"
BUNDLED_DEPS="storage:linkedlist"
usage() {
cat <<EOF
Usage:
$(basename "$0") [--scalus-version V] --all <target-dir>
$(basename "$0") [--scalus-version V] --only <name> [<name> ...] <target-dir>
$(basename "$0") --list
Options:
--scalus-version Override the Scalus version pinned in the generated project.
Default: \`val scalusStableVersion\` from build.sbt.
Use a locally-published SNAPSHOT (e.g. from \`sbtn publishLocal\`)
when the target version isn't on Maven Central yet.
--all Eject every directory-based example.
--only NAMES... Eject only the named examples (last arg is target dir).
--list Print all available examples and exit.
Each example becomes <target-dir>/<kebab-name>/scalus/ with its own build.sbt,
project/, sources, tests, and README.
EOF
}
list_examples() {
find "$EXAMPLES_ROOT" -mindepth 1 -maxdepth 1 -type d \
-exec basename {} \; | sort | while IFS= read -r name; do
case " $EXCLUDED_EXAMPLES " in
*" $name "*) ;;
*) echo "$name" ;;
esac
done
}
# Maps source directory names to kebab-case output names
# (matching the Cardano Foundation convention).
kebab_name() {
local name="$1"
case "$name" in
amm) echo "constant-product-amm" ;;
anonymousdata) echo "anonymous-data" ;;
atomictransactions) echo "atomic-transaction" ;;
crowdfunding) echo "crowdfund" ;;
decentralizedidentity) echo "decentralized-identity" ;;
editablenft) echo "editable-nft" ;;
paymentsplitter) echo "payment-splitter" ;;
simpletransfer) echo "simple-transfer" ;;
simplewallet) echo "simple-wallet" ;;
upgradeableproxy) echo "upgradable-proxy" ;;
*) echo "$name" ;;
esac
}
# ---- generators -------------------------------------------------------------
detect_extra_deps() {
local src_dir="$1"
local test_dir="$2"
local extras=()
local scan_dirs=("$src_dir")
if [[ -d "$test_dir" ]]; then
scan_dirs+=("$test_dir")
fi
for d in "${scan_dirs[@]}"; do
if grep -rqE '^[[:space:]]*import[[:space:]]+scalus\.bloxbean' "$d" 2>/dev/null; then
extras+=( '"org.scalus" %% "scalus-bloxbean-cardano-client-lib" % scalusVersion' )
break
fi
done
for d in "${scan_dirs[@]}"; do
if grep -rqE '^[[:space:]]*import[[:space:]]+scalus\.patterns' "$d" 2>/dev/null; then
extras+=( '"org.scalus" %% "scalus-design-patterns" % scalusVersion' )
break
fi
done
if (( ${#extras[@]} )); then
printf '%s\n' "${extras[@]}"
fi
}
gen_snapshot_resolver() {
if [[ "$SCALUS_VERSION" == *SNAPSHOT* ]]; then
cat <<'BLOCK'
// TODO: switch to a released version and remove this resolver
resolvers += "Sonatype Central Snapshots" at "https://central.sonatype.com/repository/maven-snapshots/"
BLOCK
fi
}
gen_build_sbt() {
local name="$1" src_dir="$2" test_dir="$3"
local extras
extras="$(detect_extra_deps "$src_dir" "$test_dir")"
local extra_lines=""
if [[ -n "$extras" ]]; then
while IFS= read -r dep; do
extra_lines+=",
$dep"
done <<< "$extras"
fi
cat <<EOF
ThisBuild / scalaVersion := "$SCALA_VERSION"
ThisBuild / organization := "org.scalus.examples"
ThisBuild / version := "0.1.0-SNAPSHOT"
$(gen_snapshot_resolver)
val scalusVersion = "$SCALUS_VERSION"
lazy val root = (project in file("."))
.enablePlugins(ScalusSbtPlugin)
.settings(
name := "$name",
scalacOptions ++= Seq("-deprecation", "-feature"),
libraryDependencies ++= Seq(
"org.scalus" %% "scalus" % scalusVersion,
"org.scalus" %% "scalus-cardano-ledger" % scalusVersion,
"org.scalus" %% "scalus-testkit" % scalusVersion % Test,
"org.scalatest" %% "scalatest" % "3.2.20" % Test$extra_lines
),
addCompilerPlugin(
("org.scalus" %% "scalus-plugin" % scalusVersion).cross(CrossVersion.full)
),
Compile / sources := {
val base = baseDirectory.value
val testDir = base / "test"
val targetDir = target.value
(base ** "*.scala").get()
.filterNot(f => f.relativeTo(testDir).isDefined)
.filterNot(f => f.relativeTo(targetDir).isDefined)
.toSeq
},
Test / sources := ((baseDirectory.value / "test") ** "*.scala")
.get()
.toSeq,
)
EOF
}
gen_plugins_sbt() {
cat <<EOF
$(gen_snapshot_resolver)
addSbtPlugin("org.scalus" % "scalus-sbt-plugin" % "$SCALUS_VERSION")
EOF
}
gen_build_properties() {
cat <<EOF
sbt.version=$SBT_VERSION
EOF
}
gen_gitignore() {
cat <<'EOF'
target/
project/target/
project/project/
.bsp/
.bloop/
.metals/
.idea/
.vscode/
EOF
}
gen_getting_started() {
local name="$1"
cat <<EOF
# Getting Started
Standalone Scalus example, also available in the [scalus3/scalus](https://github.com/scalus3/scalus) monorepo.
Set up your Scala 3 Development environment: https://scalus.org/docs/get-started#install-scala-3-development-environment
## Build
Compile the on-chain and off-chain sources:
\`\`\`sh
sbt compile
\`\`\`
## Test
Run all tests (unit + integration; uses the emulator backend).
\`\`\`sh
sbt test
\`\`\`
Test backends:
\`\`\`sh
sbt test # in-memory emulator (the default)
SCALUS_TEST_ENV=emulator sbt test # in-memory emulator, named explicitly
SCALUS_TEST_ENV=yaci sbt test # a local Yaci DevKit node (auto-started; requires Docker)
\`\`\`
## Profiling
Run the tests with on-chain execution profiling enabled. It writes an interactive HTML report (CPU and memory budget per source line) to target/profile.html
\`\`\`sh
SCALUS_PROFILE=1 sbt test
\`\`\`
## CIP-57 blueprints
\`sbt package\` embeds a CIP-57 blueprint JSON for every Contract in the JAR at
\`META-INF/scalus/blueprints/<Contract>.json\`. Run \`sbt blueprint\` to generate
without packaging — output goes to
\`target/scala-$SCALA_VERSION/resource_managed/main/META-INF/scalus/blueprints/<Contract>.json\`.
Skip generation during \`package\` with \`blueprint / skip := true\` or \`SCALUS_SKIP_BLUEPRINT=1\`.
## Deploy as a reference script
Requires a Blockfrost project id and a funded wallet mnemonic on the chosen network.
\`\`\`sh
sbt "deploy <ContractName> --network preview \\
--blockfrost-key <project-id> \\
--mnemonic '<24 words>'"
\`\`\`
Or via environment variables:
\`\`\`sh
export CARDANO_NETWORK=preview
export BLOCKFROST_API_KEY=<project-id>
export CARDANO_MNEMONIC='<24 words>'
sbt "deploy <ContractName>"
\`\`\`
The contract is deployed as a reference script UTxO at the sender's own base
address; the transaction hash is printed on success.
## Pinned versions
- Scalus: \`$SCALUS_VERSION\`
- Scala: \`$SCALA_VERSION\`
- sbt: \`$SBT_VERSION\`
EOF
}
# Portable in-place sed: plain POSIX sed + temp file. Avoids the `-i` flavor
# difference (BSD/macOS needs a backup-suffix arg, GNU must not have one), so no
# perl dependency and no flag detection — works on BSD, GNU, busybox alike.
sed_i() {
local script="$1"; shift
local f tmp
for f in "$@"; do
tmp="$(mktemp "${TMPDIR:-/tmp}/eject.XXXXXX")"
sed "$script" "$f" > "$tmp" && mv "$tmp" "$f"
done
}
# Rewrites package declarations: scalus.examples.X -> X
rewrite_packages() {
local dir="$1"
while IFS= read -r -d '' f; do
# Strip the scalus.examples. prefix everywhere — package/import lines AND
# inline fully-qualified references (e.g. d.to[scalus.examples.pricebet.OracleState]).
sed_i 's/scalus\.examples\.//g' "$f"
done < <(find "$dir" -name '*.scala' -print0)
}
# Returns bundled dependency names for an example, if any.
get_bundled_deps() {
local name="$1"
for entry in $BUNDLED_DEPS; do
local key="${entry%%:*}"
local deps="${entry#*:}"
if [[ "$key" == "$name" ]]; then
echo "$deps" | tr ',' ' '
return
fi
done
}
# ---- core -------------------------------------------------------------------
eject_one() {
local name="$1" target_root="$2"
local src_dir="$EXAMPLES_ROOT/$name"
local test_dir="$TESTS_ROOT/$name"
if [[ ! -d "$src_dir" ]]; then
echo "error: example '$name' not found at $src_dir" >&2
return 1
fi
local out_name
out_name="$(kebab_name "$name")"
local project_dir="$target_root/$out_name"
if [[ -e "$project_dir" ]]; then
echo "error: $project_dir already exists, refusing to overwrite" >&2
return 1
fi
mkdir -p "$project_dir/project"
# Copy main sources (flat, next to build.sbt)
find "$src_dir" -maxdepth 1 -name '*.scala' -exec cp {} "$project_dir/" \;
# Copy bundled dependency sources into their own package dirs.
# Only the dependency's MAIN sources are bundled (the example's own code needs
# them to compile); its tests are intentionally NOT copied — they belong to the
# dependency, not to this example, and would otherwise run under the example's
# `sbt test` (e.g. storage pulling in LinkedListTest).
local deps
deps="$(get_bundled_deps "$name")"
if [[ -n "$deps" ]]; then
for dep in $deps; do
local dep_src="$EXAMPLES_ROOT/$dep"
if [[ -d "$dep_src" ]]; then
mkdir -p "$project_dir/$dep"
find "$dep_src" -maxdepth 1 -name '*.scala' -exec cp {} "$project_dir/$dep/" \;
fi
done
fi
# Copy test sources
if [[ -d "$test_dir" ]]; then
mkdir -p "$project_dir/test"
find "$test_dir" -maxdepth 1 -name '*.scala' -exec cp {} "$project_dir/test/" \;
fi
# Rewrite package declarations
rewrite_packages "$project_dir"
# Generate build files
gen_build_sbt "$out_name" "$src_dir" "$test_dir" > "$project_dir/build.sbt"
gen_plugins_sbt > "$project_dir/project/plugins.sbt"
gen_build_properties > "$project_dir/project/build.properties"
gen_gitignore > "$project_dir/.gitignore"
gen_getting_started "$out_name" > "$project_dir/GETTING_STARTED.md"
# Copy the example's own README if it exists
if [[ -f "$src_dir/README.md" ]]; then
cp "$src_dir/README.md" "$project_dir/README.md"
fi
echo " ejected $name -> $project_dir"
}
main() {
if [[ $# -eq 0 ]]; then usage; exit 1; fi
# Parse flags in any order; collect positional args.
local mode=""
local positional=()
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help) usage; exit 0 ;;
--list) mode="list"; shift ;;
--all) mode="all"; shift ;;
--only) mode="only"; shift ;;
--scalus-version)
if [[ $# -lt 2 ]]; then
echo "error: --scalus-version requires a value" >&2; exit 1
fi
SCALUS_VERSION="$2"; shift 2 ;;
--*)
echo "error: unknown option '$1'" >&2; usage; exit 1 ;;
*)
positional+=( "$1" ); shift ;;
esac
done
if [[ -d "$EXAMPLES_ROOT" ]]; then :; else
echo "error: examples root not found: $EXAMPLES_ROOT" >&2
exit 1
fi
local failures=0
case "$mode" in
list)
while IFS= read -r name; do
printf "%-25s -> %s\n" "$name" "$(kebab_name "$name")"
done < <(list_examples) ;;
all)
if [[ ${#positional[@]} -ne 1 ]]; then
echo "error: --all takes exactly one argument: <target-dir>" >&2
exit 1
fi
local target="${positional[0]}"
mkdir -p "$target"
echo "ejecting all examples to $target (scalus $SCALUS_VERSION)"
while IFS= read -r name; do
eject_one "$name" "$target" || failures=$((failures + 1))
done < <(list_examples)
;;
only)
if [[ ${#positional[@]} -lt 2 ]]; then
echo "error: --only requires at least one example name and a target dir" >&2
exit 1
fi
local target="${positional[${#positional[@]}-1]}"
local names=( "${positional[@]:0:${#positional[@]}-1}" )
mkdir -p "$target"
echo "ejecting ${#names[@]} example(s) to $target (scalus $SCALUS_VERSION)"
for name in "${names[@]}"; do
eject_one "$name" "$target" || failures=$((failures + 1))
done
;;
"")
usage; exit 1 ;;
esac
if [[ $failures -gt 0 ]]; then
echo "done with $failures failure(s); see messages above" >&2
fi
}
main "$@"