diff --git a/starforge-cli/README.md b/starforge-cli/README.md new file mode 100644 index 0000000..92ea8b8 --- /dev/null +++ b/starforge-cli/README.md @@ -0,0 +1,35 @@ +# starforge-cli (local) + +Implements contract inspection for Soroban contracts: + +- `starforge contract history [--limit 200] [--order desc]` +- `starforge contract state-at --ledger ` + +## Required environment + +Both commands require a Soroban RPC endpoint for JSON-RPC calls. + +- `STARFORGE_RPC_URL` (recommended) or `--rpc-url` + +For Horizon calls (contract transaction listing): + +- `STARFORGE_HORIZON_URL` or `--horizon-url` + +Defaults: +- Horizon: testnet (`https://horizon-testnet.stellar.org`) +- RPC URL: **must** be provided + +## Output + +- `--export json|csv` (default `json`) +- `--output ` writes to a file; otherwise prints JSON to stdout. + +## Caching + +`state-at` caches `getLedgerEntries` responses under: + +- `~/.starforge/cache/` + +TTL: +- `--cache-ttl-seconds` (default 86400) + diff --git a/starforge-cli/bin/starforge.js b/starforge-cli/bin/starforge.js new file mode 100644 index 0000000..43c9f7b --- /dev/null +++ b/starforge-cli/bin/starforge.js @@ -0,0 +1,76 @@ +#!/usr/bin/env node + +const { Command } = require('commander'); +const program = new Command(); + +program + .name('starforge') + .description('Contract history / state-at for Soroban contracts (Horizon + Soroban RPC)') + .option('-n, --network ', 'stellar network: testnet|public', 'testnet') + .option('--horizon-url ', 'Horizon base URL', (process.env.STARFORGE_HORIZON_URL || null)) + .option('--rpc-url ', 'Soroban RPC URL', (process.env.STARFORGE_RPC_URL || null)) + .option('--cache-ttl-seconds ', 'state-at cache TTL in seconds', (process.env.STARFORGE_CACHE_TTL_SECONDS || '86400')) + .version('0.1.0'); + +const contractCmd = program + .command('contract') + .description('Contract inspection commands'); + +contractCmd + .command('history ') + + .option('--limit ', 'max transactions to scan', (v) => parseInt(v, 10), 200) + .option('--order ', 'desc|asc (Horizon order)', 'desc') + .option('--output ', 'write result JSON to a file') + .option('--export ', 'export format: json|csv', 'json') + .action(async (contractId, options, cmd) => { + // Commander nested command nesting can vary; keep direct dispatch via require + // eslint-disable-next-line global-require + const run = require('../src/commands/contractHistory'); + const res = await run({ + contractId, + limit: options.limit, + order: options.order, + output: options.output, + export: options.export, + network: program.opts().network, + horizonUrl: program.opts().horizonUrl, + rpcUrl: program.opts().rpcUrl + }); + + if (!options.output) { + process.stdout.write(JSON.stringify(res, null, 2) + '\n'); + } + }); + +contractCmd + .command('state-at ') + .requiredOption('--ledger ', 'ledger sequence number to inspect', (v) => parseInt(v, 10)) + .option('--output ', 'write result JSON to a file') + .option('--export ', 'export format: json|csv', 'json') + .action(async (contractId, options) => { + // eslint-disable-next-line global-require + const run = require('../src/commands/contractStateAt'); + const res = await run({ + contractId, + ledger: options.ledger, + output: options.output, + export: options.export, + network: program.opts().network, + horizonUrl: program.opts().horizonUrl, + rpcUrl: program.opts().rpcUrl, + cacheTtlSeconds: parseInt(program.opts().cacheTtlSeconds, 10) + }); + + if (!options.output) { + process.stdout.write(JSON.stringify(res, null, 2) + '\n'); + } + }); + +// Make nested commands work across Commander versions: parse args +program.parseAsync(process.argv).catch((err) => { + // eslint-disable-next-line no-console + console.error(err?.stack || err); + process.exit(1); +}); + diff --git a/starforge-cli/package-lock.json b/starforge-cli/package-lock.json new file mode 100644 index 0000000..cdbf3ec --- /dev/null +++ b/starforge-cli/package-lock.json @@ -0,0 +1,413 @@ +{ + "name": "starforge-cli", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "starforge-cli", + "version": "0.1.0", + "dependencies": { + "axios": "^1.6.5", + "commander": "^12.1.0", + "json2csv": "^4.4.6", + "mkdirp": "^3.0.1" + }, + "bin": { + "starforge": "bin/starforge.js" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.1.tgz", + "integrity": "sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.5", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/follow-redirects": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/json2csv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/json2csv/-/json2csv-4.5.4.tgz", + "integrity": "sha512-YxBhY4Lmn8IvVZ36nqg5omxneLy9JlorkqW1j/EDCeqvmi+CQ4uM+wsvXlcIqvGDewIPXMC/O/oF8DX9EH5aoA==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "dependencies": { + "commander": "^2.15.1", + "jsonparse": "^1.3.1", + "lodash.get": "^4.4.2" + }, + "bin": { + "json2csv": "bin/json2csv.js" + } + }, + "node_modules/json2csv/node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "license": "MIT" + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", + "engines": [ + "node >= 0.2.0" + ], + "license": "MIT" + }, + "node_modules/lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", + "deprecated": "This package is deprecated. Use the optional chaining (?.) operator instead.", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mkdirp": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-3.0.1.tgz", + "integrity": "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg==", + "license": "MIT", + "bin": { + "mkdirp": "dist/cjs/src/bin.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + } + } +} diff --git a/starforge-cli/package.json b/starforge-cli/package.json new file mode 100644 index 0000000..b4a4da1 --- /dev/null +++ b/starforge-cli/package.json @@ -0,0 +1,22 @@ +{ + "name": "starforge-cli", + "version": "0.1.0", + "private": true, + "description": "StarForge contract history/state-at CLI (Horizon + Soroban RPC)", + "bin": { + "starforge": "bin/starforge.js" + }, + "type": "commonjs", + "scripts": { + "lint": "node -e \"console.log('no lint configured')\"", + "test": "node ./src/tests/smoke.test.js" + }, + "dependencies": { + "axios": "^1.6.5", + "commander": "^12.1.0", + "json2csv": "^4.4.6", + + "mkdirp": "^3.0.1" + } +} + diff --git a/starforge-cli/src/commands/contractHistory.js b/starforge-cli/src/commands/contractHistory.js new file mode 100644 index 0000000..de1be1e --- /dev/null +++ b/starforge-cli/src/commands/contractHistory.js @@ -0,0 +1,100 @@ +const logger = require('node:console'); +const { getContractTransactions } = require('../lib/horizonClient'); +const { getSorobanTransaction } = require('../lib/sorobanClient'); +const { extractBeforeAfterFromTxMeta, buildTimelineFromLedgerEntryChanges } = require('../lib/stateDiff'); +const { writeOutput } = require('../lib/exporter'); + +function chunked(arr, n) { + const out = []; + for (let i = 0; i < arr.length; i += n) out.push(arr.slice(i, i + n)); + return out; +} + +async function runPerTx({ rpcUrl, horizonUrl, txHash, idx }) { + const tx = await getSorobanTransaction({ rpcUrl, txHash }); + + const metaV3 = tx?.meta || tx?.transactionMeta || tx?.metaV3 || {}; + const decodedChanges = extractBeforeAfterFromTxMeta(metaV3); + + const diffs = buildTimelineFromLedgerEntryChanges({ + txHash, + changesByKey: decodedChanges + }); + + return { + txHash, + ledger: tx?.ledger, + createdAt: tx?.created_at || tx?.timestamp || null, + diffs, + raw: { + // Keep minimal raw to reduce output size + sorobanMetaReturnValue: metaV3?.sorobanMeta?.returnValue ?? metaV3?.returnValue ?? null, + events: metaV3?.sorobanMeta?.events ?? metaV3?.events ?? null + } + }; +} + +async function contractHistory({ + contractId, + limit, + order, + output, + export: exportFormat, + network, + horizonUrl, + rpcUrl +}) { + const effectiveHorizonUrl = horizonUrl || (network === 'public' + ? 'https://horizon.stellar.org' + : 'https://horizon-testnet.stellar.org'); + + if (!rpcUrl) { + throw new Error('Missing Soroban RPC URL. Set --rpc-url or STARFORGE_RPC_URL.'); + } + + const records = await getContractTransactions({ + horizonUrl: effectiveHorizonUrl, + contractId, + limit, + order + }); + + // tx hash location varies; try common shapes + const txHashes = records + .map((r) => r?.hash || r?.transaction_hash || r?.tx_hash || r?.transaction?.hash) + .filter(Boolean); + + const timeline = []; + + const maxConcurrency = 5; + const batches = chunked(txHashes, maxConcurrency); + + for (let bi = 0; bi < batches.length; bi++) { + const batch = batches[bi]; + const results = await Promise.all( + batch.map((txHash, i) => runPerTx({ rpcUrl, horizonUrl: effectiveHorizonUrl, txHash, idx: i })) + ); + timeline.push(...results); + } + + // Compute per-key summary diff examples + return writeOutput({ + exportFormat, + output, + payload: { + network, + contractId, + horizonUrl: effectiveHorizonUrl, + rpcUrl, + scanned: { + horizonLimit: limit, + order, + txCount: txHashes.length + }, + timeline + } + }); +} + +module.exports = contractHistory; + diff --git a/starforge-cli/src/commands/contractStateAt.js b/starforge-cli/src/commands/contractStateAt.js new file mode 100644 index 0000000..a66fe35 --- /dev/null +++ b/starforge-cli/src/commands/contractStateAt.js @@ -0,0 +1,94 @@ +const path = require('path'); +const fs = require('fs'); +const { createAxios } = require('../lib/http'); +const { getDefaultCacheDir, getCachePath, isFresh, readJson, writeJson, ensureDir } = require('../lib/cache'); +const { writeOutput } = require('../lib/exporter'); + +// state-at goal: use getLedgerEntries for a given ledger sequence. +// Exact Soroban/RPC method for ledger entries may vary by RPC provider. +// We'll implement via JSON-RPC method 'getLedgerEntries' with params [ledger, keys?] +// where keys are optional. + +function buildCacheKey({ contractId, ledger }) { + return `state-at__contract=${contractId}__ledger=${ledger}`; +} + +async function fetchLedgerEntries({ rpcUrl, ledger }) { + // If rpc supports key-less getLedgerEntries, it will return relevant entries. + // Otherwise, user may need keys; for now we call getLedgerEntries with [ledger]. + const client = createAxios({ baseURL: rpcUrl }); + const resp = await client.post('/', { + jsonrpc: '2.0', + id: 1, + method: 'getLedgerEntries', + params: [ledger] + }); + + return resp.data?.result; +} + +function extractContractStateSnapshot(ledgerEntriesResult, contractId) { + // Best-effort extraction: + // ledger entries returned often include entries keyed by contractDataKey. + // We'll search for any entry whose key contains the contractId. + + const entries = ledgerEntriesResult?.entries || ledgerEntriesResult?.ledgerEntries || ledgerEntriesResult || []; + const out = { contractId, ledger: ledgerEntriesResult?.ledger || null, entries: [] }; + + if (!Array.isArray(entries)) return out; + + for (const e of entries) { + const keyStr = JSON.stringify(e?.key || e?.entry || e, null, 0); + if (keyStr && keyStr.includes(contractId)) { + out.entries.push(e); + } + } + + return out; +} + +async function contractStateAt({ + contractId, + ledger, + output, + export: exportFormat, + network, + horizonUrl, + rpcUrl, + cacheTtlSeconds +}) { + if (!rpcUrl) { + throw new Error('Missing Soroban RPC URL. Set --rpc-url or STARFORGE_RPC_URL.'); + } + + const cacheDir = getDefaultCacheDir(); + const cacheKey = buildCacheKey({ contractId, ledger }); + const cachePath = getCachePath({ cacheDir, key: cacheKey }); + + const ttl = Number.isFinite(cacheTtlSeconds) ? cacheTtlSeconds : 86400; + + let ledgerEntriesResult; + if (isFresh(cachePath, ttl)) { + ledgerEntriesResult = readJson(cachePath); + } else { + ledgerEntriesResult = await fetchLedgerEntries({ rpcUrl, ledger }); + writeJson(cachePath, ledgerEntriesResult); + } + + const snapshot = extractContractStateSnapshot(ledgerEntriesResult, contractId); + + return writeOutput({ + exportFormat, + output, + payload: { + network, + contractId, + ledger, + cached: isFresh(cachePath, ttl), + snapshot + } + }); +} + +module.exports = contractStateAt; + diff --git a/starforge-cli/src/lib/cache.js b/starforge-cli/src/lib/cache.js new file mode 100644 index 0000000..d2e2847 --- /dev/null +++ b/starforge-cli/src/lib/cache.js @@ -0,0 +1,44 @@ +const fs = require('fs'); +const path = require('path'); + + +function ensureDir(p) { + fs.mkdirSync(p, { recursive: true }); +} + +function getCachePath({ cacheDir, key }) { + const safeKey = key.replace(/[^a-zA-Z0-9._-]/g, '_'); + return path.join(cacheDir, safeKey + '.json'); +} + +function isFresh(filePath, ttlSeconds) { + if (!fs.existsSync(filePath)) return false; + const stat = fs.statSync(filePath); + const ageSeconds = (Date.now() - stat.mtimeMs) / 1000; + return ageSeconds <= ttlSeconds; +} + +function readJson(filePath) { + const raw = fs.readFileSync(filePath, 'utf8'); + return JSON.parse(raw); +} + +function writeJson(filePath, value) { + ensureDir(path.dirname(filePath)); + fs.writeFileSync(filePath, JSON.stringify(value, null, 2), 'utf8'); +} + +function getDefaultCacheDir() { + const home = process.env.HOME || process.env.USERPROFILE; + return path.join(home || '.', '.starforge', 'cache'); +} + +module.exports = { + ensureDir, + getCachePath, + isFresh, + readJson, + writeJson, + getDefaultCacheDir +}; + diff --git a/starforge-cli/src/lib/csv.js b/starforge-cli/src/lib/csv.js new file mode 100644 index 0000000..160e6f9 --- /dev/null +++ b/starforge-cli/src/lib/csv.js @@ -0,0 +1,36 @@ +const fs = require('fs'); +const path = require('path'); +const { Parser } = require('json2csv'); + +function exportJson(json, { outputPath } = {}) { + if (outputPath) { + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, JSON.stringify(json, null, 2), 'utf8'); + } + return json; +} + +function exportCsv(rows, { outputPath } = {}) { + // rows: array of flat objects + if (!rows || rows.length === 0) { + if (outputPath) { + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, '', 'utf8'); + } + return ''; + } + + const fields = Object.keys(rows[0]); + const opts = { fields }; + const parser = new Parser(opts); + const csv = parser.parse(rows); + + if (outputPath) { + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, csv, 'utf8'); + } + return csv; +} + +module.exports = { exportJson, exportCsv }; + diff --git a/starforge-cli/src/lib/exporter.js b/starforge-cli/src/lib/exporter.js new file mode 100644 index 0000000..0d5c835 --- /dev/null +++ b/starforge-cli/src/lib/exporter.js @@ -0,0 +1,24 @@ +const path = require('path'); +const fs = require('fs'); +const { exportJson, exportCsv } = require('./csv'); +const { flatten } = require('../utils/flatten'); + +function writeOutput({ exportFormat, output, payload }) { + if (!output) return { exported: false }; + + const ext = path.extname(output).toLowerCase(); + const format = exportFormat || (ext === '.csv' ? 'csv' : 'json'); + + if (format === 'csv') { + const rows = Array.isArray(payload) ? payload : payload?.rows || []; + const flatRows = rows.map((r) => flatten(r)); + exportCsv(flatRows, { outputPath: output }); + return { exported: true, format: 'csv', output }; + } + + exportJson(payload, { outputPath: output }); + return { exported: true, format: 'json', output }; +} + +module.exports = { writeOutput }; + diff --git a/starforge-cli/src/lib/horizonClient.js b/starforge-cli/src/lib/horizonClient.js new file mode 100644 index 0000000..a2dcd41 --- /dev/null +++ b/starforge-cli/src/lib/horizonClient.js @@ -0,0 +1,16 @@ +const { createAxios } = require('./http'); + +async function getContractTransactions({ horizonUrl, contractId, limit = 200, order = 'desc' }) { + const client = createAxios({ baseURL: horizonUrl }); + // /accounts/{contract_id}/transactions?limit=200&order=desc + const resp = await client.get(`/accounts/${contractId}/transactions`, { + params: { limit, order } + }); + + // Horizon returns embedded transactions: { _embedded: { records: [...] } } + const records = resp.data?._embedded?.records || []; + return records; +} + +module.exports = { getContractTransactions }; + diff --git a/starforge-cli/src/lib/http.js b/starforge-cli/src/lib/http.js new file mode 100644 index 0000000..a00a03a --- /dev/null +++ b/starforge-cli/src/lib/http.js @@ -0,0 +1,14 @@ +const axios = require('axios'); + +function createAxios({ baseURL, timeoutMs = 30000 } = {}) { + return axios.create({ + baseURL, + timeout: timeoutMs, + headers: { + Accept: 'application/json' + } + }); +} + +module.exports = { createAxios }; + diff --git a/starforge-cli/src/lib/sorobanClient.js b/starforge-cli/src/lib/sorobanClient.js new file mode 100644 index 0000000..cb8795f --- /dev/null +++ b/starforge-cli/src/lib/sorobanClient.js @@ -0,0 +1,32 @@ +const axios = require('./http').createAxios; + +const { createAxios } = require('./http'); + +function parseError(err) { + return { + message: err?.message || String(err), + status: err?.response?.status, + data: err?.response?.data + }; +} + +async function getSorobanTransaction({ rpcUrl, txHash }) { + // Soroban RPC (stellar rpc) is not standardized as a single endpoint, but common pattern is: + // POST { jsonrpc: '2.0', id: 1, method: 'getTransaction', params: [txHash] } + // We use 'getTransaction' per task requirement. + const client = createAxios({ baseURL: rpcUrl }); + const resp = await client.post('/', { + jsonrpc: '2.0', + id: 1, + method: 'getTransaction', + params: [txHash] + }); + + return resp.data?.result; +} + +module.exports = { + getSorobanTransaction, + parseError +}; + diff --git a/starforge-cli/src/lib/stateDiff.js b/starforge-cli/src/lib/stateDiff.js new file mode 100644 index 0000000..f0cd1f0 --- /dev/null +++ b/starforge-cli/src/lib/stateDiff.js @@ -0,0 +1,92 @@ +function safeToString(v) { + if (v === null || v === undefined) return null; + if (typeof v === 'string') return v; + if (typeof v === 'number' || typeof v === 'boolean') return String(v); + // ScVal / XDR-ish objects: keep a stable JSON representation + try { + return JSON.stringify(v); + } catch { + return String(v); + } +} + +function buildTimelineFromLedgerEntryChanges({ txHash, changesByKey }) { + // changesByKey: { [key]: { before, after } } + const diffs = []; + for (const [key, change] of Object.entries(changesByKey || {})) { + const beforeStr = safeToString(change.before); + const afterStr = safeToString(change.after); + + // Normalize "no change" detection: still include deletions/creations + const hasAny = beforeStr !== afterStr; + if (!hasAny) continue; + + diffs.push({ + key, + before: beforeStr, + after: afterStr, + txHash + }); + } + + // Sort diffs by key for stable output + diffs.sort((a, b) => a.key.localeCompare(b.key)); + return diffs; +} + +/** + * Heuristic decoder for Horizon+RPC transaction meta. + * + * We may not have a fully typed Soroban XDR parser in this repo. + * The goal is to extract storage-related before/after snapshots. + * + * Approach: + * - Inspect tx.transactionMeta / meta for ledgerEntryChanges + * - ledgerEntryChanges entries often include: + * - type (created/updated/removed) + * - entry key (maybe in "entry" or "key") + * - before/after values + * - For contract storage, key usually contains a contract id + storage key. + */ +function extractBeforeAfterFromTxMeta(txMeta) { + const out = {}; + + const changes = txMeta?.ledgerEntryChanges || txMeta?.ledgerEntryChangesV3 || []; + if (!Array.isArray(changes)) return out; + + for (const ch of changes) { + // Try to identify contract storage key + // Common shapes: + // - { type: 'updated', key: { ... }, before: { val: ... }, after: { val: ... } } + // - { type: 'updated', entry: { key: ..., val: ... }, before, after } + + const storageKeyCandidate = + ch?.key?.contractDataKey || + ch?.key?.key || + ch?.key || + ch?.entry?.key || + ch?.entry?.key?.contractDataKey || + ch?.entry; + + const keyStr = safeToString(storageKeyCandidate); + if (!keyStr) continue; + + // Prefer explicit before/after + const beforeVal = ch?.before?.val ?? ch?.before ?? ch?.entryBefore?.val ?? ch?.entry?.before; + const afterVal = ch?.after?.val ?? ch?.after ?? ch?.entryAfter?.val ?? ch?.entry?.after; + + // If not explicit, attempt to infer from { entry: { before/after } } shape + const before = beforeVal; + const after = afterVal; + + // Only keep if we have something meaningful + if (before === undefined && after === undefined) continue; + + out[keyStr] = { before, after }; + } + + return out; +} + +module.exports = { safeToString, buildTimelineFromLedgerEntryChanges, extractBeforeAfterFromTxMeta }; + diff --git a/starforge-cli/src/tests/smoke.test.js b/starforge-cli/src/tests/smoke.test.js new file mode 100644 index 0000000..984b63c --- /dev/null +++ b/starforge-cli/src/tests/smoke.test.js @@ -0,0 +1,8 @@ +/* eslint-disable no-console */ + +const pkg = require('../../package.json'); +console.log(`[smoke] starforge-cli version: ${pkg.version}`); + +require('../../bin/starforge'); +console.log('[smoke] CLI entrypoint loaded (no execution)'); + diff --git a/starforge-cli/src/utils/flatten.js b/starforge-cli/src/utils/flatten.js new file mode 100644 index 0000000..b5a6b32 --- /dev/null +++ b/starforge-cli/src/utils/flatten.js @@ -0,0 +1,25 @@ +function flatten(obj, prefix = '', out = {}) { + if (obj === null || obj === undefined) return out; + if (typeof obj !== 'object') { + out[prefix] = obj; + return out; + } + + if (Array.isArray(obj)) { + out[prefix] = JSON.stringify(obj); + return out; + } + + for (const [k, v] of Object.entries(obj)) { + const nextPrefix = prefix ? `${prefix}.${k}` : k; + if (v && typeof v === 'object' && !Array.isArray(v)) { + flatten(v, nextPrefix, out); + } else { + out[nextPrefix] = v; + } + } + return out; +} + +module.exports = { flatten }; +