@artblocks/abx-cli 0.1.0-alpha.2 → 0.1.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1991 -0
- package/assets/renderer-scaffold/src/interfaces/IAbxParams.sol +17 -0
- package/assets/renderer-scaffold/test/MyRenderer.t.sol +51 -2
- package/dist/commands/deploy.d.ts +206 -0
- package/dist/commands/deploy.d.ts.map +1 -0
- package/dist/commands/deploy.js +4273 -0
- package/dist/commands/deploy.js.map +1 -0
- package/dist/commands/project.d.ts +241 -0
- package/dist/commands/project.d.ts.map +1 -0
- package/dist/commands/project.js +1060 -0
- package/dist/commands/project.js.map +1 -0
- package/dist/commands/reads.d.ts +64 -0
- package/dist/commands/reads.d.ts.map +1 -0
- package/dist/commands/reads.js +697 -0
- package/dist/commands/reads.js.map +1 -0
- package/dist/commands/scaffold.d.ts +71 -0
- package/dist/commands/scaffold.d.ts.map +1 -0
- package/dist/commands/scaffold.js +552 -0
- package/dist/commands/scaffold.js.map +1 -0
- package/dist/commands/service.d.ts +41 -0
- package/dist/commands/service.d.ts.map +1 -0
- package/dist/commands/service.js +618 -0
- package/dist/commands/service.js.map +1 -0
- package/dist/commands/storage.d.ts +37 -0
- package/dist/commands/storage.d.ts.map +1 -0
- package/dist/commands/storage.js +343 -0
- package/dist/commands/storage.js.map +1 -0
- package/dist/config.d.ts +91 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +244 -11
- package/dist/config.js.map +1 -1
- package/dist/conformance.d.ts +31 -0
- package/dist/conformance.d.ts.map +1 -0
- package/dist/conformance.js +371 -0
- package/dist/conformance.js.map +1 -0
- package/dist/deps.d.ts +6 -39
- package/dist/deps.d.ts.map +1 -1
- package/dist/deps.js +4 -68
- package/dist/deps.js.map +1 -1
- package/dist/errors.d.ts +20 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +25 -0
- package/dist/errors.js.map +1 -0
- package/dist/flag-allowlists.d.ts +53 -0
- package/dist/flag-allowlists.d.ts.map +1 -0
- package/dist/flag-allowlists.js +148 -0
- package/dist/flag-allowlists.js.map +1 -0
- package/dist/flags.d.ts +41 -0
- package/dist/flags.d.ts.map +1 -1
- package/dist/flags.js +94 -1
- package/dist/flags.js.map +1 -1
- package/dist/jsonout.d.ts +37 -0
- package/dist/jsonout.d.ts.map +1 -0
- package/dist/jsonout.js +68 -0
- package/dist/jsonout.js.map +1 -0
- package/dist/kind.d.ts +53 -0
- package/dist/kind.d.ts.map +1 -0
- package/dist/kind.js +94 -0
- package/dist/kind.js.map +1 -0
- package/dist/main.js +534 -4708
- package/dist/main.js.map +1 -1
- package/dist/mintpage.d.ts +17 -2
- package/dist/mintpage.d.ts.map +1 -1
- package/dist/mintpage.js +214 -52
- package/dist/mintpage.js.map +1 -1
- package/dist/output.d.ts +148 -0
- package/dist/output.d.ts.map +1 -0
- package/dist/output.js +634 -0
- package/dist/output.js.map +1 -0
- package/dist/ownerops.d.ts +132 -44
- package/dist/ownerops.d.ts.map +1 -1
- package/dist/ownerops.js +1151 -329
- package/dist/ownerops.js.map +1 -1
- package/dist/preview.d.ts +81 -0
- package/dist/preview.d.ts.map +1 -0
- package/dist/preview.js +535 -0
- package/dist/preview.js.map +1 -0
- package/dist/prompt.d.ts +17 -0
- package/dist/prompt.d.ts.map +1 -0
- package/dist/prompt.js +19 -0
- package/dist/prompt.js.map +1 -0
- package/dist/provision.d.ts.map +1 -1
- package/dist/provision.js +10 -7
- package/dist/provision.js.map +1 -1
- package/dist/remote.d.ts +134 -53
- package/dist/remote.d.ts.map +1 -1
- package/dist/remote.js +358 -46
- package/dist/remote.js.map +1 -1
- package/dist/riskgate.d.ts +29 -0
- package/dist/riskgate.d.ts.map +1 -0
- package/dist/riskgate.js +91 -0
- package/dist/riskgate.js.map +1 -0
- package/dist/scaffold.d.ts +10 -0
- package/dist/scaffold.d.ts.map +1 -0
- package/dist/scaffold.js +52 -0
- package/dist/scaffold.js.map +1 -0
- package/dist/schema.d.ts +18 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +74 -23
- package/dist/schema.js.map +1 -1
- package/dist/served.d.ts +30 -0
- package/dist/served.d.ts.map +1 -0
- package/dist/served.js +112 -0
- package/dist/served.js.map +1 -0
- package/dist/signer.d.ts +13 -0
- package/dist/signer.d.ts.map +1 -1
- package/dist/signer.js +80 -14
- package/dist/signer.js.map +1 -1
- package/dist/update-check.d.ts +83 -4
- package/dist/update-check.d.ts.map +1 -1
- package/dist/update-check.js +132 -17
- package/dist/update-check.js.map +1 -1
- package/package.json +10 -6
- package/skill/SKILL.md +108 -62
- package/skill/reference/code-projects.md +109 -13
- package/skill/reference/creator-token.md +86 -0
- package/skill/reference/decisions.md +87 -0
- package/skill/reference/hosting.md +48 -15
- package/skill/reference/operating.md +32 -8
- package/skill/reference/setup.md +10 -3
- package/skill/reference/troubleshooting.md +31 -4
- package/dist/inspect.d.ts +0 -48
- package/dist/inspect.d.ts.map +0 -1
- package/dist/inspect.js +0 -184
- package/dist/inspect.js.map +0 -1
- package/dist/migrate.d.ts +0 -65
- package/dist/migrate.d.ts.map +0 -1
- package/dist/migrate.js +0 -180
- package/dist/migrate.js.map +0 -1
- package/dist/onchain-uri.d.ts +0 -97
- package/dist/onchain-uri.d.ts.map +0 -1
- package/dist/onchain-uri.js +0 -243
- package/dist/onchain-uri.js.map +0 -1
- package/dist/upload.d.ts +0 -28
- package/dist/upload.d.ts.map +0 -1
- package/dist/upload.js +0 -41
- package/dist/upload.js.map +0 -1
package/dist/ownerops.js
CHANGED
|
@@ -6,22 +6,29 @@
|
|
|
6
6
|
* served state reflects the change. The agent picks the lane; the human only
|
|
7
7
|
* approves (wallet lane) or it's the env key (hot lane).
|
|
8
8
|
*/
|
|
9
|
-
import { assertChainId,
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { DEP_RESOLUTION, parseDependencyRef, prepareLockDependencies, prepareRemoveLastDependency, prepareSetDependency, prepareSetDependencyRegistry, } from '@artblocks/abx-sdk';
|
|
9
|
+
import { assertChainId, ensureChunkStore as sdkEnsureChunkStore, predictFixedPriceMinter, predictFixedPriceMinter1155, makeHotSender, makePublicClient, makeWalletClient, oneOfOneImageAbi, oneOfOneEditionAbi, seriesImageAbi, deployFixedPriceMinter, deployFixedPriceMinter1155, prepareConfigureSale, prepareConfigureSale1155, preparePurchase, preparePurchase1155, readSaleConfig, readSaleConfig1155, prepareEditionMint, prepareEditionTransfer, prepareSetMaxSupply, preparePingURI, prepareLockContractField, prepareLockContractURI, prepareLockTokenField, prepareLockTokenURI, prepareMint, mintedTokenIds, prepareSeriesMintMany, prepareSetMinter, prepareSetMaxInvocations, prepareSetPrimaryPayee, prepareSetPaused, prepareSetContractField, prepareSetContractURIBase, prepareSetContractURIOverride, prepareSetContractURIRenderer, prepareSetParamHooks, prepareSetParamSchema, prepareRetireParam, readParamSchema, PARAM_TYPES, prepareSetRoyalty, prepareSetTokenField, batchOps, prepareSetTokenURIBase, prepareSetTokenURIOverride, prepareSetTokenURIRenderer, prepareSetTransferValidator, prepareTransfer, prepareTransferOwnership, readCreatorTokenStatus, resolveRecommendedTransferValidator, RECOMMENDED_TRANSFER_VALIDATOR, KNOWN_CHAIN_KEYS, resolveChain, resolveRpcUrl, redactRpcUrl, encodeTag, METADATA_FIELD as F, METADATA_REPRESENTATION as R, stageFieldContent, planStagedContent, exceedsOnchainSoftLimit, ONCHAIN_IMAGE_SOFT_LIMIT, ONCHAIN_PROJECT_SOFT_LIMIT, } from '@artblocks/abx-sdk';
|
|
10
|
+
import { encodeScalarParam, encodeTag as encodeTagSdk, isAccepted, prepareConfigureTokenParam, prepareConfigureTokenParamData, prepareSetContractParam, prepareSetContractParamData, seriesCodeAbi, tryReadContract, } from '@artblocks/abx-sdk';
|
|
11
|
+
import { hasParamEnumeration } from '@artblocks/abx-sdk';
|
|
12
|
+
import { decodeFieldRenderer, resolveGenerator, DEP_RESOLUTION, parseDependencyRef, prepareLockDependencies, prepareRemoveLastDependency, prepareSetDependency, prepareSetDependencyRegistry, } from '@artblocks/abx-sdk';
|
|
14
13
|
import { contentTypeFromPath } from '@artblocks/abx-storage';
|
|
15
14
|
import { toHex as toHexSdk } from 'viem';
|
|
16
15
|
import { readFileSync } from 'node:fs';
|
|
17
16
|
import { basename, resolve as resolvePath } from 'node:path';
|
|
18
17
|
import { gzipSync } from 'node:zlib';
|
|
19
18
|
import { formatEther, getAddress, isAddress, parseEther, toHex, zeroAddress } from 'viem';
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
|
|
19
|
+
import { CHAIN, chainId, fixedPriceMinterAddress, fixedPriceMinter1155Address, localIndexer } from './config.js';
|
|
20
|
+
import { CliError } from './errors.js';
|
|
21
|
+
import { detectTokenKind, isEditionContract } from './kind.js';
|
|
22
|
+
import { openWalletSession } from './signer.js';
|
|
23
|
+
import { gatedSend, laneFromFlags } from './riskgate.js';
|
|
24
|
+
import { withJson } from './jsonout.js';
|
|
25
|
+
import { resolveRemote, serviceClient } from './remote.js';
|
|
26
|
+
import { isDryRun, positionalArgs, unknownFlags, warnStrayFlags } from './flags.js';
|
|
27
|
+
import { parseSchemaSpecs, describeSchema } from './schema.js';
|
|
28
|
+
// Re-exported for main.ts (the on-chain-vs-off-chain cost model + the compression-mode type now
|
|
29
|
+
// live in the SDK's staging.ts, layered on planChunks/planContentTxs — see the comment at their
|
|
30
|
+
// definition below).
|
|
31
|
+
export { ONCHAIN_PROJECT_SOFT_LIMIT };
|
|
25
32
|
// ── ANSI (local) ─────────────────────────────────────────────────────────────
|
|
26
33
|
const C = { reset: '\x1b[0m', dim: '\x1b[2m', bold: '\x1b[1m', green: '\x1b[38;5;115m', yellow: '\x1b[38;5;221m' };
|
|
27
34
|
const dim = (s) => `${C.dim}${s}${C.reset}`;
|
|
@@ -33,19 +40,52 @@ const bold = (s) => `${C.bold}${s}${C.reset}`;
|
|
|
33
40
|
// COMPLETE set — but it's COMPUTED by the resolver/renderer from the token's fields + effect
|
|
34
41
|
// outputs; it is never a field you set. These keys are that computed output, so setting them by
|
|
35
42
|
// hand would only pollute the manifest with a bogus entry (a real round-1 agent trap). Refuse them
|
|
36
|
-
// and point at the real verb.
|
|
37
|
-
|
|
43
|
+
// and point at the real verb. `abx_params` joins them for the same reason: it is COMPUTED from the
|
|
44
|
+
// token's on-chain param enumeration, so a hand-set field of that name would be a decoy sitting
|
|
45
|
+
// beside the real block. See specs/protocol/data-plane.md + specs/protocol/onchain-metadata.md.
|
|
46
|
+
const COMPUTED_FIELD_KEYS = new Set(['artifacts', 'abx_params', 'abx_provenance']);
|
|
38
47
|
export function assertSettableField(field) {
|
|
39
48
|
if (COMPUTED_FIELD_KEYS.has(field)) {
|
|
40
49
|
const what = field === 'artifacts'
|
|
41
50
|
? "the COMPUTED manifest (the complete list of this token's files), assembled by the resolver/renderer from your fields"
|
|
42
|
-
:
|
|
43
|
-
|
|
44
|
-
|
|
51
|
+
: field === 'abx_params'
|
|
52
|
+
? "the COMPUTED parameter block, enumerated from the token's on-chain params (set one with `abx configure-param`, declare one with `abx set-schema`)"
|
|
53
|
+
: 'the COMPUTED provenance list, assembled by the resolver/renderer';
|
|
54
|
+
throw new Error(`"${field}" is not a field you set — it's ${what}.` +
|
|
55
|
+
(field === 'abx_params'
|
|
56
|
+
? `\n Set a param instead:\n abx configure-param <address> <tokenId|-> <key> <value>\n (or attach a FILE under your own key: abx attach <address> <yourkey> <ipfs://… | ar://… | https://…>)`
|
|
57
|
+
: ` To attach a file so it appears in the manifest, pick your OWN key:\n abx attach <address> <yourkey> <ipfs://… | ar://… | https://…>`));
|
|
45
58
|
}
|
|
46
59
|
}
|
|
60
|
+
/** Whether a value fits the literal `bytes32` lane of a raw contract-param write (printable ASCII,
|
|
61
|
+
* ≤ 31 bytes). Anything longer takes the data path — one blob, its hash evented. */
|
|
62
|
+
function fitsLiteralBytes32(value) {
|
|
63
|
+
return value.length <= 31 && /^[\x20-\x7e]+$/.test(value);
|
|
64
|
+
}
|
|
47
65
|
/** Flags `abx attach` recognizes — anything else warns (non-fatal), so a silent no-op flag surfaces. */
|
|
48
|
-
const ATTACH_FLAGS = ['file', 'compress', 'collection', 'token', 'send', 'sign', 'unsigned', 'yes', 'dry-run', 'port', 'sign-url-file', 'remote'];
|
|
66
|
+
const ATTACH_FLAGS = ['file', 'compress', 'collection', 'token', 'send', 'sign', 'unsigned', 'yes', 'dry-run', 'confirm', 'port', 'sign-url-file', 'remote'];
|
|
67
|
+
/**
|
|
68
|
+
* The flags EVERY owner write accepts, regardless of command — the signing lane (`laneFromFlags`),
|
|
69
|
+
* the opt-in confirm gate, the wallet-lane plumbing, the post-write reindex nudge, and `--json`.
|
|
70
|
+
* Factored out so a per-command allowlist below only has to name that command's OWN flags.
|
|
71
|
+
*/
|
|
72
|
+
const SHARED_WRITE_FLAGS = ['send', 'sign', 'unsigned', 'dry-run', 'yes', 'confirm', 'port', 'sign-url-file', 'remote', 'remote-token', 'json'];
|
|
73
|
+
/**
|
|
74
|
+
* Per-command allowlists for the owner ops where a silently-ignored flag changes MONEY or SUPPLY.
|
|
75
|
+
*
|
|
76
|
+
* These commands took no stray-flag notice at all, and the ERC-1155 lane made that expensive: an
|
|
77
|
+
* edition's semantics live in its OPTIONAL flags, which default rather than fail. A typo'd
|
|
78
|
+
* `--amount 50` minted 1 copy; a typo'd `--quantity 5` bought 1 and paid 1×; and nothing said a word.
|
|
79
|
+
* (`deploy` refuses strays outright, but its allowlists are exhaustively maintained. Here we WARN —
|
|
80
|
+
* per `unknownFlags`' own contract and the owner's scriptability line: a false warning on a valid
|
|
81
|
+
* flag must never break someone's script, and a warning already ends the silence.)
|
|
82
|
+
*/
|
|
83
|
+
const MINT_FLAGS = [...SHARED_WRITE_FLAGS, 'to', 'count', 'token-id', 'amount'];
|
|
84
|
+
const TRANSFER_FLAGS = [...SHARED_WRITE_FLAGS, 'to', 'token', 'token-id', 'amount', 'from'];
|
|
85
|
+
const SET_MAX_SUPPLY_FLAGS = [...SHARED_WRITE_FLAGS, 'token-id', 'cap'];
|
|
86
|
+
const MINTER_CONFIGURE_FLAGS = [...SHARED_WRITE_FLAGS, 'price', 'price-raw', 'allocation', 'erc20', 'token-id', 'minter-contract'];
|
|
87
|
+
const MINTER_SHOW_FLAGS = [...SHARED_WRITE_FLAGS, 'token-id', 'minter-contract'];
|
|
88
|
+
const MINTER_BUY_FLAGS = [...SHARED_WRITE_FLAGS, 'to', 'token-id', 'quantity', 'minter-contract'];
|
|
49
89
|
/** Auto-detect the on-chain representation for an off-chain locator by its URI scheme. Returns null
|
|
50
90
|
* for anything that isn't a recognized durable/http locator (so `attach` can refuse it loudly
|
|
51
91
|
* rather than silently storing a bad value — the round-1 `--representation` guessing trap). */
|
|
@@ -59,21 +99,10 @@ export function representationForLocator(uri) {
|
|
|
59
99
|
return R.url;
|
|
60
100
|
return null;
|
|
61
101
|
}
|
|
62
|
-
function chainId() {
|
|
63
|
-
return resolveChain(CHAIN).id;
|
|
64
|
-
}
|
|
65
|
-
/** Resolve the signing lane from flags: --unsigned (cold) · --sign (wallet) · default hot. */
|
|
66
|
-
export function laneFromFlags(flags) {
|
|
67
|
-
if (flags.unsigned)
|
|
68
|
-
return 'unsigned';
|
|
69
|
-
if (flags.sign)
|
|
70
|
-
return 'sign';
|
|
71
|
-
return 'send';
|
|
72
|
-
}
|
|
73
102
|
function requireAddress(address, usage) {
|
|
74
103
|
if (!address || address.startsWith('--')) {
|
|
75
104
|
console.error(`usage: ${usage}\n`);
|
|
76
|
-
|
|
105
|
+
throw new CliError('', 1, true); // already printed above — see CliError's alreadyPrinted doc
|
|
77
106
|
}
|
|
78
107
|
return address;
|
|
79
108
|
}
|
|
@@ -81,55 +110,32 @@ function requireFlag(flags, name, usage) {
|
|
|
81
110
|
const v = flags[name];
|
|
82
111
|
if (!v || v === 'true') {
|
|
83
112
|
console.error(`missing --${name}\nusage: ${usage}\n`);
|
|
84
|
-
|
|
113
|
+
throw new CliError('', 1, true); // already printed above — see CliError's alreadyPrinted doc
|
|
85
114
|
}
|
|
86
115
|
return v;
|
|
87
116
|
}
|
|
88
|
-
/**
|
|
89
|
-
*
|
|
117
|
+
/**
|
|
118
|
+
* Every owner-op's send choke point. Returns the {@link SignResult} when a tx was broadcast, else
|
|
119
|
+
* `null` (dry run, or the cold lane which prints a tx instead of sending one).
|
|
120
|
+
*
|
|
121
|
+
* It used to return a bare boolean. It returns the result now because a caller sometimes needs the
|
|
122
|
+
* *receipt* — `abx mint --json` has to report which token id was actually minted, and the only
|
|
123
|
+
* authoritative answer is the Transfer log the mint emitted. Callers that only asked "did it send?"
|
|
124
|
+
* keep working: `null` is falsy, and a result object is truthy.
|
|
125
|
+
*
|
|
126
|
+
* The dry-run preview / `--confirm` prompt / lane selection live in {@link gatedSend} — the SAME
|
|
127
|
+
* choke point the deploy family's resumed-setup send routes through — so this is now just "gate,
|
|
128
|
+
* then re-index if the project is known."
|
|
129
|
+
*/
|
|
90
130
|
async function runWrite(address, provider, flags, expectedSigner) {
|
|
91
|
-
|
|
92
|
-
// owner-op, so --dry-run is uniform across them — it must never fall through to a real send just
|
|
93
|
-
// because the flag isn't wired per-command (a round-1 finding: `set-field --dry-run` silently
|
|
94
|
-
// reached the send lane and only stopped for lack of a key).
|
|
95
|
-
if (flags['dry-run']) {
|
|
96
|
-
const prepared = typeof provider === 'function' ? await provider(expectedSigner ?? zeroAddress) : provider;
|
|
97
|
-
console.log(`\n ${C.bold}◆ ${prepared.summary}${C.reset} ${dim('(dry run — nothing sent)')}`);
|
|
98
|
-
for (const [k, v] of Object.entries(prepared.fields))
|
|
99
|
-
console.log(` ${dim(k.padEnd(12))} ${v}`);
|
|
100
|
-
console.log(` ${dim('to'.padEnd(12))} ${prepared.to ?? dim('(contract deploy)')}`);
|
|
101
|
-
if (expectedSigner)
|
|
102
|
-
console.log(` ${dim('owner'.padEnd(12))} ${expectedSigner}`);
|
|
103
|
-
console.log(dim(`\n Re-run without --dry-run to send (lane: ${laneFromFlags(flags)}).\n`));
|
|
104
|
-
return false;
|
|
105
|
-
}
|
|
106
|
-
await assertChainId(CHAIN); // verify the RPC really is CHAIN before any irreversible write
|
|
107
|
-
const result = await signTx(provider, {
|
|
108
|
-
lane: laneFromFlags(flags),
|
|
109
|
-
chainKey: CHAIN,
|
|
110
|
-
expectedSigner,
|
|
111
|
-
yes: !!flags.yes,
|
|
112
|
-
port: flags.port ? Number(flags.port) : undefined,
|
|
113
|
-
signUrlFile: flags['sign-url-file'],
|
|
114
|
-
});
|
|
131
|
+
const result = await gatedSend(provider, flags, { chainKey: CHAIN, expectedSigner });
|
|
115
132
|
if (!result)
|
|
116
|
-
return
|
|
133
|
+
return null; // dry run, or the cold lane — nothing broadcast
|
|
117
134
|
await reindexIfKnown(address, flags);
|
|
118
|
-
return
|
|
119
|
-
}
|
|
120
|
-
/** Resolve a `--remote [url]` owner-op target: explicit URL, else ABX_PUBLIC_BASE_URL / ABX_RESOLVER_URL. */
|
|
121
|
-
function remoteResolverTarget(flags) {
|
|
122
|
-
const v = flags.remote;
|
|
123
|
-
if (v === undefined)
|
|
124
|
-
return null;
|
|
125
|
-
const base = v !== 'true' && v !== '' ? String(v) : (process.env.ABX_PUBLIC_BASE_URL ?? process.env.ABX_RESOLVER_URL);
|
|
126
|
-
if (!base) {
|
|
127
|
-
throw new Error('`--remote` needs a resolver URL: pass `--remote https://host` or set ABX_PUBLIC_BASE_URL in .env');
|
|
128
|
-
}
|
|
129
|
-
return base.replace(/\/+$/, '');
|
|
135
|
+
return result;
|
|
130
136
|
}
|
|
131
137
|
async function reindexIfKnown(address, flags) {
|
|
132
|
-
const indexer =
|
|
138
|
+
const indexer = localIndexer();
|
|
133
139
|
if (indexer.store.getRegistration(address)) {
|
|
134
140
|
const { state, elapsedMs } = await indexer.reindex(address);
|
|
135
141
|
console.log(` ${green('✓')} re-indexed ${state.name ?? address}: ${state.eventCount} events in ${elapsedMs}ms`);
|
|
@@ -137,46 +143,55 @@ async function reindexIfKnown(address, flags) {
|
|
|
137
143
|
else {
|
|
138
144
|
console.log(dim(` (not indexed by this node — run \`abx add ${address}\` then \`abx index\` to serve it)`));
|
|
139
145
|
}
|
|
140
|
-
//
|
|
146
|
+
// Remote-resolver nudge. A remote resolver serves from ITS OWN store, so the LOCAL reindex above
|
|
141
147
|
// never reaches it: after an owner-op — especially a PostParam change — it stays stale, and its
|
|
142
148
|
// effect runner never sees the new inputsHash, so the marketplace thumbnail never auto-updates.
|
|
143
|
-
// `--remote <url>` re-indexes the
|
|
144
|
-
// (ABX_EFFECTS_URL) → the automatic re-render. This is what makes a
|
|
145
|
-
// one-command change (no separate `abx index --remote` + no stale thumbnail).
|
|
146
|
-
|
|
149
|
+
// `--remote <name|url>` re-indexes the remote resolver (incremental), which pings its effect
|
|
150
|
+
// runner (ABX_EFFECTS_URL) → the automatic re-render. This is what makes a remote
|
|
151
|
+
// `configure-param` a one-command change (no separate `abx index --remote` + no stale thumbnail).
|
|
152
|
+
// Best-effort BY DESIGN: the signed tx already landed, so a missing token soft-skips (a hard
|
|
153
|
+
// error here would turn an on-chain success into a CLI failure) — worse only than stale-until-reindex.
|
|
154
|
+
const remote = resolveRemote(flags.remote, flags['remote-token']);
|
|
147
155
|
if (!remote)
|
|
148
156
|
return;
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
console.log(dim(` (--remote: set ABX_RESOLVER_ADMIN_TOKEN in .env to nudge ${remote}; skipped — it will serve stale state until it re-indexes)`));
|
|
157
|
+
if (!remote.token) {
|
|
158
|
+
console.log(dim(` (--remote: set ${remote.tokenVar} in .env to nudge ${remote.url}; skipped — it will serve stale state until it re-indexes)`));
|
|
152
159
|
return;
|
|
153
160
|
}
|
|
154
161
|
try {
|
|
155
|
-
|
|
156
|
-
|
|
162
|
+
// no fromBlock ⇒ incremental nudge
|
|
163
|
+
const r = await serviceClient(remote).registerProject({ chainId: chainId(), address });
|
|
164
|
+
// A deferred nudge (202) is NOT waited on here: the signed tx has already landed, and blocking a
|
|
165
|
+
// completed owner-op behind someone else's backfill would be the wrong trade. Say where it got to.
|
|
166
|
+
if (isAccepted(r)) {
|
|
167
|
+
console.log(` ${green('✓')} nudged remote resolver ${dim(remote.url)}: ${r.project.status} — it will pick up the change (check: abx status ${address} --remote ${flags.remote})`);
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
console.log(` ${green('✓')} nudged remote resolver ${dim(remote.url)}: ${r.project.eventCount} events (${r.mode}) — its effect runner picks up the change`);
|
|
171
|
+
}
|
|
157
172
|
}
|
|
158
173
|
catch (e) {
|
|
159
|
-
console.log(dim(` (couldn't nudge ${remote}: ${e.message} — run \`abx index ${address} --remote ${remote}\` to refresh it)`));
|
|
174
|
+
console.log(dim(` (couldn't nudge ${remote.url}: ${e.message} — run \`abx index ${address} --remote ${flags.remote}\` to refresh it)`));
|
|
160
175
|
}
|
|
161
176
|
}
|
|
162
177
|
async function read(address, functionName, args = []) {
|
|
163
178
|
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}
|
|
179
|
+
const result = await tryReadContract(publicClient, { address, abi: oneOfOneImageAbi, functionName, args });
|
|
180
|
+
if (result !== undefined)
|
|
181
|
+
return result;
|
|
182
|
+
// A read that "returned no data" is usually not a real revert but an address with NO CONTRACT —
|
|
183
|
+
// previewing before deploy, a typo'd address, or the wrong chain. Every owner-op reads the
|
|
184
|
+
// owner/ownerOf here FIRST, so this one guard turns the opaque viem error into an actionable one
|
|
185
|
+
// across all of them. Only runs on the error path (zero cost when the contract exists).
|
|
186
|
+
await assertContractExists(address);
|
|
187
|
+
// The contract DOES exist → a genuine revert. tryReadContract already swallowed that error, so
|
|
188
|
+
// re-read once (uncaught) to surface it rather than a generic "read failed".
|
|
189
|
+
return (await publicClient.readContract({
|
|
190
|
+
address,
|
|
191
|
+
abi: oneOfOneImageAbi,
|
|
192
|
+
functionName: functionName,
|
|
193
|
+
args: args,
|
|
194
|
+
}));
|
|
180
195
|
}
|
|
181
196
|
/** Throw a clear, actionable error when `address` has no contract on the active chain — the common
|
|
182
197
|
* cause of an owner-op's raw `returned no data ("0x")`. No-op when code is present or unknowable. */
|
|
@@ -192,7 +207,8 @@ export async function assertContractExists(address) {
|
|
|
192
207
|
if (!code || code === '0x') {
|
|
193
208
|
throw new Error(`no contract at ${address} on ${CHAIN} — nothing to operate on. Owner ops run AFTER deploy: ` +
|
|
194
209
|
`deploy it first (e.g. abx deploy / deploy-series / deploy-code), or check the address and that ` +
|
|
195
|
-
`ABX_CHAIN='${CHAIN}' is the right network (
|
|
210
|
+
`ABX_CHAIN='${CHAIN}' is the right network — we asked ${redactRpcUrl(resolveRpcUrl(CHAIN))}, and a ` +
|
|
211
|
+
`wrong-network endpoint reads as empty even when the address is right.`);
|
|
196
212
|
}
|
|
197
213
|
}
|
|
198
214
|
// ── configure-param ──────────────────────────────────────────────────────────
|
|
@@ -209,18 +225,35 @@ export async function assertContractExists(address) {
|
|
|
209
225
|
* (mirrors parseFlags). `rest.filter(r => !r.startsWith('--'))` was NOT enough: a flag's VALUE
|
|
210
226
|
* (e.g. the URL after `--remote`, or the path after `--file`) isn't `--`-prefixed, so it leaked
|
|
211
227
|
* into the positional value (`configure-param … #ff0000 --remote http://h` → value "#ff0000 http://h"). */
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
228
|
+
/**
|
|
229
|
+
* Encode a command-line value for a payload-typed param (`String` / `Bytes`).
|
|
230
|
+
*
|
|
231
|
+
* `String` is UTF-8 text — the literal characters are the value, which is what a user means.
|
|
232
|
+
*
|
|
233
|
+
* `Bytes` is NOT text, and the old code UTF-8'd whatever string it was handed. A tester passed
|
|
234
|
+
* base64 (the encoding the params docs mention — which describes the *canonical decode* a program
|
|
235
|
+
* receives, not what you type here), and 128 packed bytes were stored as 172 bytes of base64 ASCII.
|
|
236
|
+
* Nothing errored; the in-chain renderer read ASCII where it expected bytes and drew garbage. So a
|
|
237
|
+
* `Bytes` value must state its encoding: `0x…` hex, or `--file` for real binary. A bare string is
|
|
238
|
+
* refused rather than guessed at — there is no safe guess between "these characters" and "these
|
|
239
|
+
* bytes", and the failure is invisible until an artwork renders wrong.
|
|
240
|
+
*/
|
|
241
|
+
export function encodePayloadParam(typeName, valueInput, key) {
|
|
242
|
+
if (typeName === 'String')
|
|
243
|
+
return toHexSdk(new TextEncoder().encode(valueInput));
|
|
244
|
+
const v = valueInput.trim();
|
|
245
|
+
if (/^0x[0-9a-fA-F]*$/.test(v)) {
|
|
246
|
+
if (v.length % 2 !== 0) {
|
|
247
|
+
throw new Error(`--${key} hex value has an odd number of digits (${v.length - 2}) — a byte is two hex digits.`);
|
|
220
248
|
}
|
|
221
|
-
|
|
222
|
-
}
|
|
223
|
-
|
|
249
|
+
return v;
|
|
250
|
+
}
|
|
251
|
+
throw new Error(`"${key}" is a Bytes param, so its value must say what its bytes ARE — this looks like text.\n` +
|
|
252
|
+
` Pass 0x-prefixed hex: abx configure-param <addr> <id> ${key} 0x00112233…\n` +
|
|
253
|
+
` Or the bytes in a file: abx configure-param <addr> <id> ${key} --file ./payload.bin\n` +
|
|
254
|
+
` (Base64 is how a Bytes param is DECODED for your program — not how you write it here. ` +
|
|
255
|
+
`Storing base64 text would put ASCII on-chain where a renderer expects bytes, silently. ` +
|
|
256
|
+
`To store these literal characters on purpose, declare the key as String instead.)`);
|
|
224
257
|
}
|
|
225
258
|
export async function cmdConfigureParam(address, rest, flags) {
|
|
226
259
|
const usage = 'abx configure-param <address> <tokenId|-> <key> <value> [--file <path>] [--remote [url]] [--sign|--unsigned] (tokenId "-" = contract scope, schema-less keys only)';
|
|
@@ -229,7 +262,8 @@ export async function cmdConfigureParam(address, rest, flags) {
|
|
|
229
262
|
const valueInput = valueParts.join(' ');
|
|
230
263
|
if (!tokenIdRaw || !key || (!valueInput && !flags.file)) {
|
|
231
264
|
console.error(`usage: ${usage}\n`);
|
|
232
|
-
process.
|
|
265
|
+
process.exitCode = 1;
|
|
266
|
+
return;
|
|
233
267
|
}
|
|
234
268
|
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
235
269
|
const schema = (await publicClient.readContract({
|
|
@@ -240,8 +274,9 @@ export async function cmdConfigureParam(address, rest, flags) {
|
|
|
240
274
|
}));
|
|
241
275
|
const [exists, paramTypeIdx, , , , , , selectOptions] = schema;
|
|
242
276
|
// Contract scope (`-`): the raw owner setters (`setContractParam[Data]`) — the write path of
|
|
243
|
-
// well-known contract params like `
|
|
244
|
-
//
|
|
277
|
+
// well-known contract params like `display.gateway`. Schema-less keys only: a schema'd key closes
|
|
278
|
+
// the raw path on-chain (`SchemaGoverned`) and is per-token by design. No key is special here: a
|
|
279
|
+
// contract param is enumerated on-chain like any other and lands in tokenData for every token.
|
|
245
280
|
if (tokenIdRaw === '-') {
|
|
246
281
|
if (exists) {
|
|
247
282
|
throw new Error(`"${key}" is schema-governed — it's a per-token PostParam (abx configure-param ${contract} <tokenId> ${key} …). ` +
|
|
@@ -254,9 +289,9 @@ export async function cmdConfigureParam(address, rest, flags) {
|
|
|
254
289
|
await runWrite(contract, prepareSetContractParamData({ contract, key, data, chainId: cid }), flags, owner);
|
|
255
290
|
return;
|
|
256
291
|
}
|
|
257
|
-
//
|
|
258
|
-
//
|
|
259
|
-
if (
|
|
292
|
+
// Printable ASCII ≤ 31 chars rides as a literal readable bytes32; anything longer takes the
|
|
293
|
+
// data path (one blob, hash evented).
|
|
294
|
+
if (fitsLiteralBytes32(valueInput)) {
|
|
260
295
|
console.log(` ${key} (contract scope) ← "${valueInput}" ${dim('(literal bytes32; owner-only raw setter)')}`);
|
|
261
296
|
await runWrite(contract, prepareSetContractParam({ contract, key, value: encodeTagSdk(valueInput), display: valueInput, chainId: cid }), flags, owner);
|
|
262
297
|
}
|
|
@@ -268,16 +303,21 @@ export async function cmdConfigureParam(address, rest, flags) {
|
|
|
268
303
|
}
|
|
269
304
|
const tokenId = BigInt(tokenIdRaw);
|
|
270
305
|
if (!exists) {
|
|
271
|
-
throw new Error(`no PostParam schema for "${key}" on ${contract}.
|
|
272
|
-
`abx deploy-code … --schema ${key}:<Type>:<Auth
|
|
273
|
-
`
|
|
306
|
+
throw new Error(`no PostParam schema for "${key}" on ${contract}. Declare one — at deploy with ` +
|
|
307
|
+
`abx deploy-code … --schema ${key}:<Type>:<Auth>, or right now on the live contract with ` +
|
|
308
|
+
`abx set-schema ${contract} --schema ${key}:<Type>:<Auth> (e.g. ${key}:HexColor:TokenOwner).`);
|
|
274
309
|
}
|
|
275
310
|
const typeName = ['Bool', 'Select', 'Uint256Range', 'Int256Range', 'DecimalRange', 'HexColor', 'Timestamp', 'String', 'Bytes'][paramTypeIdx];
|
|
276
311
|
let sent;
|
|
277
312
|
if (typeName === 'String' || typeName === 'Bytes') {
|
|
278
313
|
const data = flags.file
|
|
279
314
|
? toHexSdk(new Uint8Array(readFileSync(flags.file)))
|
|
280
|
-
:
|
|
315
|
+
: encodePayloadParam(typeName, valueInput, key);
|
|
316
|
+
const bytes = (data.length - 2) / 2;
|
|
317
|
+
// Echo the DECODED byte count. The old code echoed the string's length, which is precisely how a
|
|
318
|
+
// wrong encoding announced itself and was missed: 128 packed bytes passed as base64 printed
|
|
319
|
+
// "172 bytes".
|
|
320
|
+
console.log(` ${key} (${typeName}) ← ${bytes} bytes ${dim(flags.file ? '(file contents, verbatim)' : typeName === 'Bytes' ? '(decoded from hex)' : '(UTF-8 text)')}`);
|
|
281
321
|
sent = await runWrite(contract, prepareConfigureTokenParamData({ contract, tokenId, key, data, chainId: chainId() }), flags);
|
|
282
322
|
}
|
|
283
323
|
else {
|
|
@@ -285,22 +325,7 @@ export async function cmdConfigureParam(address, rest, flags) {
|
|
|
285
325
|
console.log(` ${key} (${typeName}) ← ${display} ${dim('(canonical encode; the chain enforces schema + auth)')}`);
|
|
286
326
|
sent = await runWrite(contract, prepareConfigureTokenParam({ contract, tokenId, key, value, display, chainId: chainId() }), flags);
|
|
287
327
|
}
|
|
288
|
-
// params.keys drift nudge (best-effort, never fails the command): a project on the on-chain
|
|
289
|
-
// URI lane enumerates its param surface in the `params.keys` contract param — the canonical
|
|
290
|
-
// generator reads it to build on-chain tokenData. A configured key that isn't listed is
|
|
291
|
-
// silently OMITTED there (byte-parity with the resolver breaks), so say it, with the fix.
|
|
292
328
|
if (sent) {
|
|
293
|
-
try {
|
|
294
|
-
const csv = await readParamsKeys(publicClient, contract);
|
|
295
|
-
const fixed = paramsKeysNudge(csv, key);
|
|
296
|
-
if (fixed !== null) {
|
|
297
|
-
console.log(` ${yellow('⚠')} params.keys doesn't list "${key}" — the on-chain generator's tokenData will omit it. Fix:\n` +
|
|
298
|
-
` ${bold(`abx configure-param ${contract} - params.keys ${fixed}`)}`);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
catch {
|
|
302
|
-
/* nudge is advisory — an RPC hiccup or a non-Params contract must never fail the write */
|
|
303
|
-
}
|
|
304
329
|
// What happens to the IMAGE depends on how it's produced. If the `image` field is computed
|
|
305
330
|
// on-chain (a `renderer` representation — the in-chain SVG lane), it re-tints AUTOMATICALLY: the
|
|
306
331
|
// renderer reads the param live, so tokenURI's image is already updated, nothing to re-render.
|
|
@@ -373,8 +398,12 @@ export async function cmdSetParamHooks(address, flags) {
|
|
|
373
398
|
}
|
|
374
399
|
catch (err) {
|
|
375
400
|
await assertContractExists(contract); // no contract at all → the actionable no-contract error
|
|
376
|
-
|
|
377
|
-
|
|
401
|
+
// Name the ACTUAL kind rather than assuming 721 — a 1/1-edition or EditionImage has no param
|
|
402
|
+
// hooks either (only EditionCode composes ConfigurableParams, mirroring SeriesCode), so the old
|
|
403
|
+
// blanket "a 1/1 or a plain Series" message misnamed an edition target's real kind.
|
|
404
|
+
const kind = await detectTokenKind(publicClient, contract);
|
|
405
|
+
throw new Error(`${contract} exposes no param hooks — the configure/augment/transfer hooks are a SeriesCode/EditionCode ` +
|
|
406
|
+
`(PostParams) feature. ${kind.label} has no configurable params to hook.`);
|
|
378
407
|
}
|
|
379
408
|
const cur = { configure: current[0], augment: current[1], transfer: current[2] };
|
|
380
409
|
const label = (a) => (eqAddr(a, zeroAddress) ? dim('none') : a);
|
|
@@ -421,7 +450,8 @@ export async function cmdSetDependency(address, rest, flags) {
|
|
|
421
450
|
const [indexRaw, refRaw] = positionalArgs(rest);
|
|
422
451
|
if (indexRaw === undefined || !refRaw) {
|
|
423
452
|
console.error(`usage: ${usage}\n`);
|
|
424
|
-
process.
|
|
453
|
+
process.exitCode = 1;
|
|
454
|
+
return;
|
|
425
455
|
}
|
|
426
456
|
if (!/^\d+$/.test(indexRaw))
|
|
427
457
|
throw new Error(`<index> must be a non-negative integer (got '${indexRaw}') — the list is dense: index ≤ dependencyCount`);
|
|
@@ -445,7 +475,8 @@ export async function cmdSetDependencyRegistry(address, rest, flags) {
|
|
|
445
475
|
const [raw] = positionalArgs(rest);
|
|
446
476
|
if (!raw) {
|
|
447
477
|
console.error(`usage: ${usage}\n`);
|
|
448
|
-
process.
|
|
478
|
+
process.exitCode = 1;
|
|
479
|
+
return;
|
|
449
480
|
}
|
|
450
481
|
if (raw !== 'none' && !/^0x[0-9a-fA-F]{40}$/.test(raw)) {
|
|
451
482
|
throw new Error(`<registry> must be an address (0x + 40 hex) or 'none' to clear; got '${raw}'`);
|
|
@@ -462,30 +493,129 @@ export async function cmdLockDependencies(address, flags) {
|
|
|
462
493
|
console.log(dim(' note: locking the dependency set is permanent and irreversible (list AND registry pointer freeze).'));
|
|
463
494
|
await runWrite(contract, prepareLockDependencies({ contract, chainId: chainId() }), flags, owner);
|
|
464
495
|
}
|
|
496
|
+
// ── editions: shared small parsers ────────────────────────────────────────────
|
|
497
|
+
/** A non-negative-integer edition flag (`--token-id`, `--amount`, …) — the shared parse +
|
|
498
|
+
* bound-check so every edition command that takes "an id" or "a count" rejects the same way. */
|
|
499
|
+
export function parseEditionCountFlag(raw, flag) {
|
|
500
|
+
if (raw === 'true' || !/^\d+$/.test(raw.trim()))
|
|
501
|
+
throw new Error(`--${flag} must be a non-negative integer; got '${raw}'.`);
|
|
502
|
+
return BigInt(raw.trim());
|
|
503
|
+
}
|
|
504
|
+
/** `--token-ids <csv|range>` — the shape `ping-uri` (and any future batch-by-id command) takes: a
|
|
505
|
+
* comma-separated list of ids and/or `lo-hi` ranges (`0-9,20,25-30`), de-duplicated and sorted. */
|
|
506
|
+
export function parseTokenIdRange(raw) {
|
|
507
|
+
const ids = new Set();
|
|
508
|
+
for (const part of raw.split(',').map((s) => s.trim()).filter(Boolean)) {
|
|
509
|
+
const range = part.match(/^(\d+)-(\d+)$/);
|
|
510
|
+
if (range) {
|
|
511
|
+
const [lo, hi] = [BigInt(range[1]), BigInt(range[2])];
|
|
512
|
+
if (lo > hi)
|
|
513
|
+
throw new Error(`--token-ids: range '${part}' has lo > hi.`);
|
|
514
|
+
for (let i = lo; i <= hi; i++)
|
|
515
|
+
ids.add(i);
|
|
516
|
+
}
|
|
517
|
+
else if (/^\d+$/.test(part)) {
|
|
518
|
+
ids.add(BigInt(part));
|
|
519
|
+
}
|
|
520
|
+
else {
|
|
521
|
+
throw new Error(`--token-ids: '${part}' isn't a token id or a 'lo-hi' range.`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
if (!ids.size)
|
|
525
|
+
throw new Error("--token-ids needs at least one id (e.g. '0,1,2' or '0-99').");
|
|
526
|
+
return [...ids].sort((a, b) => Number(a - b));
|
|
527
|
+
}
|
|
465
528
|
// ── mint ─────────────────────────────────────────────────────────────────────
|
|
466
529
|
// Issue a token — a deferred mint (deploy → warm resolver → mint) or a primary sale
|
|
467
530
|
// (mint straight to the buyer). For a 1/1 this is the one-shot token #0. For a Series
|
|
468
531
|
// it mints the next sequential token id (metadata = token id): bare (one), or `--count <n>`
|
|
469
532
|
// (n in order). Owner or an authorized minter signs.
|
|
533
|
+
// For an EDITION (OneOfOneEdition/EditionImage/EditionCode) this mints copies of ONE id:
|
|
534
|
+
// --token-id (required unless the target is a 1/1-edition, whose id space is fixed to {0}) +
|
|
535
|
+
// --amount (default 1). --count is the 721 Series primitive and is refused on an edition.
|
|
470
536
|
export async function cmdMint(address, flags) {
|
|
471
|
-
const usage = 'abx mint <address> [--to 0x…] [--count <n>] [--sign|--unsigned]';
|
|
537
|
+
const usage = 'abx mint <address> [--to 0x…] [--count <n> | --token-id <id> --amount <n>] [--json] [--sign|--unsigned]';
|
|
472
538
|
const contract = requireAddress(address, usage);
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
539
|
+
warnStrayFlags(flags, new Set(MINT_FLAGS), 'mint');
|
|
540
|
+
// `--json`: the TOKEN ID is the value a program came for, and it was previously only obtainable by
|
|
541
|
+
// regex-scraping coloured prose (B19). It is read from the mint's own Transfer logs rather than by
|
|
542
|
+
// re-reading `nextTokenId` afterwards — a concurrent mint would make that answer wrong, and a
|
|
543
|
+
// number that is usually right is worse than no number.
|
|
544
|
+
return withJson(flags, async () => {
|
|
545
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
546
|
+
const kind = await detectTokenKind(publicClient, contract);
|
|
547
|
+
const owner = await read(contract, 'owner');
|
|
548
|
+
const to = flags.to ?? owner; // default: pre-mint to the admin
|
|
549
|
+
if (kind.isEdition) {
|
|
550
|
+
// `--count` is the 721 Series primitive (N sequential ids); an edition mint always names its
|
|
551
|
+
// id and an amount — there is no "next in order" to count through. Refuse, don't silently
|
|
552
|
+
// reinterpret it as something else.
|
|
553
|
+
if (flags.count !== undefined) {
|
|
554
|
+
throw new Error(`--count is a 721 Series flag (mint N tokens in order) — ${contract} is a ${kind.label} (edition). Use --token-id <id> --amount <n> instead.`);
|
|
555
|
+
}
|
|
556
|
+
// OneOfOneEdition's id space is fixed to {0}, so --token-id defaults there; EditionImage/
|
|
557
|
+
// EditionCode ids are caller-named artworks with no sensible default — require it.
|
|
558
|
+
if (kind.kind !== '1of1-edition' && flags['token-id'] === undefined) {
|
|
559
|
+
throw new Error(`--token-id is required on a ${kind.label} — its ids are caller-named artworks, not a single default. ` +
|
|
560
|
+
`See existing ids with \`abx tokens ${contract}\`.`);
|
|
561
|
+
}
|
|
562
|
+
const tokenId = flags['token-id'] !== undefined ? parseEditionCountFlag(flags['token-id'], 'token-id') : 0n;
|
|
563
|
+
const amount = flags.amount !== undefined ? parseEditionCountFlag(flags.amount, 'amount') : 1n;
|
|
564
|
+
console.log(dim(` minting ${amount} cop${amount === 1n ? 'y' : 'ies'} of #${tokenId} → ${to}${flags.to ? '' : ' (owner — pass --to for a buyer)'}`));
|
|
565
|
+
const tx = prepareEditionMint({ contract, to, tokenId, amount, chainId: chainId() });
|
|
566
|
+
const result = await runWrite(contract, tx, flags, owner);
|
|
567
|
+
if (result)
|
|
568
|
+
console.log(` ${green('✓')} minted ${amount} cop${amount === 1n ? 'y' : 'ies'} of ${bold('#' + tokenId)} → ${to}`);
|
|
569
|
+
console.log(dim(` next: \`abx refresh ${contract}\` so marketplaces pick up the change.`));
|
|
570
|
+
return {
|
|
571
|
+
contract,
|
|
572
|
+
chainId: chainId(),
|
|
573
|
+
to,
|
|
574
|
+
sent: !!result,
|
|
575
|
+
txHash: result?.txHash ?? null,
|
|
576
|
+
blockNumber: result ? String(result.blockNumber) : null,
|
|
577
|
+
tokenIds: [tokenId.toString()],
|
|
578
|
+
amount: amount.toString(),
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
// 721 path (unchanged): --token-id/--amount have no meaning here — refuse rather than silently
|
|
582
|
+
// ignore (the membrane rule: enforce, don't warn).
|
|
583
|
+
if (flags['token-id'] !== undefined || flags.amount !== undefined) {
|
|
584
|
+
throw new Error(`--token-id/--amount are edition-only (ERC-1155 copies) — ${contract} is a ${kind.label} (721). ` +
|
|
585
|
+
`Mint the next token with \`abx mint ${contract}\`${kind.kind !== '1of1' ? ' (or --count N for several in order)' : ''}.`);
|
|
586
|
+
}
|
|
587
|
+
let tx;
|
|
588
|
+
let count = 1n;
|
|
589
|
+
if (flags.count !== undefined && flags.count !== 'true') {
|
|
590
|
+
count = BigInt(flags.count);
|
|
591
|
+
console.log(dim(` minting ${count} Series tokens in order → ${to}`));
|
|
592
|
+
tx = prepareSeriesMintMany({ contract, to, count, chainId: chainId() });
|
|
593
|
+
}
|
|
594
|
+
else {
|
|
595
|
+
// Bare mint: the `mint(address)` selector is shared by the 1/1 (token #0) and a
|
|
596
|
+
// Series (next sequential token) — one path serves both.
|
|
597
|
+
console.log(dim(` minting token → ${to}${flags.to ? '' : ' (owner — pass --to for a buyer)'}`));
|
|
598
|
+
tx = prepareMint({ contract, to, chainId: chainId() });
|
|
599
|
+
}
|
|
600
|
+
const result = await runWrite(contract, tx, flags, owner);
|
|
601
|
+
const tokenIds = result ? await mintedTokenIds(makePublicClient({ chainKey: CHAIN }), contract, result.txHash) : [];
|
|
602
|
+
if (result && tokenIds.length) {
|
|
603
|
+
console.log(` ${green('✓')} minted token${tokenIds.length > 1 ? 's' : ''} ${bold(tokenIds.map((t) => '#' + t).join(', '))} → ${to}`);
|
|
604
|
+
}
|
|
605
|
+
console.log(dim(` next: \`abx refresh ${contract}\` so marketplaces pick up the new token.`));
|
|
606
|
+
return {
|
|
607
|
+
contract,
|
|
608
|
+
chainId: chainId(),
|
|
609
|
+
to,
|
|
610
|
+
// `sent: false` is the dry-run and cold-lane answer — an empty tokenIds with no explanation
|
|
611
|
+
// would read as a failed mint.
|
|
612
|
+
sent: !!result,
|
|
613
|
+
txHash: result?.txHash ?? null,
|
|
614
|
+
blockNumber: result ? String(result.blockNumber) : null,
|
|
615
|
+
tokenIds,
|
|
616
|
+
requestedCount: Number(count),
|
|
617
|
+
};
|
|
618
|
+
});
|
|
489
619
|
}
|
|
490
620
|
// ── series owner ops (minter set · supply cap · primary payee) ────────────────
|
|
491
621
|
// The multi-token knobs. All owner-only; each runs through the same signing lane +
|
|
@@ -505,9 +635,100 @@ export async function cmdSetMaxInvocations(address, flags) {
|
|
|
505
635
|
const usage = 'abx set-max-invocations <address> --max <N> [--sign|--unsigned]';
|
|
506
636
|
const contract = requireAddress(address, usage);
|
|
507
637
|
const max = BigInt(requireFlag(flags, 'max', usage));
|
|
638
|
+
// The cap only ever decreases, but `--dry-run` used to print "Set max invocations → 20" and state
|
|
639
|
+
// the new value as fact for a contract capped at 16 — then the real send reverted. A creator (or an
|
|
640
|
+
// agent) reads a clean dry run as permission to send, so the preview has to know what the chain
|
|
641
|
+
// knows. Best-effort: an unreadable getter does NOT block, since the chain enforces it regardless.
|
|
642
|
+
// `readSeries`, not `read`: the 1/1 ABI that `read` uses has no `maxInvocations` at all, so reading
|
|
643
|
+
// through it always threw and this guard silently never fired.
|
|
644
|
+
const capNow = await readSeries(contract, 'maxInvocations').catch(() => null);
|
|
645
|
+
if (capNow !== null && max > capNow) {
|
|
646
|
+
throw new Error(`${contract}'s cap is already ${capNow} and maxInvocations can only DECREASE — ${max} would raise it, which the chain refuses. ` +
|
|
647
|
+
`Pass a number at or below ${capNow} (a supply cap is one-way by design: it can be tightened, never reopened).`);
|
|
648
|
+
}
|
|
508
649
|
const owner = await read(contract, 'owner');
|
|
509
650
|
await runWrite(contract, prepareSetMaxInvocations({ contract, maxInvocations: max, chainId: chainId() }), flags, owner);
|
|
510
651
|
}
|
|
652
|
+
// ── set-max-supply (editions only) — the per-id twin of set-max-invocations ──────────────────────
|
|
653
|
+
/**
|
|
654
|
+
* `abx set-max-supply <address> --token-id <n> --cap <n>` — owner overrides ONE id's ERC-1155
|
|
655
|
+
* supply cap (Edition Supply extension). Monotonically non-increasing once used for that id — the
|
|
656
|
+
* chain enforces it (`MaxSupplyIncreaseForbidden`/`MaxSupplyBelowFloor`), and `--cap open` is
|
|
657
|
+
* refused HERE, before any gas: the contract's own "0" means "closed forever" once an id has been
|
|
658
|
+
* overridden (not "reopen to uncapped" — `EditionSupply.sol`'s own doc calls this out), so accepting
|
|
659
|
+
* `open` as an alias for 0 would silently promise the opposite of what it does on a re-run.
|
|
660
|
+
*/
|
|
661
|
+
export async function cmdSetMaxSupply(address, flags) {
|
|
662
|
+
const usage = 'abx set-max-supply <address> --token-id <n> --cap <n> [--sign|--unsigned]';
|
|
663
|
+
const contract = requireAddress(address, usage);
|
|
664
|
+
warnStrayFlags(flags, new Set(SET_MAX_SUPPLY_FLAGS), 'set-max-supply');
|
|
665
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
666
|
+
const kind = await detectTokenKind(publicClient, contract);
|
|
667
|
+
if (!kind.isEdition) {
|
|
668
|
+
throw new Error(`set-max-supply is edition-only (a per-id ERC-1155 cap) — ${contract} is a ${kind.label} (721). Use \`abx set-max-invocations\` instead (the whole-project cap).`);
|
|
669
|
+
}
|
|
670
|
+
const tokenId = parseEditionCountFlag(requireFlag(flags, 'token-id', usage), 'token-id');
|
|
671
|
+
const capRaw = requireFlag(flags, 'cap', usage);
|
|
672
|
+
if (capRaw.trim().toLowerCase() === 'open') {
|
|
673
|
+
throw new Error(`--cap open is refused: once you set a cap for #${tokenId} it can only DECREASE (never increase back to uncapped) — ` +
|
|
674
|
+
`"open" would ask for exactly the increase the chain forbids. If this id has never been overridden, it's already open ` +
|
|
675
|
+
`(the --copies default from deploy) — there's nothing to set. To lower an existing cap, pass the number.`);
|
|
676
|
+
}
|
|
677
|
+
const cap = parseEditionCountFlag(capRaw, 'cap');
|
|
678
|
+
// Both ways this reverts on chain were reachable through `--dry-run` unchanged: the preview printed
|
|
679
|
+
// "#0 supply cap → 50" and stated the new cap as fact, then the real send reverted. A dry run that
|
|
680
|
+
// green-lights an impossible write is worse than no dry run — the creator's next step is to send it.
|
|
681
|
+
// `maxSupply(id) === 0` reads as "open" (the un-overridden --copies default), so any finite cap is a
|
|
682
|
+
// decrease from open and allowed. Reads are best-effort: if either read fails we do NOT block, since
|
|
683
|
+
// the chain still enforces the invariant and a guard must not turn an RPC miss into a refusal.
|
|
684
|
+
const [capNow, supplyNow] = await Promise.all([
|
|
685
|
+
readEdition(contract, 'maxSupply', [tokenId]).catch(() => null),
|
|
686
|
+
readEdition(contract, 'totalSupply', [tokenId]).catch(() => null),
|
|
687
|
+
]);
|
|
688
|
+
if (capNow !== null && capNow > 0n && cap > capNow) {
|
|
689
|
+
throw new Error(`#${tokenId}'s cap is already ${capNow} and a cap can only DECREASE — ${cap} would raise it, which the chain refuses. ` +
|
|
690
|
+
`Pass a number at or below ${capNow}${supplyNow !== null ? ` and at or above its ${supplyNow} live cop${supplyNow === 1n ? 'y' : 'ies'}` : ''}.`);
|
|
691
|
+
}
|
|
692
|
+
if (supplyNow !== null && cap < supplyNow) {
|
|
693
|
+
throw new Error(`#${tokenId} already has ${supplyNow} cop${supplyNow === 1n ? 'y' : 'ies'} minted, so a cap of ${cap} would sit BELOW live supply — the chain refuses that. ` +
|
|
694
|
+
`The lowest cap you can set is ${supplyNow} (which closes the id to further minting).`);
|
|
695
|
+
}
|
|
696
|
+
const owner = await read(contract, 'owner');
|
|
697
|
+
console.log(dim(` #${tokenId} supply cap → ${cap}`));
|
|
698
|
+
await runWrite(contract, prepareSetMaxSupply({ contract, tokenId, cap, chainId: chainId() }), flags, owner);
|
|
699
|
+
}
|
|
700
|
+
// ── ping-uri (editions only) — permissionless URI re-emission ────────────────────────────────────
|
|
701
|
+
/** How many ids one `pingURI` call carries per transaction — large enough that a normal collection
|
|
702
|
+
* fits in one tx, small enough that a genuinely huge id list doesn't build one unbounded call. */
|
|
703
|
+
const PING_URI_CHUNK_SIZE = 200;
|
|
704
|
+
/**
|
|
705
|
+
* `abx ping-uri <address> --token-ids <csv|range>` — re-emit the native ERC-1155 `URI` event for
|
|
706
|
+
* the given ids after a contract-wide re-point (`set-token-uri`/`set-renderer`), so marketplaces/
|
|
707
|
+
* indexers that only honor the native event re-index. Permissionless (anyone may call it — it only
|
|
708
|
+
* re-emits already-public, current truth), so there is no owner check and no `expectedSigner` to
|
|
709
|
+
* pin; whichever signer the active lane resolves sends it. Chunks a large id list into several
|
|
710
|
+
* transactions, each through the SAME `--dry-run`/`--confirm` gate as any other write.
|
|
711
|
+
*/
|
|
712
|
+
export async function cmdPingUri(address, flags) {
|
|
713
|
+
const usage = 'abx ping-uri <address> --token-ids <csv|range> [--sign|--unsigned]';
|
|
714
|
+
const contract = requireAddress(address, usage);
|
|
715
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
716
|
+
const kind = await detectTokenKind(publicClient, contract);
|
|
717
|
+
if (!kind.isEdition) {
|
|
718
|
+
throw new Error(`ping-uri is edition-only — it re-emits the ERC-1155 URI event, which a ${kind.label} (721) doesn't have ` +
|
|
719
|
+
`(721 emits ERC-4906 MetadataUpdate automatically on a URI change — nothing to re-emit by hand).`);
|
|
720
|
+
}
|
|
721
|
+
const ids = parseTokenIdRange(requireFlag(flags, 'token-ids', usage));
|
|
722
|
+
const chunks = [];
|
|
723
|
+
for (let i = 0; i < ids.length; i += PING_URI_CHUNK_SIZE)
|
|
724
|
+
chunks.push(ids.slice(i, i + PING_URI_CHUNK_SIZE));
|
|
725
|
+
console.log(dim(` re-emitting URI for ${ids.length} id${ids.length === 1 ? '' : 's'} — permissionless (no owner check) — ${chunks.length} tx${chunks.length === 1 ? '' : '(s)'} of up to ${PING_URI_CHUNK_SIZE} id(s) each`));
|
|
726
|
+
for (const [i, chunk] of chunks.entries()) {
|
|
727
|
+
if (chunks.length > 1)
|
|
728
|
+
console.log(dim(` chunk ${i + 1}/${chunks.length}: ${chunk.length} id(s) (#${chunk[0]}–#${chunk[chunk.length - 1]})`));
|
|
729
|
+
await runWrite(contract, preparePingURI({ contract, tokenIds: chunk, chainId: chainId() }), flags);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
511
732
|
/** Pause minting — restrict it to the owner (config/reserves) until unpaused. */
|
|
512
733
|
export async function cmdPause(address, flags) {
|
|
513
734
|
const contract = requireAddress(address, 'abx pause <address> [--sign|--unsigned]');
|
|
@@ -551,15 +772,29 @@ export async function cmdSetPrimaryPayee(address, flags) {
|
|
|
551
772
|
// marketplaces fetch the on-chain tokenURI; if the resolver wasn't warm they cache
|
|
552
773
|
// a miss until refreshed. We emit ERC-4906 on URI changes (4906-aware marketplaces
|
|
553
774
|
// auto-refresh) — this is the manual fallback for the rest, and after the genesis mint.
|
|
554
|
-
|
|
555
|
-
|
|
775
|
+
/**
|
|
776
|
+
* OpenSea's own chain slugs, keyed by ours. They are NOT our keys (`base-sepolia` is `base_sepolia`
|
|
777
|
+
* there) and not derivable from viem, so the map is unavoidable — but a chain missing from it must
|
|
778
|
+
* produce NO link rather than a wrong one, which is what `osChain ?? CHAIN` used to do.
|
|
779
|
+
*
|
|
780
|
+
* It previously listed only `sepolia` and `mainnet`, so the CLI's own DEFAULT chain (`base-sepolia`)
|
|
781
|
+
* fell through to the raw key: the refresh POST went to `/chain/base-sepolia/…` (a slug OpenSea does
|
|
782
|
+
* not know) and the printed link pointed at **mainnet** `opensea.io` for a testnet token. Same shape
|
|
783
|
+
* as the hardcoded explorer table that once sent every Base Sepolia link to Etherscan — hence
|
|
784
|
+
* `testnet` now comes from the chain registry instead of a second hand-maintained set.
|
|
785
|
+
*/
|
|
786
|
+
const OPENSEA_CHAIN = { 'base-sepolia': 'base_sepolia', sepolia: 'sepolia' };
|
|
556
787
|
export async function cmdRefresh(address, flags) {
|
|
557
788
|
const contract = requireAddress(address, 'abx refresh <address> [--token 0]');
|
|
558
789
|
const tokenId = flags.token ?? '0';
|
|
559
|
-
const
|
|
560
|
-
const
|
|
790
|
+
const chain = resolveChain(CHAIN);
|
|
791
|
+
const osChain = OPENSEA_CHAIN[CHAIN];
|
|
792
|
+
const explorer = chain.blockExplorers?.default?.url ?? '';
|
|
561
793
|
const apiKey = process.env.OPENSEA_API_KEY;
|
|
562
|
-
if (
|
|
794
|
+
if (!osChain) {
|
|
795
|
+
console.log(dim(` no OpenSea slug known for '${CHAIN}' — skipping the OpenSea refresh (a guessed slug 404s, and a guessed link would point at the wrong network).`));
|
|
796
|
+
}
|
|
797
|
+
else if (apiKey) {
|
|
563
798
|
const url = `https://api.opensea.io/api/v2/chain/${osChain}/contract/${contract}/nfts/${tokenId}/refresh`;
|
|
564
799
|
try {
|
|
565
800
|
const res = await fetch(url, { method: 'POST', headers: { 'x-api-key': apiKey, accept: 'application/json' } });
|
|
@@ -575,17 +810,69 @@ export async function cmdRefresh(address, flags) {
|
|
|
575
810
|
else {
|
|
576
811
|
console.log(dim(' no OPENSEA_API_KEY set — open these and click “Refresh metadata”:'));
|
|
577
812
|
}
|
|
578
|
-
|
|
579
|
-
|
|
813
|
+
// `testnet` from the chain registry (viem), never a local set — that is the drift this bug was.
|
|
814
|
+
const osBase = chain.testnet ? 'https://testnets.opensea.io' : 'https://opensea.io';
|
|
815
|
+
if (osChain)
|
|
816
|
+
console.log(` ${dim('OpenSea ')}${osBase}/assets/${osChain}/${contract}/${tokenId}`);
|
|
580
817
|
if (explorer)
|
|
581
818
|
console.log(` ${dim('Etherscan')} ${explorer}/token/${contract}?a=${tokenId}`);
|
|
582
|
-
|
|
819
|
+
// This line used to claim ERC-4906 had already pinged 4906-aware marketplaces — unconditionally.
|
|
820
|
+
// An ERC-1155 edition emits NO ERC-4906 (that is exactly why `ping-uri` exists), so on an edition
|
|
821
|
+
// the sentence was false in the one direction that costs the creator something: they read "already
|
|
822
|
+
// handled", skipped `ping-uri`, and the native URI event was never re-emitted, so nothing
|
|
823
|
+
// re-indexed. `ping-uri --help` said the opposite, leaving two commands contradicting each other.
|
|
824
|
+
// Best-effort probe: `refresh` otherwise needs no chain read at all, so an RPC miss must still let
|
|
825
|
+
// it print its links — it just falls back to naming both cases.
|
|
826
|
+
const isEdition = await isEditionContract(makePublicClient({ chainKey: CHAIN }), contract).catch(() => null);
|
|
827
|
+
if (isEdition === true) {
|
|
828
|
+
console.log(dim(' (an ERC-1155 edition emits NO ERC-4906 — nothing auto-pinged. After a URI/renderer re-point also run:'));
|
|
829
|
+
console.log(dim(` \`abx ping-uri ${contract} --token-ids ${tokenId}\` to re-emit the native URI event for indexers that honor it.)`));
|
|
830
|
+
}
|
|
831
|
+
else if (isEdition === false) {
|
|
832
|
+
console.log(dim(' (ERC-4906 already pings 4906-aware marketplaces on URI changes; this covers the genesis mint + the rest.)'));
|
|
833
|
+
}
|
|
834
|
+
else {
|
|
835
|
+
console.log(dim(' (on a 721, ERC-4906 already pinged 4906-aware marketplaces; on an ERC-1155 edition nothing did — run `abx ping-uri` there.)'));
|
|
836
|
+
}
|
|
583
837
|
}
|
|
584
838
|
// ── transfer ─────────────────────────────────────────────────────────────────
|
|
585
839
|
export async function cmdTransfer(address, flags) {
|
|
586
|
-
const
|
|
587
|
-
const
|
|
588
|
-
|
|
840
|
+
const usage = 'abx transfer <address> --to 0x… [--token 0 | --token-id 0] [--amount <n> --from 0x… (editions only)] [--sign|--unsigned]';
|
|
841
|
+
const contract = requireAddress(address, usage);
|
|
842
|
+
warnStrayFlags(flags, new Set(TRANSFER_FLAGS), 'transfer');
|
|
843
|
+
const to = requireFlag(flags, 'to', usage);
|
|
844
|
+
// `--token-id` is accepted as an alias for `--token`: EVERY sibling id-taking command (`mint`,
|
|
845
|
+
// `set-max-supply`, `minter …`) spells it `--token-id`, so an agent that learned the name there
|
|
846
|
+
// passed it here — where it was silently ignored and id 0 moved instead of the id they named.
|
|
847
|
+
// On an edition that means transferring the WRONG ARTWORK with no warning. Both spellings work now;
|
|
848
|
+
// disagreeing values are refused rather than silently preferring one.
|
|
849
|
+
if (flags.token !== undefined && flags['token-id'] !== undefined && flags.token !== flags['token-id']) {
|
|
850
|
+
throw new Error(`--token ${flags.token} and --token-id ${flags['token-id']} disagree — pass one (they are aliases for the same id).`);
|
|
851
|
+
}
|
|
852
|
+
const tokenId = BigInt(flags['token-id'] ?? flags.token ?? '0');
|
|
853
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
854
|
+
const kind = await detectTokenKind(publicClient, contract);
|
|
855
|
+
if (kind.isEdition) {
|
|
856
|
+
const amount = flags.amount !== undefined ? parseEditionCountFlag(flags.amount, 'amount') : 1n;
|
|
857
|
+
// Unlike a 721 (one holder, read on-chain via ownerOf), an edition id can have MANY concurrent
|
|
858
|
+
// holders — there is no single "the owner" to move copies from, so the holder must be named.
|
|
859
|
+
const fromRaw = flags.from;
|
|
860
|
+
if (!fromRaw || fromRaw === 'true') {
|
|
861
|
+
throw new Error(`--from 0x.. is required on a ${kind.label} — an edition id can have many concurrent holders, so ` +
|
|
862
|
+
`there is no single current owner to read on-chain (unlike a 721). Pass the holder's address.`);
|
|
863
|
+
}
|
|
864
|
+
if (!isAddress(fromRaw))
|
|
865
|
+
throw new Error(`--from must be a 0x address; got '${fromRaw}'.`);
|
|
866
|
+
const from = getAddress(fromRaw);
|
|
867
|
+
const tx = prepareEditionTransfer({ contract, from, to, tokenId, amount, chainId: chainId() });
|
|
868
|
+
await runWrite(contract, tx, flags, from);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
// 721 path (unchanged): --amount has no meaning — a token transfers as a whole. Refuse rather
|
|
872
|
+
// than silently ignore.
|
|
873
|
+
if (flags.amount !== undefined) {
|
|
874
|
+
throw new Error(`--amount is edition-only (ERC-1155 copies) — ${contract} is a ${kind.label} (721), where a token transfers as a whole. Drop --amount.`);
|
|
875
|
+
}
|
|
589
876
|
const from = await read(contract, 'ownerOf', [tokenId]);
|
|
590
877
|
const tx = prepareTransfer({ contract, from, to, tokenId, chainId: chainId() });
|
|
591
878
|
await runWrite(contract, tx, flags, from);
|
|
@@ -648,126 +935,195 @@ export async function cmdSetRoyalty(address, flags) {
|
|
|
648
935
|
}
|
|
649
936
|
await runWrite(contract, prepareSetRoyalty({ contract, receiver, bps, chainId: chainId() }), flags, owner);
|
|
650
937
|
}
|
|
938
|
+
// ── ERC-721C (creator token) — the transfer-validator surface ─────────────────
|
|
939
|
+
// Enrollment is a DEPLOY-TIME decision (`--721c` on the deploy commands) and permanent in both
|
|
940
|
+
// directions: an unenrolled token can never gain a validator, an enrolled one never sheds the
|
|
941
|
+
// standard. Within an enrolled token the owner re-points or suspends (zero) the validator freely.
|
|
942
|
+
/** The chain keys the manifest recommends a transfer validator for — for refusal messages. */
|
|
943
|
+
function chainsWithRecommendedValidator() {
|
|
944
|
+
const ids = new Set(Object.keys(RECOMMENDED_TRANSFER_VALIDATOR).map(Number));
|
|
945
|
+
return KNOWN_CHAIN_KEYS.filter((k) => ids.has(resolveChain(k).id)).join(', ');
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* Parse a transfer-validator choice — the shared grammar of the deploy flag (`--721c`) and the
|
|
949
|
+
* owner op (`abx set-transfer-validator`):
|
|
950
|
+
* - `recommended` (or a bare `--721c`) → the per-chain recommended validator, refusing on a
|
|
951
|
+
* chain the manifest has no entry for (naming the chains that do — never guess one);
|
|
952
|
+
* - a `0x…` address → checksum-validated (EIP-55) and returned as its canonical form;
|
|
953
|
+
* - `none`/zero → `allowNone` decides: the owner op suspends with it; the DEPLOY flag refuses
|
|
954
|
+
* it (a zero validator at deploy never enrolls — that is already the default, so someone
|
|
955
|
+
* passing it either wants plain ERC-721 (drop the flag) or mistakenly believes "enrolled but
|
|
956
|
+
* suspended" is a deploy-time state — it isn't).
|
|
957
|
+
* Pure (no RPC) — callers do the has-code precheck themselves. Exported for the regression test.
|
|
958
|
+
*/
|
|
959
|
+
export function parseTransferValidatorValue(raw, opts) {
|
|
960
|
+
const s = raw.trim().toLowerCase();
|
|
961
|
+
if (s === 'true' || s === '' || s === 'recommended') {
|
|
962
|
+
const rec = resolveRecommendedTransferValidator(opts.chainId);
|
|
963
|
+
if (!rec) {
|
|
964
|
+
throw new Error(`no recommended transfer validator is known for '${opts.chainLabel}' (chainId ${opts.chainId}) — ` +
|
|
965
|
+
`chains with one: ${chainsWithRecommendedValidator() || '(none shipped)'}. ` +
|
|
966
|
+
`Pass an explicit validator address instead (it must be a deployed contract on this chain).`);
|
|
967
|
+
}
|
|
968
|
+
return rec;
|
|
969
|
+
}
|
|
970
|
+
if (s === 'none' || s === 'zero' || s === '0' || s === '0x0' || s === zeroAddress) {
|
|
971
|
+
if (opts.allowNone)
|
|
972
|
+
return zeroAddress;
|
|
973
|
+
throw new Error(`a zero transfer validator never enrolls — a plain (unenrolled) token is already the default, so drop --721c. ` +
|
|
974
|
+
`("enrolled but suspended" is not a deploy-time state: enroll with a real validator, then suspend ` +
|
|
975
|
+
`with \`abx set-transfer-validator <address> none\`.)`);
|
|
976
|
+
}
|
|
977
|
+
const trimmed = raw.trim();
|
|
978
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(trimmed)) {
|
|
979
|
+
throw new Error(`transfer validator must be 'recommended'${opts.allowNone ? ", 'none'," : ''} or a 0x address (0x + 40 hex); got '${raw}'`);
|
|
980
|
+
}
|
|
981
|
+
// `isAddress` strict-validates the EIP-55 checksum of a mixed-case address (all-lowercase carries
|
|
982
|
+
// no checksum and passes); `getAddress` alone only NORMALIZES — it would silently accept a
|
|
983
|
+
// mis-cased paste, which is exactly the transposition this check exists to catch.
|
|
984
|
+
if (!isAddress(trimmed, { strict: true })) {
|
|
985
|
+
throw new Error(`transfer validator address failed its EIP-55 checksum: '${raw}' — paste it exactly (or all-lowercase).`);
|
|
986
|
+
}
|
|
987
|
+
return getAddress(trimmed);
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* `abx set-transfer-validator <address> <0x…|none|recommended>` — re-point an ENROLLED (ERC-721C)
|
|
991
|
+
* collection's transfer validator, or suspend enforcement with `none` (address(0); the token
|
|
992
|
+
* STAYS enrolled). Refuses up front, before any signing: a plain ERC-721 (enrollment is
|
|
993
|
+
* deploy-time-only — the contract would revert `NotCreatorToken()`), and a codeless validator
|
|
994
|
+
* (would revert `InvalidTransferValidator()`). Owner-only, any lane, guards `--dry-run`.
|
|
995
|
+
*/
|
|
996
|
+
export async function cmdSetTransferValidator(address, rest, flags) {
|
|
997
|
+
const usage = 'abx set-transfer-validator <address> <0x…|none|recommended> [--sign|--unsigned] [--dry-run]';
|
|
998
|
+
const contract = requireAddress(address, usage);
|
|
999
|
+
const [raw] = positionalArgs(rest);
|
|
1000
|
+
if (!raw) {
|
|
1001
|
+
console.error(`usage: ${usage}\n`);
|
|
1002
|
+
process.exitCode = 1;
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
const cid = chainId();
|
|
1006
|
+
const validator = parseTransferValidatorValue(raw, { chainId: cid, chainLabel: CHAIN, allowNone: true });
|
|
1007
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
1008
|
+
// Enrollment guard FIRST — a read, not a send. An unenrolled token would revert
|
|
1009
|
+
// `NotCreatorToken()`; refuse with the real story instead of letting the chain say it in hex.
|
|
1010
|
+
// (readCreatorTokenStatus is defensive, so check the contract exists first — a typo'd address
|
|
1011
|
+
// must not read as "plain ERC-721".)
|
|
1012
|
+
await assertContractExists(contract);
|
|
1013
|
+
const status = await readCreatorTokenStatus(publicClient, contract);
|
|
1014
|
+
if (!status.enrolled) {
|
|
1015
|
+
throw new Error(`${contract} did not enroll as a creator token — 721C/1155C enrollment is a deploy-time decision. ` +
|
|
1016
|
+
`Enrollment can never be added to a live collection; if enforcement is required, redeploy with ` +
|
|
1017
|
+
`--721c recommended (or --721c 0x…) on the deploy command.`);
|
|
1018
|
+
}
|
|
1019
|
+
// Codeless-validator guard: the contract refuses a non-zero validator with no code
|
|
1020
|
+
// (`InvalidTransferValidator()`) — surface it before gas is spent.
|
|
1021
|
+
if (validator !== zeroAddress) {
|
|
1022
|
+
let code;
|
|
1023
|
+
try {
|
|
1024
|
+
code = await publicClient.getCode({ address: validator });
|
|
1025
|
+
}
|
|
1026
|
+
catch (err) {
|
|
1027
|
+
throw new Error(`couldn't verify the validator has code at ${validator} (${err.message}) — refusing to re-point blind; retry when the RPC answers.`);
|
|
1028
|
+
}
|
|
1029
|
+
if (!code || code === '0x') {
|
|
1030
|
+
const rec = resolveRecommendedTransferValidator(cid);
|
|
1031
|
+
throw new Error(`no contract code at ${validator} on ${CHAIN} — the token would revert InvalidTransferValidator(). ` +
|
|
1032
|
+
`A transfer validator must be a DEPLOYED contract on this chain` +
|
|
1033
|
+
(rec ? ` (the recommended one: \`abx set-transfer-validator ${contract} recommended\` → ${rec})` : '') + `.`);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
if (eqAddr(status.validator, validator)) {
|
|
1037
|
+
console.log(dim(` no change — the validator is already ${validator === zeroAddress ? 'suspended (0x0)' : validator}. Nothing sent.`));
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
const label = (a) => (eqAddr(a, zeroAddress) ? 'suspended (0x0)' : a);
|
|
1041
|
+
console.log(dim(` transfer validator: ${label(status.validator)} → ${label(validator)}${validator === zeroAddress ? ' — transfers go unvalidated until one is set again (the token stays enrolled)' : ''}`));
|
|
1042
|
+
const owner = await read(contract, 'owner');
|
|
1043
|
+
await runWrite(contract, prepareSetTransferValidator({ contract, validator, chainId: cid }), flags, owner);
|
|
1044
|
+
}
|
|
1045
|
+
// ── multi-chunk on-chain content (the `reader` path) ─────────────────────────
|
|
1046
|
+
// The plan math (chunk count + tx shape), the cost-model constants, and the actual
|
|
1047
|
+
// plan→resolve-store→stage→encode orchestration all live in the SDK's staging.ts, layered on
|
|
1048
|
+
// planChunks/planContentTxs/stageContent/encodeReader/ensureChunkStore — see its module doc. What
|
|
1049
|
+
// stays here is Node-only (reading the file, gzip) plus the narration: every console.log below is
|
|
1050
|
+
// this file's onEvent handler for the SDK's `StagingEvent`, so the lines are unchanged from before
|
|
1051
|
+
// the move.
|
|
651
1052
|
export function parseCompress(v) {
|
|
652
1053
|
const c = (v ?? 'none').toLowerCase();
|
|
653
1054
|
if (c === 'none' || c === 'fastlz' || c === 'gzip')
|
|
654
1055
|
return c;
|
|
655
1056
|
throw new Error(`--compress must be none | fastlz | gzip (got '${v}')`);
|
|
656
1057
|
}
|
|
1058
|
+
/** The chunk-store bootstrap narration shared by every content-staging path below — one place so
|
|
1059
|
+
* the lines are identical whether the store is resolved for a single field ({@link putContentOnChain}
|
|
1060
|
+
* → the SDK's `stageFieldContent`) or once up front for a whole batch ({@link ensureChunkStore}). */
|
|
1061
|
+
function printChunkStoreEvent(e) {
|
|
1062
|
+
if (e.kind === 'stale')
|
|
1063
|
+
console.log(yellow(` configured chunk store ${e.address} is a stale deployment (no writeContent) — deploying a current one`));
|
|
1064
|
+
else if (e.kind === 'canonical')
|
|
1065
|
+
console.log(dim(` using the canonical chunk store at its deterministic address ${e.address}`));
|
|
1066
|
+
else if (e.kind === 'deploying')
|
|
1067
|
+
console.log(dim(' deploying the canonical multi-chunk content store (AbxChunkStore) — CREATE2…'));
|
|
1068
|
+
else {
|
|
1069
|
+
console.log(` ${green('✓')} chunk store ${e.address}`);
|
|
1070
|
+
console.log(dim(` not in the shipped manifest for ${CHAIN} — to reuse it set ABX_CHUNK_STORE=${e.address} (or add it to packages/sdk/src/deployments.ts)`));
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
657
1073
|
/**
|
|
658
1074
|
* The chain's shared multi-chunk store/reader; deploy it once if missing, signing through
|
|
659
1075
|
* `send` (the env key on the hot lane, or the connected wallet on the wallet lane) — the
|
|
660
|
-
* store is ownerless, so any funded signer can stand it up.
|
|
1076
|
+
* store is ownerless, so any funded signer can stand it up. Used directly only by
|
|
1077
|
+
* {@link stageImageFieldsBatch} (resolving ONE store up front for every token); a single-field
|
|
1078
|
+
* stage ({@link putContentOnChain}) resolves its store through the SDK's `stageFieldContent`
|
|
1079
|
+
* instead, which calls the very same SDK `ensureChunkStore` internally.
|
|
661
1080
|
*/
|
|
662
1081
|
async function ensureChunkStore(send, override) {
|
|
663
|
-
//
|
|
664
|
-
//
|
|
665
|
-
|
|
1082
|
+
// The resolution logic lives in the SDK (`ensureChunkStore`) so an SDK integrator bootstraps
|
|
1083
|
+
// identically instead of hand-rolling the "is this store capable?" guard — forget it and an
|
|
1084
|
+
// incapable store fails deep inside a mint, after transactions have landed. The CLI keeps only the
|
|
1085
|
+
// narration: the SDK reports progress through `onEvent` rather than printing.
|
|
666
1086
|
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
667
|
-
|
|
668
|
-
const code = await publicClient.getCode({ address: known });
|
|
669
|
-
if (code && code !== '0x') {
|
|
670
|
-
// Has code, but is it the *current* store? A pre-`writeContent` deployment passes a
|
|
671
|
-
// bare code check yet reverts the staging call — verify the ABI, don't just assume.
|
|
672
|
-
if (await storeSupportsWriteContent(publicClient, known))
|
|
673
|
-
return known;
|
|
674
|
-
console.log(yellow(` configured chunk store ${known} is a stale deployment (no writeContent) — deploying a current one`));
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
// No usable listed store. The canonical store is CREATE2-deterministic, so it may already exist at
|
|
678
|
-
// its predicted address — deployed by the forge script (or a prior lazy deploy) with the manifest
|
|
679
|
-
// not yet updated. Check there before deploying: self-healing, and never a duplicate at a random
|
|
680
|
-
// CREATE address. `deployChunkStore` (below) also lands at exactly this address.
|
|
681
|
-
const predicted = predictChunkStore();
|
|
682
|
-
if (!known || known.toLowerCase() !== predicted.toLowerCase()) {
|
|
683
|
-
const pcode = await publicClient.getCode({ address: predicted });
|
|
684
|
-
if (pcode && pcode !== '0x' && (await storeSupportsWriteContent(publicClient, predicted))) {
|
|
685
|
-
console.log(dim(` using the canonical chunk store at its deterministic address ${predicted}`));
|
|
686
|
-
return predicted;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
console.log(dim(' deploying the canonical multi-chunk content store (AbxChunkStore) — CREATE2…'));
|
|
690
|
-
const { chunkStore } = await deployChunkStore(send);
|
|
691
|
-
console.log(` ${green('✓')} chunk store ${chunkStore}`);
|
|
692
|
-
console.log(dim(` not in the shipped manifest for ${CHAIN} — to reuse it set ABX_CHUNK_STORE=${chunkStore} (or add it to packages/sdk/src/deployments.ts)`));
|
|
693
|
-
return chunkStore;
|
|
1087
|
+
return sdkEnsureChunkStore(publicClient, send, { chainId: chainId(), override, onEvent: printChunkStoreEvent });
|
|
694
1088
|
}
|
|
695
1089
|
/**
|
|
696
|
-
* The hot-lane staging signer: the env key signs + broadcasts each chunk-store write
|
|
697
|
-
*
|
|
698
|
-
*
|
|
699
|
-
*
|
|
1090
|
+
* The hot-lane staging signer: the env key signs + broadcasts each chunk-store write, via the
|
|
1091
|
+
* SDK's `makeHotSender` (pinned nonce, pinned gas, typed revert). Built lazily so commands that
|
|
1092
|
+
* never stage on-chain don't require a key. The wallet lane passes a session-backed sender
|
|
1093
|
+
* instead (see {@link openWalletSession}); the cold lane can't stage interactively, so it's
|
|
1094
|
+
* rejected up front by the deploy/set-field commands.
|
|
700
1095
|
*/
|
|
701
1096
|
export function envStagingSender() {
|
|
702
1097
|
const { wallet, account } = makeWalletClient({ chainKey: CHAIN });
|
|
703
1098
|
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
704
|
-
return
|
|
705
|
-
const hash = await wallet.sendTransaction({
|
|
706
|
-
account,
|
|
707
|
-
chain: wallet.chain,
|
|
708
|
-
to: tx.to ?? undefined,
|
|
709
|
-
data: tx.data,
|
|
710
|
-
value: 0n,
|
|
711
|
-
});
|
|
712
|
-
return publicClient.waitForTransactionReceipt({ hash });
|
|
713
|
-
};
|
|
1099
|
+
return makeHotSender({ wallet, account, publicClient });
|
|
714
1100
|
}
|
|
715
1101
|
/** Wallet-lane staging signer: each chunk-store write is approved in the human's browser
|
|
716
|
-
* wallet through the open {@link WalletSession}, sharing one connection with the final tx.
|
|
1102
|
+
* wallet through the open {@link WalletSession}, sharing one connection with the final tx. A
|
|
1103
|
+
* {@link PreparedTx} already carries everything `session.send` needs, so this is a thin adapter. */
|
|
717
1104
|
export function sessionStagingSender(session) {
|
|
718
|
-
|
|
719
|
-
return async (tx) => (await session.send({
|
|
720
|
-
op: 'stage',
|
|
721
|
-
to: tx.to,
|
|
722
|
-
data: tx.data,
|
|
723
|
-
value: '0x0',
|
|
724
|
-
chainId: id,
|
|
725
|
-
summary: tx.summary,
|
|
726
|
-
fields: tx.fields,
|
|
727
|
-
})).receipt;
|
|
1105
|
+
return async (tx) => (await session.send(tx)).receipt;
|
|
728
1106
|
}
|
|
729
|
-
/**
|
|
730
|
-
* Put `content` on-chain as SSTORE2 chunks behind the shared reader, and return the field's
|
|
731
|
-
* `(representation, value)`. `fastlz` compresses per chunk (reader decodes on read → stays
|
|
732
|
-
* on-chain renderable); `gzip` compresses the whole content (off-chain decode → the
|
|
733
|
-
* `reader-gzip` representation, not on-chain renderable).
|
|
734
|
-
*
|
|
735
|
-
* Staging is one atomic `writeContent` when the content fits a single tx's gas, else
|
|
736
|
-
* gas-bounded chunk-write `multicall`s plus a final manifest write — {@link stageContent}
|
|
737
|
-
* picks, and we print the tx plan up front so the human knows the count before signing.
|
|
738
|
-
* These store writes use the env key (the data contracts are ownerless); the owner only
|
|
739
|
-
* signs the field set that references the manifest.
|
|
740
|
-
*/
|
|
741
|
-
/**
|
|
742
|
-
* Pure staging plan for a piece of content — chunk count + transaction shape — with NO
|
|
743
|
-
* chain writes, no signer, no `ensureChunkStore`. Shared by {@link putContentOnChain}
|
|
744
|
-
* (which then actually stages) and the deploy dry-run preview, so the count the human is
|
|
745
|
-
* told up front is the same one the real staging will produce. `chunkSize` defaults to the
|
|
746
|
-
* SDK's {@link planChunks} default (currently 22 KB), so e.g. a 2.8 KB SVG is 1 chunk.
|
|
747
|
-
*/
|
|
748
|
-
// On-chain image storage costs ~200 gas/byte (SSTORE2 code deposit) + per-chunk tx overhead, so it
|
|
749
|
-
// is cost-effective ONLY for tiny art. Past these soft limits, off-chain (Arweave pay-once, or a
|
|
750
|
-
// hosted resolver + IPFS) is FAR cheaper — on-chain's remaining edge is self-resolution, not cost.
|
|
751
|
-
// Per-file limit ≈ one 22 KB storage chunk; project limit caps the whole collection's gas.
|
|
752
|
-
export const ONCHAIN_IMAGE_SOFT_LIMIT = 24 * 1024; // per file
|
|
753
|
-
export const ONCHAIN_PROJECT_SOFT_LIMIT = 256 * 1024; // whole collection
|
|
754
1107
|
const kb = (n) => `${n < 10 * 1024 ? (n / 1024).toFixed(1) : Math.round(n / 1024)}KB`;
|
|
755
1108
|
/** Warn (loudly) when content is too big for on-chain to be the cost-sane choice. Returns true if it warned. */
|
|
756
1109
|
export function warnIfLargeForOnChain(bytesLen, label) {
|
|
757
|
-
if (bytesLen
|
|
1110
|
+
if (!exceedsOnchainSoftLimit(bytesLen))
|
|
758
1111
|
return false;
|
|
759
1112
|
console.log(yellow(` ⚠ ${label} is ${kb(bytesLen)} — large for ON-CHAIN storage (~200 gas/byte). Past ~${kb(ONCHAIN_IMAGE_SOFT_LIMIT)}/file, on-chain is FAR more expensive than off-chain, not cheaper.`));
|
|
760
1113
|
console.log(dim(` For art this size prefer off-chain: --backend arweave (pay-once, permanent) or a hosted resolver + IPFS. Use on-chain only if self-resolution is a hard requirement.`));
|
|
761
1114
|
return true;
|
|
762
1115
|
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Pure staging plan for a piece of content — chunk count + transaction shape — with NO chain
|
|
1118
|
+
* writes, no signer, no `ensureChunkStore`. The CLI-facing wrapper over the SDK's pure
|
|
1119
|
+
* {@link planStagedContent}: `gzip` is a Node-only transform, so it happens here (not in the SDK —
|
|
1120
|
+
* see staging.ts's module doc) before handing the result off to the SDK's chunk/tx-shape math.
|
|
1121
|
+
* Shared by {@link putContentOnChain} (which then actually stages) and the deploy dry-run preview,
|
|
1122
|
+
* so the count the human is told up front is the same one the real staging will produce.
|
|
1123
|
+
*/
|
|
763
1124
|
export function computeContentPlan(bytes, compress) {
|
|
764
1125
|
const content = compress === 'gzip' ? new Uint8Array(gzipSync(bytes)) : new Uint8Array(bytes);
|
|
765
|
-
|
|
766
|
-
const planned = planChunks(content, { fastlz });
|
|
767
|
-
const plan = planContentTxs(planned);
|
|
768
|
-
const representation = compress === 'gzip' ? R.readerGzip : R.reader;
|
|
769
|
-
const stagedBytes = planned.reduce((n, c) => n + c.data.length, 0);
|
|
770
|
-
return { content, fastlz, chunks: planned.length, stagedBytes, plan, representation };
|
|
1126
|
+
return planStagedContent(content, compress);
|
|
771
1127
|
}
|
|
772
1128
|
/** Human-readable size line for a content plan, e.g. `2812B → 1 chunk [fastlz 2812→904B]`. */
|
|
773
1129
|
function planSizeLine(bytes, p, compress) {
|
|
@@ -789,15 +1145,43 @@ function planTxLine(p, finalLabel) {
|
|
|
789
1145
|
? `plan: 1 staging tx (atomic writeContent) + ${finalLabel} = 2 transactions`
|
|
790
1146
|
: `plan: ${p.plan.batches.length} chunk-batch tx(s) + 1 manifest tx + ${finalLabel} = ${p.plan.txCount + 1} transactions`;
|
|
791
1147
|
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Put `bytes` on-chain as SSTORE2 chunks behind the shared reader, and return the field's
|
|
1150
|
+
* `(representation, value)`. `fastlz` compresses per chunk (reader decodes on read → stays
|
|
1151
|
+
* on-chain renderable); `gzip` compresses the whole content (off-chain decode → the
|
|
1152
|
+
* `reader-gzip` representation, not on-chain renderable) — done here, not in the SDK's
|
|
1153
|
+
* `stageFieldContent` (a Node-only transform; see staging.ts's module doc).
|
|
1154
|
+
*
|
|
1155
|
+
* Staging is one atomic `writeContent` when the content fits a single tx's gas, else
|
|
1156
|
+
* gas-bounded chunk-write `multicall`s plus a final manifest write — the SDK picks, and we
|
|
1157
|
+
* print the tx plan up front (via its `onEvent`) so the human knows the count before signing.
|
|
1158
|
+
* These store writes use the env key (the data contracts are ownerless); the owner only
|
|
1159
|
+
* signs the field set that references the manifest.
|
|
1160
|
+
*/
|
|
792
1161
|
async function putContentOnChain(bytes, compress, field, send, finalLabel = '1 owner field-set', store) {
|
|
793
|
-
const p = computeContentPlan(bytes, compress);
|
|
794
1162
|
warnIfLargeForOnChain(bytes.length, `'${field}'`);
|
|
795
|
-
const
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1163
|
+
const content = compress === 'gzip' ? new Uint8Array(gzipSync(bytes)) : new Uint8Array(bytes);
|
|
1164
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
1165
|
+
return stageFieldContent({
|
|
1166
|
+
content,
|
|
1167
|
+
compress,
|
|
1168
|
+
field,
|
|
1169
|
+
send,
|
|
1170
|
+
publicClient,
|
|
1171
|
+
chainId: chainId(),
|
|
1172
|
+
store,
|
|
1173
|
+
onEvent: (e) => {
|
|
1174
|
+
if (e.kind === 'chunk-store')
|
|
1175
|
+
printChunkStoreEvent(e.event);
|
|
1176
|
+
else if (e.kind === 'planned') {
|
|
1177
|
+
console.log(dim(` '${field}' on-chain: ${planSizeLine(bytes.length, e.contentPlan, compress)} via reader ${e.store}`));
|
|
1178
|
+
console.log(dim(` ${planTxLine(e.contentPlan, finalLabel)}`));
|
|
1179
|
+
}
|
|
1180
|
+
else {
|
|
1181
|
+
console.log(dim(` staged in ${e.txHashes.length} tx(s); manifest → ${e.manifest}`));
|
|
1182
|
+
}
|
|
1183
|
+
},
|
|
1184
|
+
});
|
|
801
1185
|
}
|
|
802
1186
|
/**
|
|
803
1187
|
* Dry-run preview of staging an image fully on-chain — the REAL chunk + transaction plan,
|
|
@@ -845,6 +1229,55 @@ export async function stageImageFieldsBatch(imagePaths, compress, send, storeOve
|
|
|
845
1229
|
}
|
|
846
1230
|
return { fields, store };
|
|
847
1231
|
}
|
|
1232
|
+
// ── the generator repoint guard ───────────────────────────────────────────────
|
|
1233
|
+
// The canonical AbxGenerator reads a token's param surface FROM CHAIN (`tokenParamKeys` /
|
|
1234
|
+
// `contractParamKeys`). A LEGACY implementation — deployed before enumeration shipped — has neither
|
|
1235
|
+
// getter, so the generator finds nothing: every configured param vanishes from tokenData and from
|
|
1236
|
+
// the live view, silently, behind a tokenURI that still looks perfectly healthy. That is the exact
|
|
1237
|
+
// failure class this toolkit refuses rather than warns about, so pointing a legacy token at the
|
|
1238
|
+
// current generator is REFUSED. (Repointing the metadata RENDERER is safe and unguarded: a v4
|
|
1239
|
+
// renderer on a legacy token just emits no params block.)
|
|
1240
|
+
/** The field-renderer address a `--value` names: the canonical `abi.encode(address)` (32 bytes),
|
|
1241
|
+
* or a bare 20-byte address. Null when it is neither. */
|
|
1242
|
+
function fieldRendererTarget(value) {
|
|
1243
|
+
const hex = value.trim();
|
|
1244
|
+
if (!/^0x[0-9a-fA-F]*$/.test(hex))
|
|
1245
|
+
return null;
|
|
1246
|
+
if (hex.length === 42)
|
|
1247
|
+
return getAddress(hex);
|
|
1248
|
+
if (hex.length !== 66)
|
|
1249
|
+
return null;
|
|
1250
|
+
try {
|
|
1251
|
+
return decodeFieldRenderer(hex);
|
|
1252
|
+
}
|
|
1253
|
+
catch {
|
|
1254
|
+
return null;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
export async function assertGeneratorRepointable(contract, field, flags,
|
|
1258
|
+
/** Injected for tests; the real probe is one eth_call. */
|
|
1259
|
+
probe = (c) => hasParamEnumeration(makePublicClient({ chainKey: CHAIN }), c)) {
|
|
1260
|
+
if (flags.representation !== R.renderer || !flags.value || flags.value === 'true')
|
|
1261
|
+
return;
|
|
1262
|
+
const target = fieldRendererTarget(flags.value);
|
|
1263
|
+
const generator = resolveGenerator(chainId());
|
|
1264
|
+
// Only the CANONICAL generator is guarded — any other field renderer is the creator's own contract
|
|
1265
|
+
// and none of our business.
|
|
1266
|
+
if (!target || !generator || target.toLowerCase() !== generator.toLowerCase())
|
|
1267
|
+
return;
|
|
1268
|
+
// The `owner` read has already succeeded by the time this runs, so the RPC is proven reachable:
|
|
1269
|
+
// a failing probe here means the getter is absent, not that the node is down.
|
|
1270
|
+
if (await probe(contract))
|
|
1271
|
+
return;
|
|
1272
|
+
throw new Error(`refusing to point ${field} at the canonical generator ${generator} — ${contract} does not expose the param\n` +
|
|
1273
|
+
` enumeration surface (tokenParamKeys/contractParamKeys), so it is a LEGACY implementation. The current\n` +
|
|
1274
|
+
` generator reads params FROM CHAIN, so on this token it would read NOTHING: every configured param would\n` +
|
|
1275
|
+
` silently disappear from tokenData, the live view, and every render — with a tokenURI that still looks fine.\n\n` +
|
|
1276
|
+
` Two honest options:\n` +
|
|
1277
|
+
` • stay on the generator this project already uses (pass that address as --value; it reads the project's\n` +
|
|
1278
|
+
` params.keys list, which is how it has always worked here), or\n` +
|
|
1279
|
+
` • redeploy the project with the current \`abx deploy-code\` — new projects enumerate on-chain and need no list.`);
|
|
1280
|
+
}
|
|
848
1281
|
// ── set-field ──────────────────────────────────────────────────────────────--
|
|
849
1282
|
// Set an on-chain metadata field. `--field` is what (e.g. image, description),
|
|
850
1283
|
// `--representation` is how it's carried (default `inline` for --text, `keccak256`
|
|
@@ -859,10 +1292,11 @@ export async function cmdSetField(address, flags) {
|
|
|
859
1292
|
const collection = !!flags.collection;
|
|
860
1293
|
const lane = laneFromFlags(flags);
|
|
861
1294
|
const owner = await read(contract, 'owner');
|
|
1295
|
+
await assertGeneratorRepointable(contract, field, flags); // legacy impl + the current generator = params silently invisible
|
|
862
1296
|
const staging = !!(flags.file && flags.file !== 'true'); // large content ON-CHAIN via chunk store/reader
|
|
863
1297
|
// --file + --dry-run: preview the on-chain staging plan and store/send NOTHING. (The locator/text
|
|
864
1298
|
// path flows through runWrite, which previews there; staging must short-circuit before any upload.)
|
|
865
|
-
if (staging && flags
|
|
1299
|
+
if (staging && isDryRun(flags)) {
|
|
866
1300
|
const bytes = readFileSync(resolvePath(flags.file));
|
|
867
1301
|
const p = computeContentPlan(bytes, parseCompress(flags.compress));
|
|
868
1302
|
console.log(`\n ${bold('◆ set-field ' + field)} ${dim('(dry run — nothing staged or sent)')}`);
|
|
@@ -938,9 +1372,25 @@ export async function cmdSetField(address, flags) {
|
|
|
938
1372
|
* - computed keys (`artifacts`, `abx_provenance`) are refused — they're the manifest, not inputs.
|
|
939
1373
|
* Scope: token (`--token`, default 0) or `--collection`. Any signing lane. Owner-only.
|
|
940
1374
|
*/
|
|
1375
|
+
/**
|
|
1376
|
+
* Attach one or more artifacts. Several `<key> <uri>` pairs in one invocation become **one
|
|
1377
|
+
* transaction**.
|
|
1378
|
+
*
|
|
1379
|
+
* That batching is a safety fix, not a convenience (backlog B20). The CLI's most-documented flow —
|
|
1380
|
+
* mint, then attach each artifact, then refresh — sent one transaction per step with no all-or-nothing
|
|
1381
|
+
* boundary, so a failure partway through left a permanently half-written token that cannot be
|
|
1382
|
+
* un-minted. An integrator hit exactly this and folded 8 operations into 1 transaction using the SDK's
|
|
1383
|
+
* `batchOps`, which the CLI already shipped and did not use. Now it does: N pairs are one
|
|
1384
|
+
* `multicall`, so either every artifact lands or none does.
|
|
1385
|
+
*
|
|
1386
|
+
* A single pair passes through `batchOps` untouched, so the one-artifact case sends the identical
|
|
1387
|
+
* transaction it always did.
|
|
1388
|
+
*/
|
|
941
1389
|
export async function cmdAttach(rest, flags) {
|
|
942
|
-
const usage = 'abx attach <address> <key> <ipfs://… | ar://… | https://…> [--file <path>] [--collection | --token 0] [--sign|--unsigned] [--dry-run]';
|
|
943
|
-
const [address,
|
|
1390
|
+
const usage = 'abx attach <address> <key> <ipfs://… | ar://… | https://…> [<key> <uri> …] [--file <path>] [--collection | --token 0] [--sign|--unsigned] [--dry-run]';
|
|
1391
|
+
const [address, ...pairArgs] = positionalArgs(rest);
|
|
1392
|
+
const key = pairArgs[0];
|
|
1393
|
+
const uri = pairArgs[1];
|
|
944
1394
|
// Warn (never throw) on an unrecognized flag — a typo or a hopeful `--mime-type` otherwise no-ops
|
|
945
1395
|
// INVISIBLY (round-1: an agent passed `--mime-type` and it was silently swallowed). mimeType is
|
|
946
1396
|
// declared from the URL extension, not a flag; say so.
|
|
@@ -955,13 +1405,15 @@ export async function cmdAttach(rest, flags) {
|
|
|
955
1405
|
const contract = requireAddress(address, usage);
|
|
956
1406
|
if (!key) {
|
|
957
1407
|
console.error(`usage: ${usage}\n the <key> is the name your file appears under in the manifest (e.g. print, certificate, stems, readme).\n`);
|
|
958
|
-
process.
|
|
1408
|
+
process.exitCode = 1;
|
|
1409
|
+
return;
|
|
959
1410
|
}
|
|
960
1411
|
assertSettableField(key);
|
|
961
1412
|
const hasFile = !!(flags.file && flags.file !== 'true');
|
|
962
1413
|
if (!uri && !hasFile) {
|
|
963
1414
|
console.error(`usage: ${usage}\n pass a locator URI (ipfs://… / ar://… / https://…) or --file <path> to store bytes on-chain.\n`);
|
|
964
|
-
process.
|
|
1415
|
+
process.exitCode = 1;
|
|
1416
|
+
return;
|
|
965
1417
|
}
|
|
966
1418
|
if (uri && hasFile)
|
|
967
1419
|
throw new Error('pass EITHER a locator URI OR --file <path>, not both.');
|
|
@@ -975,40 +1427,133 @@ export async function cmdAttach(rest, flags) {
|
|
|
975
1427
|
// Locator path (the common case): auto-detect the representation, refuse an unrecognized scheme
|
|
976
1428
|
// loudly (never silently store a bad value) — fail fast before any RPC. Derive the declared
|
|
977
1429
|
// mimeType from the extension.
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
1430
|
+
// Every `<key> <uri>` pair, validated BEFORE anything is sent — a batch that would revert partway
|
|
1431
|
+
// is exactly what this command now exists to prevent, so a bad locator in pair 5 must stop pair 1.
|
|
1432
|
+
if (pairArgs.length % 2 !== 0) {
|
|
1433
|
+
throw new Error(`attach takes <key> <uri> PAIRS; got ${pairArgs.length} positional argument(s) after the address. ` +
|
|
1434
|
+
`Last one seen: "${pairArgs[pairArgs.length - 1]}".`);
|
|
1435
|
+
}
|
|
1436
|
+
const pairs = [];
|
|
1437
|
+
for (let i = 0; i < pairArgs.length; i += 2) {
|
|
1438
|
+
const k = pairArgs[i];
|
|
1439
|
+
const u = pairArgs[i + 1];
|
|
1440
|
+
assertSettableField(k);
|
|
1441
|
+
const rep = representationForLocator(u);
|
|
1442
|
+
if (!rep) {
|
|
1443
|
+
throw new Error(`"${u}" isn't a recognized file locator. Use ipfs://… (pinned/IPFS), ar://… (Arweave), or https://… . ` +
|
|
1444
|
+
'To store literal text or raw bytes on-chain instead, use `abx set-field`.');
|
|
1445
|
+
}
|
|
1446
|
+
pairs.push({ key: k, uri: u, representation: rep, mimeType: contentTypeFromPath(u) });
|
|
1447
|
+
}
|
|
1448
|
+
// A key repeated within one batch would have the later write silently win — the same
|
|
1449
|
+
// full-column-upsert hazard that bit `register` and `lock-field`. Refuse instead.
|
|
1450
|
+
const dupes = pairs.map((p) => p.key).filter((k, i, a) => a.indexOf(k) !== i);
|
|
1451
|
+
if (dupes.length) {
|
|
1452
|
+
throw new Error(`the same key appears twice in one batch: ${[...new Set(dupes)].join(', ')}. ` +
|
|
1453
|
+
'Each field holds ONE active value, so the last write would silently win — attach them separately if that is really what you want.');
|
|
982
1454
|
}
|
|
1455
|
+
const representation = pairs[0].representation;
|
|
983
1456
|
const owner = await read(contract, 'owner');
|
|
984
|
-
const
|
|
985
|
-
|
|
1457
|
+
for (const p of pairs) {
|
|
1458
|
+
if (p.mimeType === 'application/octet-stream') {
|
|
1459
|
+
console.log(yellow(' ⚠ ') +
|
|
1460
|
+
dim(`no file extension in "${p.uri.slice(0, 64)}" → declared type will be application/octet-stream. `) +
|
|
1461
|
+
dim('Point the URI at the file itself (…/master.tiff, …/coa.pdf) so collectors get the right type.'));
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
const mimeType = pairs[0].mimeType;
|
|
1465
|
+
for (const p of pairs) {
|
|
1466
|
+
console.log(` attaching ${bold(p.key)} ${dim(`(${p.mimeType}, ${p.representation})`)} to ${scope}: ${dim(p.uri)}`);
|
|
1467
|
+
}
|
|
1468
|
+
// Where it surfaces. This used to be one dim line, and it read as a footnote rather than as a
|
|
1469
|
+
// dependency: an integrator attached five audio stems to a fully-on-chain token, paid to store
|
|
1470
|
+
// them, and found `tokenURI` listed none of them — "paid for, stored on-chain, and invisible".
|
|
1471
|
+
// The on-chain renderer deliberately omits locator-represented artifacts (they duplicate no
|
|
1472
|
+
// on-chain type information — see specs/protocol/data-plane.md), so the artifacts manifest comes
|
|
1473
|
+
// from a RESOLVER. When the project has no resolver baked in, that is not a footnote, it is the
|
|
1474
|
+
// difference between a feature working and not existing, so say it as a warning.
|
|
1475
|
+
const uriBase = await read(contract, 'tokenURIBase').catch(() => '');
|
|
1476
|
+
const artifactsPath = `/t/${chainId()}/${contract}/${flags.token ?? '0'}`;
|
|
1477
|
+
if (uriBase && uriBase.trim() !== '') {
|
|
1478
|
+
console.log(dim(` → listed in this project's resolver artifacts (${artifactsPath} and /data/<key>); a bare on-chain tokenURI carries reserved fields plus abx_params only.`));
|
|
1479
|
+
}
|
|
1480
|
+
else {
|
|
986
1481
|
console.log(yellow(' ⚠ ') +
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
//
|
|
993
|
-
|
|
994
|
-
const
|
|
995
|
-
? prepareSetContractField({ contract, field: key, representation, value: toHex(uri), chainId: chainId() })
|
|
996
|
-
: prepareSetTokenField({ contract, tokenId: BigInt(flags.token ?? '0'), field: key, representation, value: toHex(uri), chainId: chainId() });
|
|
997
|
-
const
|
|
1482
|
+
`this project resolves ON-CHAIN (no resolver base baked in), and the on-chain document carries reserved fields plus the computed ${bold('abx_params')} block only — ` +
|
|
1483
|
+
`so ${pairs.map((p) => bold(p.key)).join(', ')} will NOT appear in ${bold('tokenURI')}. The bytes are stored and provable, but nothing surfaces them to a marketplace or wallet. ` +
|
|
1484
|
+
dim('(Configured params DO appear on-chain — attachments are the surface that needs a resolver.)'));
|
|
1485
|
+
console.log(dim(` to make attached artifacts visible, point the project at a resolver (${bold('abx deploy-resolver')}, or a managed one via ${bold('abx add <addr> --remote <name>')}) — it serves the listing at ${artifactsPath}.`));
|
|
1486
|
+
}
|
|
1487
|
+
// ONE transaction for the whole set. `batchOps` folds a same-target run into a `multicall` and
|
|
1488
|
+
// passes a lone op through untouched, so a single attach is byte-identical to before.
|
|
1489
|
+
const ops = pairs.map((p) => collection
|
|
1490
|
+
? prepareSetContractField({ contract, field: p.key, representation: p.representation, value: toHex(p.uri), chainId: chainId() })
|
|
1491
|
+
: prepareSetTokenField({ contract, tokenId: BigInt(flags.token ?? '0'), field: p.key, representation: p.representation, value: toHex(p.uri), chainId: chainId() }));
|
|
1492
|
+
const batched = batchOps(ops);
|
|
1493
|
+
if (batched.length !== 1) {
|
|
1494
|
+
// Defensive: every op here targets the same contract and carries no value, so batchOps must
|
|
1495
|
+
// return exactly one tx. If that ever changes, fail loudly rather than send a partial set.
|
|
1496
|
+
throw new Error(`attach expected to batch ${ops.length} op(s) into one transaction, got ${batched.length}`);
|
|
1497
|
+
}
|
|
1498
|
+
if (pairs.length > 1) {
|
|
1499
|
+
console.log(dim(` ${pairs.length} artifacts → ONE transaction (all-or-nothing: a revert lands none of them, so no half-written token).`));
|
|
1500
|
+
}
|
|
1501
|
+
const sent = await runWrite(contract, batched[0], flags, owner);
|
|
998
1502
|
if (sent) {
|
|
999
1503
|
const id = flags.token ?? '0';
|
|
1000
|
-
|
|
1504
|
+
const names = pairs.map((p) => bold(p.key)).join(', ');
|
|
1505
|
+
console.log(` ${green('✓')} attached — ${names} join${pairs.length > 1 ? '' : 's'} ${scope}'s ${bold('artifacts')} manifest (stored on-chain, anchored).\n` +
|
|
1001
1506
|
dim(` verify (a resolver serves the complete listing): `) +
|
|
1002
|
-
`
|
|
1003
|
-
dim(` ${collection ? '' : `→ artifacts[].key "${key}"; /data
|
|
1004
|
-
dim(` (The complete file listing is a resolver surface — the bare on-chain tokenURI enumerates reserved fields
|
|
1507
|
+
`abx tokenuri ${contract}${id === '0' ? '' : ` --token ${id}`} --fetch` +
|
|
1508
|
+
dim(` ${collection ? '' : `→ artifacts[].key ${pairs.map((p) => `"${p.key}"`).join(', ')}; /data/<key> fetches each`}\n`) +
|
|
1509
|
+
dim(` (The complete file listing is a resolver surface — the bare on-chain tokenURI enumerates reserved fields plus abx_params. Params never need a resolver; attachments do.)\n`));
|
|
1005
1510
|
}
|
|
1006
1511
|
}
|
|
1007
1512
|
// ── lock-field ───────────────────────────────────────────────────────────────
|
|
1513
|
+
/**
|
|
1514
|
+
* Refuse `lock-field` on a name that is a declared PARAM key.
|
|
1515
|
+
*
|
|
1516
|
+
* Fields and params are two separate namespaces that may share a name, and `lock-field` only ever
|
|
1517
|
+
* locks the *field*. A tester welded `grid` — a `Bytes` param holding the artwork — with
|
|
1518
|
+
* `lock-field --field grid`, got "permanent", got `tokenFieldLocked(0,"grid") == true`, and then
|
|
1519
|
+
* overwrote the artwork with `configure-param` on the next call. Every individual statement the CLI
|
|
1520
|
+
* made was true; together they promised a protection that did not exist. Permanence is the pitch, so
|
|
1521
|
+
* this refuses rather than warns, and names the mechanism that actually welds a param.
|
|
1522
|
+
*/
|
|
1523
|
+
async function refuseIfParamKey(contract, field) {
|
|
1524
|
+
let exists = false;
|
|
1525
|
+
try {
|
|
1526
|
+
const schema = (await makePublicClient({ chainKey: CHAIN }).readContract({
|
|
1527
|
+
address: contract,
|
|
1528
|
+
abi: seriesCodeAbi,
|
|
1529
|
+
functionName: 'paramSchema',
|
|
1530
|
+
args: [encodeTagSdk(field)],
|
|
1531
|
+
}));
|
|
1532
|
+
exists = !!schema[0];
|
|
1533
|
+
}
|
|
1534
|
+
catch {
|
|
1535
|
+
// No param surface at all (a 1/1 or plain Series) — nothing to confuse the name with.
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
if (!exists)
|
|
1539
|
+
return;
|
|
1540
|
+
throw new Error(`"${field}" is a declared PostParam key on ${contract}, and lock-field does NOT lock params — ` +
|
|
1541
|
+
`it locks the metadata FIELD of the same name. They are separate namespaces, so this would have ` +
|
|
1542
|
+
`reported "permanent" while configure-param stayed free to overwrite the value.\n` +
|
|
1543
|
+
` To weld the param, lock its schema instead:\n` +
|
|
1544
|
+
` abx set-schema ${contract} --schema ${field}:<Type>:<Auth>:lock=now\n` +
|
|
1545
|
+
` (after that every configure-param on "${field}" reverts ParamLockExpired — check with ` +
|
|
1546
|
+
`\`abx inspect ${contract}\`.)\n` +
|
|
1547
|
+
` If you really did mean the metadata field "${field}" and not the param, re-run with --force-field.`);
|
|
1548
|
+
}
|
|
1008
1549
|
export async function cmdLockField(address, flags) {
|
|
1009
1550
|
const contract = requireAddress(address, 'abx lock-field <address> --field <name> [--collection | --token 0] [--sign|--unsigned]');
|
|
1010
1551
|
const field = requireFlag(flags, 'field', 'abx lock-field <address> --field <name>');
|
|
1011
1552
|
const collection = !!flags.collection;
|
|
1553
|
+
// The metadata field and a same-named param are different things; only an explicit --force-field
|
|
1554
|
+
// says "yes, I mean the field". See refuseIfParamKey.
|
|
1555
|
+
if (flags['force-field'] === undefined)
|
|
1556
|
+
await refuseIfParamKey(contract, field);
|
|
1012
1557
|
const owner = await read(contract, 'owner');
|
|
1013
1558
|
console.log(dim(` note: locking the '${field}' field is permanent and irreversible (freezes all its representations).`));
|
|
1014
1559
|
const tx = collection
|
|
@@ -1069,15 +1614,16 @@ async function readSeries(token, fn, args = []) {
|
|
|
1069
1614
|
args: args,
|
|
1070
1615
|
}));
|
|
1071
1616
|
}
|
|
1072
|
-
|
|
1617
|
+
/** The edition twin of {@link readSeries} — reads a per-id getter (`totalSupply(id)`,
|
|
1618
|
+
* `maxSupply(id)`, `uri(id)`, …) via the narrowest-common-superset edition ABI. */
|
|
1619
|
+
async function readEdition(token, fn, args = []) {
|
|
1073
1620
|
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
1074
|
-
|
|
1075
|
-
address:
|
|
1076
|
-
abi:
|
|
1077
|
-
functionName:
|
|
1078
|
-
args:
|
|
1621
|
+
return (await publicClient.readContract({
|
|
1622
|
+
address: token,
|
|
1623
|
+
abi: oneOfOneEditionAbi,
|
|
1624
|
+
functionName: fn,
|
|
1625
|
+
args: args,
|
|
1079
1626
|
}));
|
|
1080
|
-
return { configured, paymentToken, price, allocation, sold };
|
|
1081
1627
|
}
|
|
1082
1628
|
/** Resolve the shared minter for the chain (flag → env → manifest), or deploy it if none exists.
|
|
1083
1629
|
* It's ownerless, so any funded signer can stand it up — the sibling of `ensureChunkStore`. */
|
|
@@ -1101,38 +1647,51 @@ async function ensureFixedPriceMinter(override) {
|
|
|
1101
1647
|
}
|
|
1102
1648
|
}
|
|
1103
1649
|
const { wallet, account } = makeWalletClient({ chainKey: CHAIN });
|
|
1650
|
+
const send = makeHotSender({ wallet, account, publicClient });
|
|
1104
1651
|
console.log(dim(' deploying the canonical fixed-price minter (shared, ownerless) — CREATE2…'));
|
|
1105
|
-
const { minter, txHash } = await deployFixedPriceMinter(
|
|
1652
|
+
const { minter, txHash } = await deployFixedPriceMinter(send, publicClient);
|
|
1106
1653
|
console.log(` ${green('✓')} fixed-price minter ${minter}`);
|
|
1107
1654
|
console.log(dim(` tx ${txHash}`));
|
|
1108
1655
|
console.log(dim(` not in the shipped manifest for ${CHAIN} — to reuse it set ${bold(`ABX_FIXED_PRICE_MINTER=${minter}`)} (or add it to packages/sdk/src/deployments.ts)`));
|
|
1109
1656
|
return minter;
|
|
1110
1657
|
}
|
|
1658
|
+
/** The edition twin of {@link ensureFixedPriceMinter} — resolves (or deploys) the chain's shared
|
|
1659
|
+
* `AbxFixedPriceMinter1155`, the Minter spine's per-`(token, id)` sale singleton. */
|
|
1660
|
+
async function ensureFixedPriceMinter1155(override) {
|
|
1661
|
+
const known = fixedPriceMinter1155Address(override);
|
|
1662
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
1663
|
+
if (known) {
|
|
1664
|
+
const code = await publicClient.getCode({ address: known });
|
|
1665
|
+
if (code && code !== '0x')
|
|
1666
|
+
return known;
|
|
1667
|
+
console.log(yellow(` configured edition minter ${known} has no code on ${CHAIN} — deploying a fresh one`));
|
|
1668
|
+
}
|
|
1669
|
+
const predicted = predictFixedPriceMinter1155();
|
|
1670
|
+
if (!known || known.toLowerCase() !== predicted.toLowerCase()) {
|
|
1671
|
+
const pcode = await publicClient.getCode({ address: predicted });
|
|
1672
|
+
if (pcode && pcode !== '0x') {
|
|
1673
|
+
console.log(dim(` using the canonical fixed-price edition minter at its deterministic address ${predicted}`));
|
|
1674
|
+
return predicted;
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
const { wallet, account } = makeWalletClient({ chainKey: CHAIN });
|
|
1678
|
+
const send = makeHotSender({ wallet, account, publicClient });
|
|
1679
|
+
console.log(dim(' deploying the canonical fixed-price edition minter (shared, ownerless) — CREATE2…'));
|
|
1680
|
+
const { minter, txHash } = await deployFixedPriceMinter1155(send, publicClient);
|
|
1681
|
+
console.log(` ${green('✓')} fixed-price edition minter ${minter}`);
|
|
1682
|
+
console.log(dim(` tx ${txHash}`));
|
|
1683
|
+
console.log(dim(` not in the shipped manifest for ${CHAIN} — to reuse it set ${bold(`ABX_FIXED_PRICE_MINTER_1155=${minter}`)} (or add it to packages/sdk/src/deployments.ts)`));
|
|
1684
|
+
return minter;
|
|
1685
|
+
}
|
|
1111
1686
|
/** A minter write (configure/buy). No re-index — the sale lives on the minter, not the token
|
|
1112
|
-
* projection; the token's own state is unchanged by a sale config.
|
|
1687
|
+
* projection; the token's own state is unchanged by a sale config.
|
|
1688
|
+
*
|
|
1689
|
+
* Used to hand-roll its own dry-run guard — "the minter path does not go through runWrite, so it
|
|
1690
|
+
* needs its OWN" — which is exactly the duplication {@link gatedSend} exists to end: this now shares
|
|
1691
|
+
* the identical choke point `runWrite` does, so `minter configure`/`minter buy` also pick up
|
|
1692
|
+
* `--confirm` (previously only the deploy family had it) with no extra code here. */
|
|
1113
1693
|
async function runMinterWrite(provider, flags, expectedSigner) {
|
|
1114
|
-
|
|
1115
|
-
// through runWrite, so it needs its OWN dry-run guard — without it, `minter configure --dry-run`
|
|
1116
|
-
// silently signs + broadcasts a real sale (a critical footgun: a mainnet creator "previewing"
|
|
1117
|
-
// their sale would send it). Mirrors runWrite's guard.
|
|
1118
|
-
if (flags['dry-run']) {
|
|
1119
|
-
const prepared = typeof provider === 'function' ? await provider(expectedSigner ?? zeroAddress) : provider;
|
|
1120
|
-
console.log(`\n ${bold('◆ ' + prepared.summary)} ${dim('(dry run — nothing sent)')}`);
|
|
1121
|
-
for (const [k, v] of Object.entries(prepared.fields))
|
|
1122
|
-
console.log(` ${dim(k.padEnd(12))} ${v}`);
|
|
1123
|
-
console.log(` ${dim('to'.padEnd(12))} ${prepared.to ?? dim('(contract deploy)')}`);
|
|
1124
|
-
console.log(dim(`\n Re-run without --dry-run to send (lane: ${laneFromFlags(flags)}).\n`));
|
|
1125
|
-
return;
|
|
1126
|
-
}
|
|
1127
|
-
await assertChainId(CHAIN);
|
|
1128
|
-
await signTx(provider, {
|
|
1129
|
-
lane: laneFromFlags(flags),
|
|
1130
|
-
chainKey: CHAIN,
|
|
1131
|
-
expectedSigner,
|
|
1132
|
-
yes: !!flags.yes,
|
|
1133
|
-
port: flags.port ? Number(flags.port) : undefined,
|
|
1134
|
-
signUrlFile: flags['sign-url-file'],
|
|
1135
|
-
});
|
|
1694
|
+
await gatedSend(provider, flags, { chainKey: CHAIN, expectedSigner });
|
|
1136
1695
|
}
|
|
1137
1696
|
/** Parse the sale price: `--price-raw <units>` (exact base units) or the friendly `--price <ether>`
|
|
1138
1697
|
* (18-decimals). ETH sales use `--price`; non-18-dp ERC-20s should use `--price-raw`. */
|
|
@@ -1142,30 +1701,84 @@ function parseSalePrice(flags, usage) {
|
|
|
1142
1701
|
if (flags.price && flags.price !== 'true')
|
|
1143
1702
|
return parseEther(flags.price);
|
|
1144
1703
|
console.error(`missing --price <ether> or --price-raw <units>\nusage: ${usage}\n`);
|
|
1145
|
-
|
|
1704
|
+
throw new CliError('', 1, true); // already printed above — see CliError's alreadyPrinted doc
|
|
1146
1705
|
}
|
|
1147
1706
|
/**
|
|
1148
1707
|
* `abx minter configure <token> --price <eth> --allocation <n> [--erc20 0x…]` — set the fixed-price
|
|
1149
1708
|
* sale for a project on the shared minter. Defers to the token owner. Resolves (or deploys) the
|
|
1150
1709
|
* shared minter, then reports the two remaining grants the owner still needs (assign the minter on
|
|
1151
1710
|
* the token, set a primary payee) and whether the token is paused.
|
|
1711
|
+
*
|
|
1712
|
+
* On an EDITION (OneOfOneEdition/EditionImage/EditionCode), `--token-id` is REQUIRED (sales are
|
|
1713
|
+
* keyed `(token, id)` — a per-artwork price, not one project-wide sale) and the sale routes to the
|
|
1714
|
+
* shared `AbxFixedPriceMinter1155` instead. Refused on a 721 target.
|
|
1152
1715
|
*/
|
|
1153
1716
|
export async function cmdMinterConfigure(address, flags) {
|
|
1154
|
-
const usage = 'abx minter configure <token> (--price <eth> | --price-raw <units>) --allocation <n> [--erc20 0x…] [--minter-contract 0x…] [--sign|--unsigned]';
|
|
1717
|
+
const usage = 'abx minter configure <token> (--price <eth> | --price-raw <units>) --allocation <n> [--erc20 0x…] [--token-id <n> (editions)] [--minter-contract 0x…] [--sign|--unsigned]';
|
|
1155
1718
|
const token = requireAddress(address, usage);
|
|
1719
|
+
warnStrayFlags(flags, new Set(MINTER_CONFIGURE_FLAGS), 'minter configure');
|
|
1720
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
1721
|
+
const kind = await detectTokenKind(publicClient, token);
|
|
1156
1722
|
const owner = await read(token, 'owner');
|
|
1157
1723
|
const erc20 = flags.erc20 && flags.erc20 !== 'true' ? flags.erc20 : zeroAddress;
|
|
1158
1724
|
const allocation = BigInt(requireFlag(flags, 'allocation', usage));
|
|
1159
1725
|
const price = parseSalePrice(flags, usage);
|
|
1160
|
-
|
|
1161
|
-
//
|
|
1162
|
-
|
|
1726
|
+
const isEth = erc20 === zeroAddress;
|
|
1727
|
+
// On --dry-run resolve the minter WITHOUT deploying — ensure* would deploy the shared singleton
|
|
1728
|
+
// if absent, and a preview must never send. Fall back to a label if none exists.
|
|
1729
|
+
const dryRun = isDryRun(flags);
|
|
1730
|
+
if (kind.isEdition) {
|
|
1731
|
+
const tokenId = parseEditionCountFlag(requireFlag(flags, 'token-id', usage), 'token-id');
|
|
1732
|
+
const knownMinter = fixedPriceMinter1155Address(flags['minter-contract']);
|
|
1733
|
+
if (dryRun && !knownMinter) {
|
|
1734
|
+
console.log(yellow(` ⚠ no shared edition minter deployed on ${CHAIN} yet — a real run deploys it once (a separate tx) before configuring.`));
|
|
1735
|
+
}
|
|
1736
|
+
const minter = dryRun ? (knownMinter ?? zeroAddress) : await ensureFixedPriceMinter1155(flags['minter-contract']);
|
|
1737
|
+
// Sanity-check the allocation against what THIS id can still mint. `maxSupply(id) === 0` reads
|
|
1738
|
+
// as "open" (the un-overridden --copies default, or an id nobody has ever capped) — the same
|
|
1739
|
+
// convention `tokens.ts`'s TokenRow.maxSupply documents; see set-max-supply's own note on why a
|
|
1740
|
+
// bare 0 can't be told apart from "explicitly closed" without more than this one read.
|
|
1741
|
+
const [maxSupply, supplyNow] = await Promise.all([
|
|
1742
|
+
readEdition(token, 'maxSupply', [tokenId]).catch(() => 0n),
|
|
1743
|
+
readEdition(token, 'totalSupply', [tokenId]).catch(() => 0n),
|
|
1744
|
+
]);
|
|
1745
|
+
const remaining = maxSupply > 0n ? (maxSupply > supplyNow ? maxSupply - supplyNow : 0n) : null;
|
|
1746
|
+
if (remaining !== null && allocation > remaining) {
|
|
1747
|
+
console.log(yellow(` ⚠ allocation ${allocation} exceeds the ${remaining} #${tokenId} can still mint `) +
|
|
1748
|
+
dim(`(cap ${maxSupply} − ${supplyNow} minted). Only ${remaining} will actually sell.`));
|
|
1749
|
+
console.log(dim(` To sell ${allocation}, raise this id's cap is not possible (caps only decrease) — set --allocation ${remaining} (or less, to hold reserves).`));
|
|
1750
|
+
}
|
|
1751
|
+
console.log(dim(` configuring sale on ${minter}`));
|
|
1752
|
+
console.log(dim(` token ${token} · id #${tokenId}`));
|
|
1753
|
+
console.log(dim(` price ${isEth ? `${formatEther(price)} ETH` : `${price} units of ${erc20}`} / copy`));
|
|
1754
|
+
console.log(dim(` allocation ${allocation}`));
|
|
1755
|
+
await runMinterWrite(prepareConfigureSale1155({ minter, token, tokenId, paymentToken: erc20, price, allocation, chainId: chainId() }), flags, owner);
|
|
1756
|
+
const [assignedMinter, payee, paused] = await Promise.all([
|
|
1757
|
+
read(token, 'minter').catch(() => zeroAddress),
|
|
1758
|
+
read(token, 'primaryPayee').catch(() => zeroAddress),
|
|
1759
|
+
read(token, 'paused').catch(() => false),
|
|
1760
|
+
]);
|
|
1761
|
+
const assigned = assignedMinter.toLowerCase() === minter.toLowerCase();
|
|
1762
|
+
console.log('');
|
|
1763
|
+
console.log(assigned ? dim(' ✓ minter is assigned on the token') : yellow(` ⚠ assign this minter on the token: abx set-minter ${token} --minter ${minter}`));
|
|
1764
|
+
if (payee === zeroAddress)
|
|
1765
|
+
console.log(yellow(` ⚠ set a primary payee (sales revert without one): abx set-primary-payee ${token} --payee 0x…`));
|
|
1766
|
+
else
|
|
1767
|
+
console.log(dim(` ✓ proceeds → ${payee}`));
|
|
1768
|
+
if (paused)
|
|
1769
|
+
console.log(yellow(` • token is paused — open the sale when ready: abx unpause ${token}`));
|
|
1770
|
+
console.log(dim(` buyers then run: abx minter buy ${token} --token-id ${tokenId} --quantity <n>`));
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
// 721 path (unchanged): --token-id has no meaning — a 721 sale is one project-wide price.
|
|
1774
|
+
if (flags['token-id'] !== undefined) {
|
|
1775
|
+
throw new Error(`--token-id is edition-only (per-(token,id) sales) — ${token} is a ${kind.label} (721), sold as a single project-wide sale. Drop --token-id.`);
|
|
1776
|
+
}
|
|
1163
1777
|
const knownMinter = fixedPriceMinterAddress(flags['minter-contract']);
|
|
1164
1778
|
if (dryRun && !knownMinter) {
|
|
1165
1779
|
console.log(yellow(` ⚠ no shared minter deployed on ${CHAIN} yet — a real run deploys it once (a separate tx) before configuring.`));
|
|
1166
1780
|
}
|
|
1167
1781
|
const minter = dryRun ? (knownMinter ?? zeroAddress) : await ensureFixedPriceMinter(flags['minter-contract']);
|
|
1168
|
-
const isEth = erc20 === zeroAddress;
|
|
1169
1782
|
// Sanity-check the allocation against what the contract can actually mint. A creator who sets
|
|
1170
1783
|
// --allocation 100 on a 16-supply Series would only ever sell the remainder (maxInvocations binds
|
|
1171
1784
|
// tighter than the minter's allocation) and discover it when mint #16 reverts. Warn loudly — but
|
|
@@ -1203,19 +1816,68 @@ export async function cmdMinterConfigure(address, flags) {
|
|
|
1203
1816
|
console.log(dim(` buyers then run: abx minter buy ${token}`));
|
|
1204
1817
|
}
|
|
1205
1818
|
/** `abx minter show <token>` — the sale terms + the token's readiness (assigned? payee? paused?).
|
|
1206
|
-
* Read-only; the agent runs it to see exactly what's configured before/after a sale.
|
|
1819
|
+
* Read-only; the agent runs it to see exactly what's configured before/after a sale. On an
|
|
1820
|
+
* edition, `--token-id` is required and the readout is per-id (copies, not a whole-contract cap). */
|
|
1207
1821
|
export async function cmdMinterShow(address, flags) {
|
|
1208
|
-
const
|
|
1822
|
+
const usage = 'abx minter show <token> [--token-id <n> (editions)] [--minter-contract 0x…]';
|
|
1823
|
+
const token = requireAddress(address, usage);
|
|
1824
|
+
warnStrayFlags(flags, new Set(MINTER_SHOW_FLAGS), 'minter show');
|
|
1209
1825
|
// Refuse a nonexistent contract like the sibling owner-ops (state/unpause/minter configure) do —
|
|
1210
1826
|
// otherwise the minter singleton returns zero-config for the unconfigured token and we print a
|
|
1211
1827
|
// plausible-but-fake `paused: no (open)` readout for an address that has no project at all.
|
|
1212
1828
|
await assertContractExists(token);
|
|
1829
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
1830
|
+
const kind = await detectTokenKind(publicClient, token);
|
|
1831
|
+
if (kind.isEdition) {
|
|
1832
|
+
const tokenId = parseEditionCountFlag(requireFlag(flags, 'token-id', usage), 'token-id');
|
|
1833
|
+
const minter = fixedPriceMinter1155Address(flags['minter-contract']);
|
|
1834
|
+
if (!minter) {
|
|
1835
|
+
console.log(yellow(` no shared edition minter known for ${CHAIN} — configure a sale (deploys it) or set ABX_FIXED_PRICE_MINTER_1155`));
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
const sale = await readSaleConfig1155(publicClient, minter, token, tokenId);
|
|
1839
|
+
// Every read here goes through the EDITION ABI: the generic `read()` is the 721 1/1 ABI,
|
|
1840
|
+
// which has no minter()/primaryPayee() at all — a swallowed client-side throw there printed
|
|
1841
|
+
// a false "not assigned / no payee" for every correctly-configured edition (caught live by
|
|
1842
|
+
// the Sepolia fixture sweep, 2026-08-05).
|
|
1843
|
+
const [assignedMinter, payee, paused, maxSupply, supply] = await Promise.all([
|
|
1844
|
+
readEdition(token, 'minter').catch(() => zeroAddress),
|
|
1845
|
+
readEdition(token, 'primaryPayee').catch(() => zeroAddress),
|
|
1846
|
+
readEdition(token, 'paused').catch(() => false),
|
|
1847
|
+
readEdition(token, 'maxSupply', [tokenId]).catch(() => 0n),
|
|
1848
|
+
readEdition(token, 'totalSupply', [tokenId]).catch(() => 0n),
|
|
1849
|
+
]);
|
|
1850
|
+
const isEth = sale.paymentToken === zeroAddress;
|
|
1851
|
+
const assigned = assignedMinter.toLowerCase() === minter.toLowerCase();
|
|
1852
|
+
console.log(bold(`\n minter sale — ${token} #${tokenId}`));
|
|
1853
|
+
console.log(` shared minter: ${minter}`);
|
|
1854
|
+
if (!sale.configured) {
|
|
1855
|
+
console.log(yellow(` not configured — abx minter configure ${token} --token-id ${tokenId} --price <eth> --allocation <n>`));
|
|
1856
|
+
}
|
|
1857
|
+
else {
|
|
1858
|
+
console.log(` price: ${isEth ? `${formatEther(sale.price)} ETH` : `${sale.price} units of ${sale.paymentToken}`}`);
|
|
1859
|
+
console.log(` allocation: ${sale.sold}/${sale.allocation} sold`);
|
|
1860
|
+
}
|
|
1861
|
+
console.log(` assigned on token: ${assigned ? green('yes') : yellow(`no — abx set-minter ${token} --minter ${minter}`)}`);
|
|
1862
|
+
console.log(` primary payee: ${payee === zeroAddress ? yellow('none — abx set-primary-payee …') : payee}`);
|
|
1863
|
+
console.log(` paused: ${paused ? yellow(`yes — abx unpause ${token}`) : green('no (open)')}`);
|
|
1864
|
+
console.log(` copies: ${supply}${maxSupply > 0n ? `/${maxSupply}` : dim(' (open — no cap)')}`);
|
|
1865
|
+
const remaining = maxSupply > 0n ? (maxSupply > supply ? maxSupply - supply : 0n) : null;
|
|
1866
|
+
if (sale.configured && remaining !== null && sale.allocation > remaining) {
|
|
1867
|
+
console.log(yellow(` ⚠ allocation ${sale.allocation} exceeds the ${remaining} still mintable for #${tokenId} (cap ${maxSupply} − ${supply} minted) — only ${remaining} can actually sell.`));
|
|
1868
|
+
}
|
|
1869
|
+
console.log('');
|
|
1870
|
+
return;
|
|
1871
|
+
}
|
|
1872
|
+
if (flags['token-id'] !== undefined) {
|
|
1873
|
+
throw new Error(`--token-id is edition-only — ${token} is a ${kind.label} (721). Drop --token-id.`);
|
|
1874
|
+
}
|
|
1213
1875
|
const minter = fixedPriceMinterAddress(flags['minter-contract']);
|
|
1214
1876
|
if (!minter) {
|
|
1215
1877
|
console.log(yellow(` no shared minter known for ${CHAIN} — configure a sale (deploys it) or set ABX_FIXED_PRICE_MINTER`));
|
|
1216
1878
|
return;
|
|
1217
1879
|
}
|
|
1218
|
-
const sale = await
|
|
1880
|
+
const sale = await readSaleConfig(publicClient, minter, token);
|
|
1219
1881
|
const [assignedMinter, payee, paused, max, supply] = await Promise.all([
|
|
1220
1882
|
readSeries(token, 'minter').catch(() => zeroAddress),
|
|
1221
1883
|
readSeries(token, 'primaryPayee').catch(() => zeroAddress),
|
|
@@ -1247,14 +1909,47 @@ export async function cmdMinterShow(address, flags) {
|
|
|
1247
1909
|
console.log('');
|
|
1248
1910
|
}
|
|
1249
1911
|
/** `abx minter buy <token> [--to 0x…]` — buy one token through the shared minter (public; any
|
|
1250
|
-
* funded signer). ETH sales attach the price; ERC-20 sales need a prior approval to the minter.
|
|
1912
|
+
* funded signer). ETH sales attach the price; ERC-20 sales need a prior approval to the minter.
|
|
1913
|
+
* On an edition, `--token-id` is required and `--quantity` (default 1) buys several copies in the
|
|
1914
|
+
* same purchase — the total ETH attached is `price × quantity`. */
|
|
1251
1915
|
export async function cmdMinterBuy(address, flags) {
|
|
1252
|
-
const usage = 'abx minter buy <token> [--to 0x…] [--minter-contract 0x…] [--sign|--unsigned]';
|
|
1916
|
+
const usage = 'abx minter buy <token> [--to 0x…] [--token-id <n> --quantity <n> (editions)] [--minter-contract 0x…] [--sign|--unsigned]';
|
|
1253
1917
|
const token = requireAddress(address, usage);
|
|
1918
|
+
warnStrayFlags(flags, new Set(MINTER_BUY_FLAGS), 'minter buy');
|
|
1919
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
1920
|
+
const kind = await detectTokenKind(publicClient, token);
|
|
1921
|
+
if (kind.isEdition) {
|
|
1922
|
+
const tokenId = parseEditionCountFlag(requireFlag(flags, 'token-id', usage), 'token-id');
|
|
1923
|
+
const quantity = flags.quantity !== undefined ? parseEditionCountFlag(flags.quantity, 'quantity') : 1n;
|
|
1924
|
+
if (quantity === 0n)
|
|
1925
|
+
throw new Error('--quantity must be at least 1 (0 copies is not a purchase).');
|
|
1926
|
+
const minter = fixedPriceMinter1155Address(flags['minter-contract']);
|
|
1927
|
+
if (!minter)
|
|
1928
|
+
throw new Error(`no shared edition minter known for ${CHAIN} — configure a sale first, or set ABX_FIXED_PRICE_MINTER_1155`);
|
|
1929
|
+
const sale = await readSaleConfig1155(publicClient, minter, token, tokenId);
|
|
1930
|
+
if (!sale.configured)
|
|
1931
|
+
throw new Error(`no sale configured for ${token} #${tokenId} — run: abx minter configure ${token} --token-id ${tokenId} …`);
|
|
1932
|
+
const isEth = sale.paymentToken === zeroAddress;
|
|
1933
|
+
const to = flags.to && flags.to !== 'true' ? flags.to : undefined;
|
|
1934
|
+
// Payment math: price × quantity, computed ONCE and shown in the confirm/dry-run readout below
|
|
1935
|
+
// (via runMinterWrite → gatedSend's own preview) — the exact ETH the tx attaches.
|
|
1936
|
+
const value = isEth ? sale.price * quantity : 0n;
|
|
1937
|
+
if (!isEth) {
|
|
1938
|
+
console.log(yellow(` ERC-20 sale: the buyer must have approved ${minter} to spend ${sale.price * quantity} units of ${sale.paymentToken} first (else the tx reverts).`));
|
|
1939
|
+
}
|
|
1940
|
+
console.log(dim(` buying ${quantity} cop${quantity === 1n ? 'y' : 'ies'} of #${tokenId}${to ? ` → ${to}` : ' → signer'} for ` +
|
|
1941
|
+
`${isEth ? `${formatEther(value)} ETH (${formatEther(sale.price)} × ${quantity})` : `${value} units (${sale.price} × ${quantity})`}`));
|
|
1942
|
+
await runMinterWrite(preparePurchase1155({ minter, token, tokenId, quantity, to, value, chainId: chainId() }), flags);
|
|
1943
|
+
console.log(dim(` next: \`abx refresh ${token}\` so marketplaces pick up the change.`));
|
|
1944
|
+
return;
|
|
1945
|
+
}
|
|
1946
|
+
if (flags['token-id'] !== undefined || flags.quantity !== undefined) {
|
|
1947
|
+
throw new Error(`--token-id/--quantity are edition-only — ${token} is a ${kind.label} (721), where a sale buys exactly one token. Drop them.`);
|
|
1948
|
+
}
|
|
1254
1949
|
const minter = fixedPriceMinterAddress(flags['minter-contract']);
|
|
1255
1950
|
if (!minter)
|
|
1256
1951
|
throw new Error(`no shared minter known for ${CHAIN} — configure a sale first, or set ABX_FIXED_PRICE_MINTER`);
|
|
1257
|
-
const sale = await
|
|
1952
|
+
const sale = await readSaleConfig(publicClient, minter, token);
|
|
1258
1953
|
if (!sale.configured)
|
|
1259
1954
|
throw new Error(`no sale configured for ${token} — run: abx minter configure ${token} …`);
|
|
1260
1955
|
const isEth = sale.paymentToken === zeroAddress;
|
|
@@ -1267,4 +1962,131 @@ export async function cmdMinterBuy(address, flags) {
|
|
|
1267
1962
|
await runMinterWrite(preparePurchase({ minter, token, to, value, chainId: chainId() }), flags);
|
|
1268
1963
|
console.log(dim(` next: \`abx refresh ${token}\` so marketplaces pick up the new token.`));
|
|
1269
1964
|
}
|
|
1965
|
+
// ── PostParam schemas, after deploy ──────────────────────────────────────────
|
|
1966
|
+
// `setParamSchema` is owner-gated with no deploy-time restriction, so a project's param surface was
|
|
1967
|
+
// never actually frozen at deploy — the toolkit just had no way to reach it, which read to creators
|
|
1968
|
+
// as a protocol limitation ("we must guess every param up front, or redeploy and lose the address").
|
|
1969
|
+
// Two commands close that: `set-schema` (attach or replace one key) and `retire-param` (stop all
|
|
1970
|
+
// further writes, the closest thing to a delete the protocol has).
|
|
1971
|
+
/** Values already stored under a key can be stranded by a schema change — the contract does NOT
|
|
1972
|
+
* re-validate them. Compare old vs new and name what would break, so the guard can refuse. */
|
|
1973
|
+
export function strandingRisks(before, after) {
|
|
1974
|
+
const risks = [];
|
|
1975
|
+
const typeName = (i) => PARAM_TYPES[i] ?? String(i);
|
|
1976
|
+
if (before.paramType !== after.paramType) {
|
|
1977
|
+
risks.push(`type ${typeName(before.paramType)} → ${typeName(after.paramType)} (a stored value keeps its old encoding)`);
|
|
1978
|
+
}
|
|
1979
|
+
const dropped = before.selectOptions.filter((o) => !after.selectOptions.includes(o));
|
|
1980
|
+
if (before.selectOptions.length && dropped.length) {
|
|
1981
|
+
risks.push(`Select option(s) removed: ${dropped.join(', ')} (a token already set to one keeps it)`);
|
|
1982
|
+
}
|
|
1983
|
+
// Narrowing either bound can strand a value that sat inside the old range.
|
|
1984
|
+
const asInt = (h) => (PARAM_TYPES[after.paramType] === 'Int256Range' ? BigInt.asIntN(256, BigInt(h)) : BigInt(h));
|
|
1985
|
+
if (before.min !== after.min && asInt(after.min) > asInt(before.min))
|
|
1986
|
+
risks.push(`min raised (${asInt(before.min)} → ${asInt(after.min)})`);
|
|
1987
|
+
if (before.max !== after.max && asInt(before.max) !== 0n && asInt(after.max) < asInt(before.max)) {
|
|
1988
|
+
risks.push(`max lowered (${asInt(before.max)} → ${asInt(after.max)})`);
|
|
1989
|
+
}
|
|
1990
|
+
return risks;
|
|
1991
|
+
}
|
|
1992
|
+
/** `abx set-schema <address> --schema key:Type:Auth[:lock=<when>]` — attach or replace ONE key's
|
|
1993
|
+
* on-chain schema, any time in a project's life. Owner-only. */
|
|
1994
|
+
export async function cmdSetSchema(address, flags) {
|
|
1995
|
+
const usage = 'abx set-schema <address> --schema key:Type:Auth[:lock=<when>] [--force] [--dry-run] [--sign|--unsigned]';
|
|
1996
|
+
const contract = requireAddress(address, usage);
|
|
1997
|
+
const specs = parseSchemaSpecs(flags.schema);
|
|
1998
|
+
if (specs.length !== 1) {
|
|
1999
|
+
console.error(`usage: ${usage}\n\n One key per call — a schema write is a full-row upsert, so batching them hides which one changed.\n`);
|
|
2000
|
+
process.exitCode = 1;
|
|
2001
|
+
return;
|
|
2002
|
+
}
|
|
2003
|
+
const next = specs[0];
|
|
2004
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
2005
|
+
const owner = await read(contract, 'owner');
|
|
2006
|
+
const before = await readParamSchema(publicClient, contract, next.key);
|
|
2007
|
+
if (!before.exists) {
|
|
2008
|
+
console.log(` ${next.key} ${dim('— new governed key')} ${describeSchema(next)}`);
|
|
2009
|
+
}
|
|
2010
|
+
else {
|
|
2011
|
+
// The upsert hazard: this is a FULL row write, so anything not restated is overwritten. Show
|
|
2012
|
+
// both sides, and refuse a change that could strand values unless the caller insists.
|
|
2013
|
+
console.log(` ${next.key} ${dim('— replacing an existing schema')}`);
|
|
2014
|
+
console.log(` ${dim('before')} ${describeSchema(onChainToParsed(next.key, before))}`);
|
|
2015
|
+
console.log(` ${dim('after ')} ${describeSchema(next)}`);
|
|
2016
|
+
const risks = strandingRisks(before, next);
|
|
2017
|
+
if (risks.length && flags.force === undefined) {
|
|
2018
|
+
throw new Error(`refusing to replace "${next.key}" — this change can strand values already stored under it:\n` +
|
|
2019
|
+
risks.map((r) => ` • ${r}`).join('\n') +
|
|
2020
|
+
`\n\n The contract does NOT re-validate stored values against a new schema, so affected tokens would keep\n` +
|
|
2021
|
+
` values their own schema no longer allows. Re-run with --force if that is what you intend.`);
|
|
2022
|
+
}
|
|
2023
|
+
// With --force, say what is being overridden. Silently applying a value-stranding change is the
|
|
2024
|
+
// one outcome worse than refusing it: the operator gets no record of which tokens they may have
|
|
2025
|
+
// just invalidated, and neither does anyone reading the terminal afterwards.
|
|
2026
|
+
if (risks.length) {
|
|
2027
|
+
console.log(` ${C.yellow}⚠${C.reset} ${bold('--force')} — applying a change that can strand stored values:`);
|
|
2028
|
+
for (const r of risks)
|
|
2029
|
+
console.log(` • ${r}`);
|
|
2030
|
+
console.log(dim(` any token already holding a value for "${next.key}" keeps it, now outside what its schema allows.`));
|
|
2031
|
+
}
|
|
2032
|
+
if (before.lockAfter && !next.lockAfter) {
|
|
2033
|
+
console.log(` ${C.yellow}⚠${C.reset} the existing lock (${new Date(before.lockAfter * 1000).toISOString().slice(0, 19)}Z) is being REMOVED — restate it with :lock= to keep it.`);
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
// ONE op. A schema write used to need a `params.keys` companion write in the same tx to keep the
|
|
2037
|
+
// on-chain generator's key list in step; the generator now enumerates params from the token
|
|
2038
|
+
// itself, so the schema write is the whole change.
|
|
2039
|
+
await runWrite(contract, prepareSetParamSchema({
|
|
2040
|
+
contract,
|
|
2041
|
+
key: next.key,
|
|
2042
|
+
paramType: next.paramType,
|
|
2043
|
+
auth: next.auth,
|
|
2044
|
+
authAddress: next.authAddress,
|
|
2045
|
+
lockAfter: next.lockAfter,
|
|
2046
|
+
min: next.min,
|
|
2047
|
+
max: next.max,
|
|
2048
|
+
selectOptions: next.selectOptions,
|
|
2049
|
+
chainId: chainId(),
|
|
2050
|
+
display: describeSchema(next),
|
|
2051
|
+
}), flags, owner);
|
|
2052
|
+
}
|
|
2053
|
+
/** Render an on-chain schema through the same formatter the CLI uses for a parsed one. */
|
|
2054
|
+
function onChainToParsed(key, s) {
|
|
2055
|
+
return {
|
|
2056
|
+
key,
|
|
2057
|
+
paramType: s.paramType,
|
|
2058
|
+
auth: s.auth,
|
|
2059
|
+
authAddress: s.authAddress,
|
|
2060
|
+
lockAfter: s.lockAfter,
|
|
2061
|
+
min: s.min,
|
|
2062
|
+
max: s.max,
|
|
2063
|
+
selectOptions: s.selectOptions,
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
/** `abx retire-param <address> <key>` — permanently stop further writes to a PostParam. */
|
|
2067
|
+
export async function cmdRetireParam(address, rest, flags) {
|
|
2068
|
+
const usage = 'abx retire-param <address> <key> [--dry-run] [--sign|--unsigned]';
|
|
2069
|
+
const contract = requireAddress(address, usage);
|
|
2070
|
+
const [key] = positionalArgs(rest);
|
|
2071
|
+
if (!key) {
|
|
2072
|
+
console.error(`usage: ${usage}\n`);
|
|
2073
|
+
process.exitCode = 1;
|
|
2074
|
+
return;
|
|
2075
|
+
}
|
|
2076
|
+
const publicClient = makePublicClient({ chainKey: CHAIN });
|
|
2077
|
+
const owner = await read(contract, 'owner');
|
|
2078
|
+
const current = await readParamSchema(publicClient, contract, key);
|
|
2079
|
+
if (!current.exists)
|
|
2080
|
+
throw new Error(`no PostParam schema for "${key}" on ${contract} — nothing to retire.`);
|
|
2081
|
+
if (current.lockAfter && current.lockAfter < Math.floor(Date.now() / 1000)) {
|
|
2082
|
+
console.log(` ${C.green}✓${C.reset} "${key}" is already retired (locked ${new Date(current.lockAfter * 1000).toISOString().slice(0, 19)}Z). Nothing to do.`);
|
|
2083
|
+
return;
|
|
2084
|
+
}
|
|
2085
|
+
console.log(` ${key} ${dim(describeSchema(onChainToParsed(key, current)))}`);
|
|
2086
|
+
console.log(` ${dim('after this: every write reverts ParamLockExpired — permanently, with no way back.')}`);
|
|
2087
|
+
console.log(` ${dim('the schema stays (a key can never be un-governed), and any value ALREADY stored stays and keeps serving.')}`);
|
|
2088
|
+
// Read-modify-write: carry every field forward and change only the lock. Composing a fresh schema
|
|
2089
|
+
// here would silently reset type/auth/bounds/options — the upsert clobber this command exists to avoid.
|
|
2090
|
+
await runWrite(contract, prepareRetireParam({ contract, key, current, chainId: chainId() }), flags, owner);
|
|
2091
|
+
}
|
|
1270
2092
|
//# sourceMappingURL=ownerops.js.map
|