Repository navigation
515 lines (441 loc) · 18.4 KB
/
Copy pathcontract.yml
File metadata and controls
515 lines (441 loc) · 18.4 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
name: Smart Contract - Build & CI
on:
push:
branches: [ main ]
tags: [ 'v*' ]
pull_request:
branches: [ main ]
# Cancel superseded pull-request runs on the same branch; never cancel a push to
# main or a tag run (those feed releases and the testnet gates below).
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
ci:
name: Contract CI
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Install Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v2
with:
# Soroban builds require wasm32v1-none (setup-rust-toolchain uses singular `target`).
target: wasm32v1-none
# Cache the cargo registry/git and target dir between runs.
cache: true
- name: Install cargo-audit and cargo-deny
run: |
cargo install cargo-audit --locked
cargo install cargo-deny --locked
- name: Run cargo audit
run: |
cargo audit
- name: Run cargo deny
run: |
cargo deny check
- name: Install stellar-cli
uses: stellar/stellar-cli@v28.1.0
- name: Build smart contracts
run: |
# stellar-cli v25+ has no --release flag; release profile is the default.
stellar contract build
- name: Run contract test suite (flat weight fixture)
run: ACCORD_WEIGHT_FIXTURE=flat cargo test --locked -- --nocapture
- name: Run contract test suite (skewed weight fixture)
run: ACCORD_WEIGHT_FIXTURE=skewed cargo test --locked -- --nocapture
- name: Run RBAC tests
run: cargo test --locked -- rbac -- --nocapture
- name: Generate wasm-manifest.json
run: |
python3 <<'PY'
import glob
import hashlib
import json
import os
import re
from datetime import datetime, timezone
wasm_files = sorted(glob.glob("target/wasm32*/release/*.wasm"))
if not wasm_files:
raise SystemExit("No WASM files found after contract build")
# Prefer the Accord contract artifact when multiple WASMs exist.
wasm_path = next(
(p for p in wasm_files if os.path.basename(p) == "accord.wasm"),
wasm_files[0],
)
with open(wasm_path, "rb") as f:
wasm_hash = hashlib.sha256(f.read()).hexdigest()
cargo_toml = open("Cargo.toml", encoding="utf-8").read()
match = re.search(
r'^soroban-sdk\s*=\s*"=?([^"\n]+)"',
cargo_toml,
flags=re.MULTILINE,
)
if not match:
raise SystemExit("Could not read soroban-sdk version from Cargo.toml")
soroban_sdk_version = match.group(1)
# Probed: True if contract source includes feature capability flags
try:
lib_rs = open("contracts/accord/src/lib.rs", encoding="utf-8").read()
supports_recurring_payments = "RecurringPayment" in lib_rs and "disburse_recurring" in lib_rs
supports_rbac = ("GrantRole" in lib_rs and "RevokeRole" in lib_rs) or ("get_roles" in lib_rs and "get_role_version" in lib_rs)
except FileNotFoundError:
supports_recurring_payments = False
supports_rbac = False
manifest = {
"wasm_file": os.path.basename(wasm_path),
"wasm_hash": wasm_hash,
"commit_sha": os.environ.get("GITHUB_SHA", ""),
"build_timestamp": datetime.now(timezone.utc)
.replace(microsecond=0)
.isoformat()
.replace("+00:00", "Z"),
"soroban_sdk_version": soroban_sdk_version,
"supports_recurring_payments": supports_recurring_payments,
"supports_rbac": supports_rbac,
}
with open("wasm-manifest.json", "w", encoding="utf-8") as out:
json.dump(manifest, out, indent=2)
out.write("\n")
print(json.dumps(manifest, indent=2))
PY
- name: Upload compiled WASM artifact
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
uses: actions/upload-artifact@v7
with:
name: accord-contract-wasm
path: |
target/wasm32v1-none/release/*.wasm
target/wasm32*/release/*.wasm
wasm-manifest.json
retention-days: 90
- name: Report WASM file sizes
run: |
python3 -c '
import os, glob
files = glob.glob("target/wasm32*/release/*.wasm")
if not files:
print("No WASM files found in release target directories.")
for f in files:
if os.path.isfile(f):
size_bytes = os.path.getsize(f)
size_kb = size_bytes / 1024.0
print(f"Contract: {os.path.basename(f)} | Size: {size_kb:.2f} KB ({size_bytes} bytes)")
'
# Snapshot verification (#815). Runs the deterministic contract tests and
# reports when the working tree's snapshots differ from the committed ones.
# The report is advisory so an existing stale baseline cannot block every
# pull request; the full patch is uploaded as an artifact. Property tests opt
# out of snapshot capture because their random inputs would churn the
# directory on every run.
snapshots:
name: Contract Snapshot Verification
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Install Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v2
- name: Run tests and report snapshot drift
env:
SNAPSHOT_VERIFY_WARN_ONLY: '1'
run: bash scripts/verify-snapshots.sh
- name: Upload snapshot verification report
if: always()
uses: actions/upload-artifact@v7
with:
name: contract-snapshot-verification
path: target/snapshot-verification
retention-days: 30
if-no-files-found: ignore
# Coverage gate (#813). Separate from `ci` so a failing test there is reported
# once, there; --ignore-run-fail lets this job still measure coverage and
# enforce the threshold. The threshold lives in contracts/accord/Cargo.toml.
coverage:
name: Contract Coverage
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Install Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v2
with:
components: llvm-tools-preview
cache: true
- name: Install cargo-llvm-cov
uses: taiki-e/install-action@cargo-llvm-cov
- name: Read coverage threshold
id: threshold
run: |
threshold=$(sed -n 's/^min-line-coverage *= *\([0-9][0-9.]*\).*/\1/p' contracts/accord/Cargo.toml)
if [ -z "$threshold" ]; then
echo "min-line-coverage is missing from contracts/accord/Cargo.toml" >&2
exit 1
fi
echo "value=$threshold" >> "$GITHUB_OUTPUT"
- name: Measure contract coverage
run: |
cargo llvm-cov --locked -p accord --lib --no-report --ignore-run-fail \
--ignore-filename-regex '(test|bench)\.rs$'
- name: Write coverage reports
run: |
mkdir -p target/coverage
cargo llvm-cov report --ignore-filename-regex '(test|bench)\.rs$' --html --output-dir target/coverage
cargo llvm-cov report --ignore-filename-regex '(test|bench)\.rs$' --lcov --output-path target/coverage/lcov.info
cargo llvm-cov report --ignore-filename-regex '(test|bench)\.rs$' --summary-only | tee target/coverage/summary.txt
{
echo "### Contract coverage"
echo
echo "Minimum line coverage: ${{ steps.threshold.outputs.value }}%"
echo
echo '```'
cat target/coverage/summary.txt
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Upload coverage report
if: always()
uses: actions/upload-artifact@v7
with:
name: contract-coverage
path: target/coverage
retention-days: 30
- name: Enforce coverage threshold
run: |
cargo llvm-cov report --ignore-filename-regex '(test|bench)\.rs$' \
--fail-under-lines "${{ steps.threshold.outputs.value }}"
# Resource/CPU regression gate (#814). Compares the metered cost of the hot
# entrypoints with contracts/accord/bench-baseline.txt and fails when any
# figure grows past the threshold (default 5%). See CONTRIBUTING.md.
benchmarks:
name: Contract Benchmarks
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Install Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v2
with:
cache: true
- name: Run resource benchmarks
run: cargo test --locked -p accord --lib bench_hot_entrypoints -- --nocapture
- name: Report benchmark deltas
if: always()
run: |
if [ -f target/bench/report.md ]; then
cat target/bench/report.md >> "$GITHUB_STEP_SUMMARY"
fi
- name: Upload benchmark report
if: always()
uses: actions/upload-artifact@v7
with:
name: contract-benchmarks
path: target/bench
retention-days: 30
if-no-files-found: ignore
# Fork pull requests get a read-only token, so commenting is best effort;
# the deltas are always in the job summary and the artifact above.
- name: Comment deltas on the pull request
if: always() && github.event_name == 'pull_request'
continue-on-error: true
uses: actions/github-script@v9
with:
script: |
const fs = require('fs');
if (!fs.existsSync('target/bench/report.md')) return;
const marker = '<!-- accord-contract-benchmarks -->';
const body = `${marker}\n${fs.readFileSync('target/bench/report.md', 'utf8')}`;
const { owner, repo } = context.repo;
const issue_number = context.issue.number;
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
const existing = comments.find((c) => c.body && c.body.startsWith(marker));
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number, body });
}
# Detect whether a PR touches contract/build paths so the testnet upgrade
# simulation (#816) only runs when it can actually catch a regression.
testnet-upgrade-changes:
name: Detect testnet upgrade paths
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
outputs:
relevant: ${{ steps.filter.outputs.relevant }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect relevant changes
id: filter
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
set -euo pipefail
changed="$(git diff --name-only "$BASE_SHA" "$HEAD_SHA")"
printf 'Changed files:\n%s\n' "$changed"
if grep -Eq '^(contracts/accord/|Cargo\.toml$|Cargo\.lock$|scripts/testnet-upgrade-simulation\.sh$|\.github/workflows/contract\.yml$)' <<< "$changed"; then
echo "relevant=true" >> "$GITHUB_OUTPUT"
else
echo "relevant=false" >> "$GITHUB_OUTPUT"
fi
# Testnet upgrade simulation (#816). Deploys a legacy-shaped fixture,
# upgrades it to the PR build, migrates governance, and verifies state.
# Only runs for relevant PRs; the regular Contract CI job covers builds and
# unit tests, so this job is intentionally independent of it.
testnet-upgrade-simulation:
name: Testnet Upgrade Simulation
runs-on: ubuntu-latest
needs: testnet-upgrade-changes
if: github.event_name == 'pull_request' && needs.testnet-upgrade-changes.outputs.relevant == 'true'
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
target: wasm32v1-none
cache: true
- name: Install Stellar CLI
uses: stellar/stellar-cli@v28.1.0
- name: Run deploy, upgrade, migrate, verify simulation
env:
NETWORK: testnet
IDENTITY: accord-upgrade-sim-${{ github.run_id }}-${{ github.run_attempt }}
run: bash scripts/testnet-upgrade-simulation.sh
- name: Upload simulation report
if: always()
uses: actions/upload-artifact@v4
with:
name: testnet-upgrade-simulation
path: target/testnet-upgrade-simulation
retention-days: 30
if-no-files-found: ignore
# Runs only on push to main — never on pull requests.
# Requires TESTNET_CONTRACT_ID to be set as a repository variable under
# Settings → Secrets and variables → Actions → Variables.
# When the variable is absent the job logs a message and exits cleanly so
# forks and contributor PRs are unaffected.
testnet-smoke-test:
name: Testnet Smoke Test
runs-on: ubuntu-latest
needs: ci
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps:
- name: Check TESTNET_CONTRACT_ID is configured
id: guard
run: |
if [ -z "${{ vars.TESTNET_CONTRACT_ID }}" ]; then
echo "TESTNET_CONTRACT_ID repository variable is not set — skipping smoke test."
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: Install Stellar CLI
if: steps.guard.outputs.skip != 'true'
uses: stellar/stellar-cli@v28.1.0
- name: Simulate get_total_proposals on deployed testnet contract
if: steps.guard.outputs.skip != 'true'
id: invoke
run: |
result=$(stellar contract invoke \
--network testnet \
--id "${{ vars.TESTNET_CONTRACT_ID }}" \
-- get_total_proposals)
echo "result=$result" >> "$GITHUB_OUTPUT"
- name: Report live proposal count
if: steps.guard.outputs.skip != 'true'
run: |
echo "Deployed contract get_total_proposals returned: ${{ steps.invoke.outputs.result }}"
# Pre-mainnet deployment gate (issue #420).
# Runs on version tags (v*) that gate mainnet deployment. Queries the live
# testnet contract and fails if sum(owner weights) != get_total_weight.
# Skips cleanly when TESTNET_CONTRACT_ID is unset (same pattern as smoke test).
weight-invariant-gate:
name: Weight Invariant Gate
runs-on: ubuntu-latest
needs: ci
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
steps:
- name: Check TESTNET_CONTRACT_ID is configured
id: guard
run: |
if [ -z "${{ vars.TESTNET_CONTRACT_ID }}" ]; then
echo "TESTNET_CONTRACT_ID repository variable is not set — skipping weight invariant gate."
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: Install Stellar CLI
if: steps.guard.outputs.skip != 'true'
uses: stellar/stellar-cli@v28.1.0
- name: Verify total-weight invariant on testnet
if: steps.guard.outputs.skip != 'true'
env:
CONTRACT_ID: ${{ vars.TESTNET_CONTRACT_ID }}
run: |
set -euo pipefail
weights_raw=$(stellar contract invoke \
--network testnet \
--id "$CONTRACT_ID" \
-- get_owner_weights)
total_raw=$(stellar contract invoke \
--network testnet \
--id "$CONTRACT_ID" \
-- get_total_weight)
export WEIGHTS_RAW="$weights_raw"
export TOTAL_RAW="$total_raw"
python3 <<'PY'
import json, os, re, sys
def parse_u32(value):
if isinstance(value, bool):
raise TypeError(value)
if isinstance(value, int):
return value
if isinstance(value, str):
return int(value, 10)
raise TypeError(type(value))
def extract_weight(entry):
if isinstance(entry, dict):
for key, val in entry.items():
if str(key).lower() == "weight":
return parse_u32(val)
raise ValueError(f"Cannot read weight from entry: {entry!r}")
weights_raw = os.environ["WEIGHTS_RAW"].strip()
total_raw = os.environ["TOTAL_RAW"].strip()
try:
weights = json.loads(weights_raw)
except json.JSONDecodeError:
found = re.findall(r'"?weight"?\s*[:=]\s*"?(\d+)"?', weights_raw, flags=re.I)
if not found:
print("Failed to parse get_owner_weights output:", weights_raw, file=sys.stderr)
sys.exit(1)
summed = sum(int(w) for w in found)
else:
if not isinstance(weights, list):
print("Expected a list from get_owner_weights, got:", type(weights), file=sys.stderr)
sys.exit(1)
summed = sum(extract_weight(entry) for entry in weights)
try:
reported = parse_u32(json.loads(total_raw))
except Exception:
m = re.search(r"\d+", total_raw)
if not m:
print("Failed to parse get_total_weight output:", total_raw, file=sys.stderr)
sys.exit(1)
reported = int(m.group(0))
print(f"sum(owner weights) = {summed}")
print(f"get_total_weight = {reported}")
if summed != reported:
print(
"Weight invariant failed: sum of owner weights does not equal reported total weight.",
file=sys.stderr,
)
sys.exit(1)
print("Weight invariant OK.")
PY