@givelotus/compiler 0.0.0-stage → 0.1.0
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/README.md +331 -2
- package/artifact-v2.schema.json +58 -0
- package/artifact.schema.json +19 -0
- package/dist/ast.d.ts +292 -0
- package/dist/ast.js +150 -0
- package/dist/bindings.d.ts +6 -0
- package/dist/bindings.js +134 -0
- package/dist/call-runtime.d.ts +84 -0
- package/dist/call-runtime.js +249 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +22 -0
- package/dist/compiler.d.ts +79 -0
- package/dist/compiler.js +125 -0
- package/dist/diagnostics.d.ts +163 -0
- package/dist/diagnostics.js +498 -0
- package/dist/ecash.d.ts +41 -0
- package/dist/ecash.js +190 -0
- package/dist/fees.d.ts +164 -0
- package/dist/fees.js +208 -0
- package/dist/fixture-cli.d.ts +2 -0
- package/dist/fixture-cli.js +41 -0
- package/dist/fixtures.d.ts +68 -0
- package/dist/fixtures.js +46 -0
- package/dist/forth-ir.d.ts +73 -0
- package/dist/forth-ir.js +147 -0
- package/dist/generic-cli.d.ts +2 -0
- package/dist/generic-cli.js +140 -0
- package/dist/generic.d.ts +48 -0
- package/dist/generic.js +2566 -0
- package/dist/lints.d.ts +8 -0
- package/dist/lints.js +204 -0
- package/dist/names.d.ts +1 -0
- package/dist/names.js +7 -0
- package/dist/opcodes.d.ts +154 -0
- package/dist/opcodes.js +162 -0
- package/dist/optimizer.d.ts +58 -0
- package/dist/optimizer.js +786 -0
- package/dist/package-fetch-cli.d.ts +2 -0
- package/dist/package-fetch-cli.js +17 -0
- package/dist/package-lock-cli.d.ts +2 -0
- package/dist/package-lock-cli.js +28 -0
- package/dist/package-sources.d.ts +82 -0
- package/dist/package-sources.js +785 -0
- package/dist/package-update-cli.d.ts +2 -0
- package/dist/package-update-cli.js +20 -0
- package/dist/packages.d.ts +231 -0
- package/dist/packages.js +1307 -0
- package/dist/parser.d.ts +32 -0
- package/dist/parser.js +575 -0
- package/dist/policy.d.ts +83 -0
- package/dist/policy.js +207 -0
- package/dist/runtime.d.ts +58 -0
- package/dist/runtime.js +126 -0
- package/dist/scheduler.d.ts +38 -0
- package/dist/scheduler.js +76 -0
- package/dist/semantic-ir.d.ts +76 -0
- package/dist/semantic-ir.js +231 -0
- package/dist/std.d.ts +27 -0
- package/dist/std.js +225 -0
- package/dist/target-compiler.d.ts +9 -0
- package/dist/target-compiler.js +139 -0
- package/dist/targets.d.ts +53 -0
- package/dist/targets.js +67 -0
- package/dist/toml-subset.d.ts +19 -0
- package/dist/toml-subset.js +81 -0
- package/dist/transaction-runtime.d.ts +182 -0
- package/dist/transaction-runtime.js +646 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.js +3 -0
- package/dist/vm-cost.d.ts +11 -0
- package/dist/vm-cost.js +541 -0
- package/package.json +71 -4
- package/policy-artifact.schema.json +20 -0
- package/std/custody/arbiter-escrow.lotus +20 -0
- package/std/custody/htlc.lotus +15 -0
- package/std/custody/multisig-2of3.lotus +13 -0
- package/std/custody/single-owner-wallet.lotus +9 -0
- package/std/custody/vault-with-recovery.lotus +14 -0
- package/std/defi/amm-pool-v2.lotus +97 -0
- package/std/defi/indexed-limit-order.lotus +37 -0
- package/std/nft/nft-collection.lotus +51 -0
- package/std/nft/royalty-transfer-rules.lotus +38 -0
- package/std/nft/unique-nft.lotus +30 -0
- package/std/tokens/capped-supply-token.lotus +76 -0
- package/std/tokens/fixed-supply-token.lotus +29 -0
- package/std/tokens/standard-transfer-rules.lotus +15 -0
- package/std/tokens/voucher-mint-token.lotus +31 -0
package/dist/ecash.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/** Narrow eCash backend. Portable semantic IR only; no Lotus bytecode reuse. */
|
|
2
|
+
import { validateSemanticProgram } from './semantic-ir.js';
|
|
3
|
+
import { resolveTarget, checkCapabilities } from './targets.js';
|
|
4
|
+
/** Data pushes preserve bytes exactly, including one-byte zero (not OP_0). */
|
|
5
|
+
function push(value) {
|
|
6
|
+
if (!value.length)
|
|
7
|
+
return [0x00];
|
|
8
|
+
if (value.length === 1 && value[0] >= 1 && value[0] <= 16)
|
|
9
|
+
return [0x50 + value[0]];
|
|
10
|
+
if (value.length === 1 && value[0] === 0x81)
|
|
11
|
+
return [0x4f];
|
|
12
|
+
if (value.length <= 75)
|
|
13
|
+
return [value.length, ...value];
|
|
14
|
+
if (value.length <= 255)
|
|
15
|
+
return [0x4c, value.length, ...value];
|
|
16
|
+
return [0x4d, value.length & 255, value.length >>> 8, ...value];
|
|
17
|
+
}
|
|
18
|
+
function number(value) {
|
|
19
|
+
const result = [];
|
|
20
|
+
for (; value; value = Math.floor(value / 256))
|
|
21
|
+
result.push(value & 255);
|
|
22
|
+
if (result.length && result[result.length - 1] & 0x80)
|
|
23
|
+
result.push(0);
|
|
24
|
+
return Uint8Array.from(result);
|
|
25
|
+
}
|
|
26
|
+
/** Validate the complete input and capabilities before creating any wire bytes. */
|
|
27
|
+
export function compileEcash(input) {
|
|
28
|
+
const checked = validateSemanticProgram(input);
|
|
29
|
+
if (!checked.ok)
|
|
30
|
+
return checked;
|
|
31
|
+
const target = resolveTarget('ecash');
|
|
32
|
+
const diagnostics = checkCapabilities(target, checked.requirements);
|
|
33
|
+
if (diagnostics.length)
|
|
34
|
+
return { ok: false, diagnostics };
|
|
35
|
+
const program = checked.program;
|
|
36
|
+
const fail = (message, span = program.span) => ({ ok: false,
|
|
37
|
+
diagnostics: [{ code: 'E1210', message: `ecash: ${message}`, span: { ...span } }] });
|
|
38
|
+
// Traverse both arms, including statically false ones. No unsupported or
|
|
39
|
+
// oversized constant can hide in a branch that happens not to execute.
|
|
40
|
+
let largest = 0;
|
|
41
|
+
let violation;
|
|
42
|
+
function inspect(expr) {
|
|
43
|
+
if (expr.kind === 'bytes') {
|
|
44
|
+
largest = Math.max(largest, expr.hex.length / 2);
|
|
45
|
+
if (expr.hex.length / 2 > target.limits.maxElementBytes)
|
|
46
|
+
violation ??= expr.span;
|
|
47
|
+
}
|
|
48
|
+
else if (expr.kind === 'bool')
|
|
49
|
+
largest = Math.max(largest, 1);
|
|
50
|
+
else if (expr.kind === 'sha256' || expr.kind === 'hash256') {
|
|
51
|
+
largest = Math.max(largest, 32);
|
|
52
|
+
inspect(expr.value);
|
|
53
|
+
}
|
|
54
|
+
else if (expr.kind === 'equal') {
|
|
55
|
+
inspect(expr.left);
|
|
56
|
+
inspect(expr.right);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function inspectBody(body) {
|
|
60
|
+
for (const stmt of body) {
|
|
61
|
+
inspect(stmt.condition);
|
|
62
|
+
if (stmt.kind === 'if') {
|
|
63
|
+
inspectBody(stmt.then);
|
|
64
|
+
inspectBody(stmt.otherwise);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
for (const arg of program.args) {
|
|
69
|
+
const size = arg.type.kind === 'bytes' ? arg.type.length : 1;
|
|
70
|
+
largest = Math.max(largest, size);
|
|
71
|
+
if (size > target.limits.maxElementBytes)
|
|
72
|
+
violation ??= arg.span;
|
|
73
|
+
}
|
|
74
|
+
inspectBody(program.body);
|
|
75
|
+
if (violation)
|
|
76
|
+
return fail(`element exceeds ${target.limits.maxElementBytes} bytes`, violation);
|
|
77
|
+
const stackLimit = target.limits.maxStackItems;
|
|
78
|
+
if (stackLimit === null)
|
|
79
|
+
return fail('concrete stack limit required');
|
|
80
|
+
if (program.args.length > stackLimit)
|
|
81
|
+
return fail('initial declared stack exceeds limit');
|
|
82
|
+
const wire = [];
|
|
83
|
+
const sourceMap = [];
|
|
84
|
+
let depth = program.args.length, peak = depth, ops = 0;
|
|
85
|
+
function emit(op, bytes, delta, span, counted = true) {
|
|
86
|
+
const start = wire.length;
|
|
87
|
+
wire.push(...bytes);
|
|
88
|
+
sourceMap.push({ op, source: { ...span }, byteStart: start, byteEnd: wire.length });
|
|
89
|
+
if (counted && bytes[0] > 0x60)
|
|
90
|
+
ops++;
|
|
91
|
+
depth += delta;
|
|
92
|
+
if (depth < 0)
|
|
93
|
+
throw Error('eCash backend internal stack underflow');
|
|
94
|
+
peak = Math.max(peak, depth);
|
|
95
|
+
}
|
|
96
|
+
function data(value, span) {
|
|
97
|
+
emit('PUSH', push(value), 1, span, false);
|
|
98
|
+
largest = Math.max(largest, value.length);
|
|
99
|
+
}
|
|
100
|
+
function pick(index, span) {
|
|
101
|
+
const distance = depth - index - 1;
|
|
102
|
+
if (!distance)
|
|
103
|
+
emit('DUP', [0x76], 1, span);
|
|
104
|
+
else {
|
|
105
|
+
data(number(distance), span);
|
|
106
|
+
emit('PICK', [0x79], 0, span);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// Args arrive bottom-to-top; originals remain at their fixed bottom indexes.
|
|
110
|
+
// Validate every declaration, including unused inputs, before body execution.
|
|
111
|
+
program.args.forEach((arg, index) => {
|
|
112
|
+
pick(index, arg.span);
|
|
113
|
+
if (arg.type.kind === 'bytes') {
|
|
114
|
+
emit('SIZE', [0x82], 1, arg.span);
|
|
115
|
+
data(number(arg.type.length), arg.span);
|
|
116
|
+
emit('EQUALVERIFY', [0x88], -2, arg.span);
|
|
117
|
+
emit('DROP', [0x75], -1, arg.span);
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
emit('DUP', [0x76], 1, arg.span);
|
|
121
|
+
data(new Uint8Array(), arg.span);
|
|
122
|
+
emit('EQUAL', [0x87], -1, arg.span);
|
|
123
|
+
emit('SWAP', [0x7c], 0, arg.span);
|
|
124
|
+
data(Uint8Array.of(1), arg.span);
|
|
125
|
+
emit('EQUAL', [0x87], -1, arg.span);
|
|
126
|
+
emit('BOOLOR', [0x9b], -1, arg.span);
|
|
127
|
+
emit('VERIFY', [0x69], -1, arg.span);
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
function expression(expr) {
|
|
131
|
+
switch (expr.kind) {
|
|
132
|
+
case 'bytes':
|
|
133
|
+
data(Uint8Array.from(Buffer.from(expr.hex, 'hex')), expr.span);
|
|
134
|
+
break;
|
|
135
|
+
case 'bool':
|
|
136
|
+
data(expr.value ? Uint8Array.of(1) : new Uint8Array(), expr.span);
|
|
137
|
+
break;
|
|
138
|
+
case 'arg':
|
|
139
|
+
pick(program.args.findIndex(arg => arg.name === expr.name), expr.span);
|
|
140
|
+
break;
|
|
141
|
+
case 'sha256':
|
|
142
|
+
case 'hash256':
|
|
143
|
+
expression(expr.value);
|
|
144
|
+
emit(expr.kind.toUpperCase(), [expr.kind === 'sha256' ? 0xa8 : 0xaa], 0, expr.span);
|
|
145
|
+
break;
|
|
146
|
+
case 'equal':
|
|
147
|
+
expression(expr.left);
|
|
148
|
+
expression(expr.right);
|
|
149
|
+
emit('EQUAL', [0x87], -1, expr.span);
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function body(statements) {
|
|
154
|
+
for (const stmt of statements) {
|
|
155
|
+
expression(stmt.condition);
|
|
156
|
+
if (stmt.kind === 'require')
|
|
157
|
+
emit('VERIFY', [0x69], -1, stmt.span);
|
|
158
|
+
else {
|
|
159
|
+
emit('IF', [0x63], -1, stmt.span);
|
|
160
|
+
const base = depth;
|
|
161
|
+
body(stmt.then);
|
|
162
|
+
if (depth !== base)
|
|
163
|
+
throw Error('eCash backend internal branch stack imbalance');
|
|
164
|
+
emit('ELSE', [0x67], 0, stmt.span);
|
|
165
|
+
body(stmt.otherwise);
|
|
166
|
+
if (depth !== base)
|
|
167
|
+
throw Error('eCash backend internal branch stack imbalance');
|
|
168
|
+
emit('ENDIF', [0x68], 0, stmt.span);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
body(program.body);
|
|
173
|
+
for (const arg of program.args)
|
|
174
|
+
emit('DROP', [0x75], -1, arg.span);
|
|
175
|
+
data(Uint8Array.of(1), program.span);
|
|
176
|
+
if (depth !== 1)
|
|
177
|
+
throw Error('eCash backend internal final stack imbalance');
|
|
178
|
+
if (wire.length > target.limits.maxScriptBytes)
|
|
179
|
+
return fail(`script exceeds ${target.limits.maxScriptBytes} bytes`);
|
|
180
|
+
if (ops > target.limits.maxOps)
|
|
181
|
+
return fail(`script exceeds ${target.limits.maxOps} opcodes (both branches counted)`);
|
|
182
|
+
if (peak > stackLimit)
|
|
183
|
+
return fail(`stack exceeds ${stackLimit} items`);
|
|
184
|
+
return { ok: true, artifact: {
|
|
185
|
+
schema: 'ecash/script-artifact/1', target: 'ecash', targetRevision: target.revision, targetProfile: target.profile,
|
|
186
|
+
entrypoint: program.entrypoint, args: program.args.map(arg => ({ ...arg, type: { ...arg.type }, span: { ...arg.span } })),
|
|
187
|
+
scriptHex: Buffer.from(wire).toString('hex'), sourceMap,
|
|
188
|
+
staticResources: { scriptBytes: wire.length, opCount: ops, maxStackItems: peak, maxElementBytes: largest },
|
|
189
|
+
} };
|
|
190
|
+
}
|
package/dist/fees.d.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fee floors for planned transactions (C14a, C14b, C14c and P05).
|
|
3
|
+
*
|
|
4
|
+
* Nothing here is a chain default. Every value that depends on the chain (the
|
|
5
|
+
* byte-fee rate, the dust limit, the subsidy index and the EMA) comes from an
|
|
6
|
+
* explicit `FeeParameters` object. `SPEC_FEE_PARAMETERS` holds the spec values
|
|
7
|
+
* at the calibration point (both subsidy indices 1, a quiet chain) for tests and examples.
|
|
8
|
+
*
|
|
9
|
+
* Two floors exist:
|
|
10
|
+
* - the consensus floor: C14b's indexed byte fee and C14a's token-output burn;
|
|
11
|
+
* - the cu share (P05 "Relay and wallet fee policy"): the transaction's share
|
|
12
|
+
* of the block burn floor R, 2 * ((C_tx * max(E, E_min)) >> S_linear) * sqrt(I),
|
|
13
|
+
* plus its share of the concentration term Q. This is what relay and wallet
|
|
14
|
+
* fee estimation charge; a transaction paying only the consensus floor is
|
|
15
|
+
* valid but leaves the miner to burn its share out of the subsidy.
|
|
16
|
+
*/
|
|
17
|
+
import { MAX_MONEY } from './runtime.js';
|
|
18
|
+
export { MAX_MONEY };
|
|
19
|
+
/** P05's approved cost schedule (2026-11-18), as in the reference `APPROVED` and `APPROVED_BURN`. */
|
|
20
|
+
export type CostSchedule = {
|
|
21
|
+
/** cu per serialized wire byte. */
|
|
22
|
+
wireByteCu: bigint;
|
|
23
|
+
/** S_tx_knee: C_tx = L + ((L * L) >> S_tx_knee). */
|
|
24
|
+
txKneeShift: bigint;
|
|
25
|
+
/** E_min, the floor of the EMA price M = max(E, E_min). */
|
|
26
|
+
emaMin: bigint;
|
|
27
|
+
/** S_linear: the linear burn is (C * M) >> S_linear. */
|
|
28
|
+
linearShift: bigint;
|
|
29
|
+
/** S_quad: the fixed concentration branch is C_block^2 >> S_quad. */
|
|
30
|
+
quadShift: bigint;
|
|
31
|
+
};
|
|
32
|
+
export declare const APPROVED_COST_SCHEDULE: Readonly<CostSchedule>;
|
|
33
|
+
export type FeeParameters = CostSchedule & {
|
|
34
|
+
/** C14b MIN_FEE_PER_KB, atoms per 1,000 bytes. */
|
|
35
|
+
minFeePerKb: bigint;
|
|
36
|
+
/** C14a/C14c DUST_LIMIT. */
|
|
37
|
+
dustLimitAtoms: bigint;
|
|
38
|
+
/** Genesis tail anchor T_g (atoms) and genesis work W_g. */
|
|
39
|
+
genesisTail: bigint;
|
|
40
|
+
genesisWork: bigint;
|
|
41
|
+
/**
|
|
42
|
+
* The byte-fee index (C14b): subsidy S_a of block a = max(1, h - COINBASE_MATURITY) and
|
|
43
|
+
* its parent's work W_(a-1), for a transaction in block h.
|
|
44
|
+
*/
|
|
45
|
+
byteIndexSubsidy: bigint;
|
|
46
|
+
byteIndexWork: bigint;
|
|
47
|
+
/**
|
|
48
|
+
* The block's own index (P05), for the cu share and Q: the subsidy S_n of the block the
|
|
49
|
+
* transaction goes in and its parent's work W_(n-1).
|
|
50
|
+
*/
|
|
51
|
+
blockSubsidy: bigint;
|
|
52
|
+
parentWork: bigint;
|
|
53
|
+
/** The chain's ema_block_cost E_n. */
|
|
54
|
+
ema: bigint;
|
|
55
|
+
/** Expected cost of the rest of the block, for the transaction's share of Q. */
|
|
56
|
+
blockCostCu?: bigint;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Spec values at the calibration point: MIN_FEE_PER_KB = 1000 (C14b), DUST_LIMIT = 546
|
|
60
|
+
* (C14c), the approved schedule, both indices 1 and E = E_min. A wallet replaces the indices
|
|
61
|
+
* and EMA with the chain's values.
|
|
62
|
+
*/
|
|
63
|
+
export declare const SPEC_FEE_PARAMETERS: Readonly<FeeParameters>;
|
|
64
|
+
/** How the required fee is computed. */
|
|
65
|
+
export type FeeRule = 'cu-share' | 'consensus';
|
|
66
|
+
/**
|
|
67
|
+
* `rule` defaults to `cu-share`. `consensus` pays only the per-transaction consensus
|
|
68
|
+
* minimum, for vectors and tests. The fee may not exceed `maxFeeAtoms`, which defaults
|
|
69
|
+
* to DEFAULT_MAX_FEE_MULTIPLE times the required fee; set it to pay more.
|
|
70
|
+
*/
|
|
71
|
+
export type FeePolicy = {
|
|
72
|
+
parameters: FeeParameters;
|
|
73
|
+
rule?: FeeRule;
|
|
74
|
+
maxFeeAtoms?: bigint;
|
|
75
|
+
/**
|
|
76
|
+
* Measured VM charges keyed `input:witness`, such as testv2transaction's
|
|
77
|
+
* accounting_cost; they replace the static charge for those invocations.
|
|
78
|
+
*/
|
|
79
|
+
invocationCu?: Readonly<Record<string, bigint>>;
|
|
80
|
+
};
|
|
81
|
+
export declare const DEFAULT_MAX_FEE_MULTIPLE = 10n;
|
|
82
|
+
export declare function assertFeeParameters(p: FeeParameters): void;
|
|
83
|
+
export declare function assertFeePolicy(policy: FeePolicy): void;
|
|
84
|
+
export declare function isqrt(n: bigint): bigint;
|
|
85
|
+
/** C14b ByteFee(b) = ceil(MIN_FEE_PER_KB * b / 1000). */
|
|
86
|
+
export declare function byteFee(size: number | bigint, p: FeeParameters): bigint;
|
|
87
|
+
/** C14b IndexedByteFee: the ceiling square root of floor(ByteFee(b)^2 * I_sub). */
|
|
88
|
+
export declare function indexedByteFee(size: number | bigint, p: FeeParameters): bigint;
|
|
89
|
+
/** C14a: 2 * DUST_LIMIT per token-bearing output created. */
|
|
90
|
+
export declare function tokenOutputBurn(tokenOutputs: number, p: FeeParameters): bigint;
|
|
91
|
+
/** C_tx = L + ((L * L) >> S_tx_knee). */
|
|
92
|
+
export declare function transactionCost(linear: bigint, p: CostSchedule): bigint;
|
|
93
|
+
/**
|
|
94
|
+
* The transaction's cu share in atoms: twice what it must burn, because C16 burns half
|
|
95
|
+
* of the fee. The linear part is 2 * ceil((C_tx * M) / 2^S_linear) scaled by sqrt(I_n),
|
|
96
|
+
* the block's own index
|
|
97
|
+
* (rounded up); the concentration part is twice the growth of P05's Q that the transaction
|
|
98
|
+
* causes on top of `blockCostCu` (0 when unset). Rounding is upward throughout, so the
|
|
99
|
+
* share is never below P05's expression.
|
|
100
|
+
*/
|
|
101
|
+
export declare function cuShareAtoms(costCu: bigint, p: FeeParameters): bigint;
|
|
102
|
+
/**
|
|
103
|
+
* P05 Q = max(C^2 >> S_quad, floor(S * e^2 / E_min^2)), e = max(0, C - E_min), with S the
|
|
104
|
+
* block subsidy (`blockSubsidy`). `up` rounds the divisions up.
|
|
105
|
+
*/
|
|
106
|
+
export declare function concentration(cost: bigint, p: FeeParameters, up?: boolean): bigint;
|
|
107
|
+
/** Outer (non-VM) weights of the approved schedule, from the reference `Schedule`. */
|
|
108
|
+
export declare const APPROVED_OUTER_WEIGHTS: Readonly<{
|
|
109
|
+
hashBlock: 1n;
|
|
110
|
+
invocationBase: 6n;
|
|
111
|
+
coinRead: 64n;
|
|
112
|
+
coinByte: 1n;
|
|
113
|
+
keyRead: 64n;
|
|
114
|
+
keyLevels: 27n;
|
|
115
|
+
pathMatch: 2n;
|
|
116
|
+
assetRecord: 1n;
|
|
117
|
+
mintLookup: 2n;
|
|
118
|
+
}>;
|
|
119
|
+
export type CostShapeInput = {
|
|
120
|
+
kind: 'spend';
|
|
121
|
+
coreBytes: number;
|
|
122
|
+
fullBytes: number;
|
|
123
|
+
coinOutputBytes: number;
|
|
124
|
+
witnesses: CostShapeWitness[];
|
|
125
|
+
} | {
|
|
126
|
+
kind: 'mint';
|
|
127
|
+
coreBytes: number;
|
|
128
|
+
fullBytes: number;
|
|
129
|
+
witnesses: [CostShapeWitness];
|
|
130
|
+
};
|
|
131
|
+
/** `vmCu` is the invocation's static VM charge, including 1 cu per script byte. */
|
|
132
|
+
export type CostShapeWitness = {
|
|
133
|
+
scriptBytes: number;
|
|
134
|
+
siblings: number;
|
|
135
|
+
vmCu: bigint;
|
|
136
|
+
};
|
|
137
|
+
export type CostShape = {
|
|
138
|
+
wireBytes: number;
|
|
139
|
+
inputs: CostShapeInput[];
|
|
140
|
+
outputs: {
|
|
141
|
+
bytes: number;
|
|
142
|
+
burn: boolean;
|
|
143
|
+
}[];
|
|
144
|
+
};
|
|
145
|
+
/** L(tx) for an ordinary transaction. */
|
|
146
|
+
export declare function linearCost(shape: CostShape, p: CostSchedule): bigint;
|
|
147
|
+
export { staticInvocationCu, type FieldSizes } from './vm-cost.js';
|
|
148
|
+
export type FeeRequirement = {
|
|
149
|
+
wireBytes: number;
|
|
150
|
+
linearCostCu: bigint;
|
|
151
|
+
transactionCostCu: bigint;
|
|
152
|
+
/** C14b at this size and index. */
|
|
153
|
+
byteFeeAtoms: bigint;
|
|
154
|
+
/** C14a. */
|
|
155
|
+
tokenOutputBurnAtoms: bigint;
|
|
156
|
+
cuShareAtoms: bigint;
|
|
157
|
+
/** The consensus floor: max(byte fee, token burn). */
|
|
158
|
+
minimumFeeAtoms: bigint;
|
|
159
|
+
/** The floor the policy requires. */
|
|
160
|
+
requiredFeeAtoms: bigint;
|
|
161
|
+
maxFeeAtoms: bigint;
|
|
162
|
+
rule: FeeRule;
|
|
163
|
+
};
|
|
164
|
+
export declare function feeRequirement(shape: CostShape, tokenOutputs: number, policy: FeePolicy): FeeRequirement;
|
package/dist/fees.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fee floors for planned transactions (C14a, C14b, C14c and P05).
|
|
3
|
+
*
|
|
4
|
+
* Nothing here is a chain default. Every value that depends on the chain (the
|
|
5
|
+
* byte-fee rate, the dust limit, the subsidy index and the EMA) comes from an
|
|
6
|
+
* explicit `FeeParameters` object. `SPEC_FEE_PARAMETERS` holds the spec values
|
|
7
|
+
* at the calibration point (both subsidy indices 1, a quiet chain) for tests and examples.
|
|
8
|
+
*
|
|
9
|
+
* Two floors exist:
|
|
10
|
+
* - the consensus floor: C14b's indexed byte fee and C14a's token-output burn;
|
|
11
|
+
* - the cu share (P05 "Relay and wallet fee policy"): the transaction's share
|
|
12
|
+
* of the block burn floor R, 2 * ((C_tx * max(E, E_min)) >> S_linear) * sqrt(I),
|
|
13
|
+
* plus its share of the concentration term Q. This is what relay and wallet
|
|
14
|
+
* fee estimation charge; a transaction paying only the consensus floor is
|
|
15
|
+
* valid but leaves the miner to burn its share out of the subsidy.
|
|
16
|
+
*/
|
|
17
|
+
import { MAX_MONEY } from './runtime.js';
|
|
18
|
+
export { MAX_MONEY };
|
|
19
|
+
const U64 = (1n << 64n) - 1n;
|
|
20
|
+
export const APPROVED_COST_SCHEDULE = Object.freeze({
|
|
21
|
+
wireByteCu: 2n,
|
|
22
|
+
txKneeShift: 18n,
|
|
23
|
+
emaMin: 1n << 34n,
|
|
24
|
+
linearShift: 32n,
|
|
25
|
+
quadShift: 32n,
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* Spec values at the calibration point: MIN_FEE_PER_KB = 1000 (C14b), DUST_LIMIT = 546
|
|
29
|
+
* (C14c), the approved schedule, both indices 1 and E = E_min. A wallet replaces the indices
|
|
30
|
+
* and EMA with the chain's values.
|
|
31
|
+
*/
|
|
32
|
+
export const SPEC_FEE_PARAMETERS = Object.freeze({
|
|
33
|
+
...APPROVED_COST_SCHEDULE,
|
|
34
|
+
minFeePerKb: 1000n,
|
|
35
|
+
dustLimitAtoms: 546n,
|
|
36
|
+
genesisTail: 1n,
|
|
37
|
+
genesisWork: 1n,
|
|
38
|
+
byteIndexSubsidy: 1n,
|
|
39
|
+
byteIndexWork: 1n,
|
|
40
|
+
blockSubsidy: 1n,
|
|
41
|
+
parentWork: 1n,
|
|
42
|
+
ema: 0n,
|
|
43
|
+
});
|
|
44
|
+
export const DEFAULT_MAX_FEE_MULTIPLE = 10n;
|
|
45
|
+
function nonnegative(value, name) {
|
|
46
|
+
if (typeof value !== 'bigint' || value < 0n)
|
|
47
|
+
throw new Error(`fee parameter ${name} must be a nonnegative bigint`);
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
export function assertFeeParameters(p) {
|
|
51
|
+
if (!p || typeof p !== 'object')
|
|
52
|
+
throw new Error('fee parameters required');
|
|
53
|
+
for (const name of ['wireByteCu', 'txKneeShift', 'emaMin', 'linearShift', 'quadShift', 'minFeePerKb', 'dustLimitAtoms',
|
|
54
|
+
'genesisTail', 'genesisWork', 'byteIndexSubsidy', 'byteIndexWork', 'blockSubsidy', 'parentWork', 'ema'])
|
|
55
|
+
nonnegative(p[name], name);
|
|
56
|
+
if (p.blockCostCu !== undefined)
|
|
57
|
+
nonnegative(p.blockCostCu, 'blockCostCu');
|
|
58
|
+
for (const name of ['genesisTail', 'genesisWork', 'byteIndexWork', 'parentWork', 'emaMin', 'wireByteCu'])
|
|
59
|
+
if (p[name] === 0n)
|
|
60
|
+
throw new Error(`fee parameter ${name} must be positive`);
|
|
61
|
+
if (p.dustLimitAtoms > MAX_MONEY)
|
|
62
|
+
throw new Error('fee parameter dustLimitAtoms exceeds MAX_MONEY');
|
|
63
|
+
for (const name of ['txKneeShift', 'linearShift', 'quadShift'])
|
|
64
|
+
if (p[name] > 255n)
|
|
65
|
+
throw new Error(`fee parameter ${name} is not a shift`);
|
|
66
|
+
}
|
|
67
|
+
export function assertFeePolicy(policy) {
|
|
68
|
+
if (!policy || typeof policy !== 'object')
|
|
69
|
+
throw new Error('fee policy required: { parameters, rule?, maxFeeAtoms?, invocationCu? }');
|
|
70
|
+
assertFeeParameters(policy.parameters);
|
|
71
|
+
if (policy.rule !== undefined && policy.rule !== 'cu-share' && policy.rule !== 'consensus')
|
|
72
|
+
throw new Error('fee rule must be cu-share or consensus');
|
|
73
|
+
for (const [key, value] of Object.entries(policy.invocationCu ?? {})) {
|
|
74
|
+
if (!/^(0|[1-9][0-9]*):(0|[1-9][0-9]*)$/.test(key))
|
|
75
|
+
throw new Error(`invocationCu key ${key} is not input:witness`);
|
|
76
|
+
nonnegative(value, `invocationCu[${key}]`);
|
|
77
|
+
}
|
|
78
|
+
if (policy.maxFeeAtoms !== undefined)
|
|
79
|
+
nonnegative(policy.maxFeeAtoms, 'maxFeeAtoms');
|
|
80
|
+
}
|
|
81
|
+
export function isqrt(n) {
|
|
82
|
+
if (n < 0n)
|
|
83
|
+
throw new Error('isqrt of a negative value');
|
|
84
|
+
if (n < 2n)
|
|
85
|
+
return n;
|
|
86
|
+
let x = BigInt(Math.floor(Math.sqrt(Number(n))));
|
|
87
|
+
while (x * x > n)
|
|
88
|
+
x--;
|
|
89
|
+
while ((x + 1n) * (x + 1n) <= n)
|
|
90
|
+
x++;
|
|
91
|
+
return x;
|
|
92
|
+
}
|
|
93
|
+
function ceilSqrt(n) { const r = isqrt(n); return r * r < n ? r + 1n : r; }
|
|
94
|
+
/** floor(floor(v^2 * S * W_g / W) / T_g) = floor(v^2 * I) for an index I = S * W_g / (T_g * W). */
|
|
95
|
+
function radicand(v, subsidy, work, p) {
|
|
96
|
+
return (v * v * subsidy * p.genesisWork) / work / p.genesisTail;
|
|
97
|
+
}
|
|
98
|
+
/** C14b ByteFee(b) = ceil(MIN_FEE_PER_KB * b / 1000). */
|
|
99
|
+
export function byteFee(size, p) {
|
|
100
|
+
const b = BigInt(size);
|
|
101
|
+
if (b < 0n)
|
|
102
|
+
throw new Error('byte count must be nonnegative');
|
|
103
|
+
return (p.minFeePerKb * b + 999n) / 1000n;
|
|
104
|
+
}
|
|
105
|
+
/** C14b IndexedByteFee: the ceiling square root of floor(ByteFee(b)^2 * I_sub). */
|
|
106
|
+
export function indexedByteFee(size, p) {
|
|
107
|
+
return ceilSqrt(radicand(byteFee(size, p), p.byteIndexSubsidy, p.byteIndexWork, p));
|
|
108
|
+
}
|
|
109
|
+
/** C14a: 2 * DUST_LIMIT per token-bearing output created. */
|
|
110
|
+
export function tokenOutputBurn(tokenOutputs, p) {
|
|
111
|
+
return 2n * p.dustLimitAtoms * BigInt(tokenOutputs);
|
|
112
|
+
}
|
|
113
|
+
/** C_tx = L + ((L * L) >> S_tx_knee). */
|
|
114
|
+
export function transactionCost(linear, p) {
|
|
115
|
+
if (linear < 0n || linear > U64)
|
|
116
|
+
throw new Error('linear cost out of u64 range');
|
|
117
|
+
const c = linear + ((linear * linear) >> p.txKneeShift);
|
|
118
|
+
if (c > U64)
|
|
119
|
+
throw new Error('transaction cost exceeds u64');
|
|
120
|
+
return c;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The transaction's cu share in atoms: twice what it must burn, because C16 burns half
|
|
124
|
+
* of the fee. The linear part is 2 * ceil((C_tx * M) / 2^S_linear) scaled by sqrt(I_n),
|
|
125
|
+
* the block's own index
|
|
126
|
+
* (rounded up); the concentration part is twice the growth of P05's Q that the transaction
|
|
127
|
+
* causes on top of `blockCostCu` (0 when unset). Rounding is upward throughout, so the
|
|
128
|
+
* share is never below P05's expression.
|
|
129
|
+
*/
|
|
130
|
+
export function cuShareAtoms(costCu, p) {
|
|
131
|
+
const m = p.ema > p.emaMin ? p.ema : p.emaMin;
|
|
132
|
+
const shift = 1n << p.linearShift;
|
|
133
|
+
const linear = (costCu * m + shift - 1n) / shift;
|
|
134
|
+
const indexed = ceilSqrt(radicand(linear, p.blockSubsidy, p.parentWork, p));
|
|
135
|
+
const block = p.blockCostCu ?? 0n, after = block + costCu;
|
|
136
|
+
return 2n * (indexed + concentration(after, p, true) - concentration(block, p, false));
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* P05 Q = max(C^2 >> S_quad, floor(S * e^2 / E_min^2)), e = max(0, C - E_min), with S the
|
|
140
|
+
* block subsidy (`blockSubsidy`). `up` rounds the divisions up.
|
|
141
|
+
*/
|
|
142
|
+
export function concentration(cost, p, up = false) {
|
|
143
|
+
const div = (a, b) => (up ? (a + b - 1n) / b : a / b);
|
|
144
|
+
const excess = cost > p.emaMin ? cost - p.emaMin : 0n;
|
|
145
|
+
const fixed = div(cost * cost, 1n << p.quadShift);
|
|
146
|
+
const counted = div(p.blockSubsidy * excess * excess, p.emaMin * p.emaMin);
|
|
147
|
+
return fixed > counted ? fixed : counted;
|
|
148
|
+
}
|
|
149
|
+
// ---------------------------------------------------------------------------
|
|
150
|
+
// L(tx): the reference's `linear_cost` under the approved schedule.
|
|
151
|
+
/** Outer (non-VM) weights of the approved schedule, from the reference `Schedule`. */
|
|
152
|
+
export const APPROVED_OUTER_WEIGHTS = Object.freeze({
|
|
153
|
+
hashBlock: 1n, invocationBase: 6n, coinRead: 64n, coinByte: 1n, keyRead: 64n, keyLevels: 27n,
|
|
154
|
+
pathMatch: 2n, assetRecord: 1n, mintLookup: 2n,
|
|
155
|
+
});
|
|
156
|
+
function cs(n) { return n < 253 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9; }
|
|
157
|
+
function h(n) { return APPROVED_OUTER_WEIGHTS.hashBlock * BigInt(Math.ceil((n + 64) / 64)); }
|
|
158
|
+
/** P02 Coin record length for an output of `n` bytes. */
|
|
159
|
+
function coinLength(n) { return 32 + 4 + cs(n) + n + 8 + 8 + 1 + 1 + 8 + 8; }
|
|
160
|
+
function stateKey(coin) {
|
|
161
|
+
const w = APPROVED_OUTER_WEIGHTS;
|
|
162
|
+
return h(36) + h(33 + cs(coin) + coin) + w.keyLevels * h(67) + w.keyRead;
|
|
163
|
+
}
|
|
164
|
+
/** L(tx) for an ordinary transaction. */
|
|
165
|
+
export function linearCost(shape, p) {
|
|
166
|
+
const w = APPROVED_OUTER_WEIGHTS;
|
|
167
|
+
let total = p.wireByteCu * BigInt(shape.wireBytes) + 2n * h(112);
|
|
168
|
+
let spends = 0;
|
|
169
|
+
for (const input of shape.inputs) {
|
|
170
|
+
total += h(input.coreBytes) + h(input.fullBytes);
|
|
171
|
+
for (const witness of input.witnesses)
|
|
172
|
+
total += witness.vmCu + w.invocationBase + h(1 + cs(witness.scriptBytes) + witness.scriptBytes) + BigInt(witness.siblings) * h(65);
|
|
173
|
+
if (input.kind === 'spend') {
|
|
174
|
+
spends++;
|
|
175
|
+
const n = input.coinOutputBytes, coin = coinLength(n);
|
|
176
|
+
total += w.coinRead + w.coinByte * BigInt(coin);
|
|
177
|
+
total += h(cs(n) + n) + h(input.coreBytes + cs(n) + n);
|
|
178
|
+
total += w.pathMatch + stateKey(coin);
|
|
179
|
+
}
|
|
180
|
+
else
|
|
181
|
+
total += h(0) + w.mintLookup;
|
|
182
|
+
}
|
|
183
|
+
total += (6n * BigInt(Math.max(shape.inputs.length, 1)) + 2n * BigInt(Math.max(shape.outputs.length, 1))) * h(66);
|
|
184
|
+
for (const output of shape.outputs) {
|
|
185
|
+
total += h(cs(output.bytes) + output.bytes);
|
|
186
|
+
if (!output.burn)
|
|
187
|
+
total += stateKey(coinLength(output.bytes));
|
|
188
|
+
}
|
|
189
|
+
total += w.assetRecord * BigInt(shape.inputs.length + shape.outputs.length + spends);
|
|
190
|
+
if (total > U64)
|
|
191
|
+
throw new Error('transaction linear cost exceeds u64');
|
|
192
|
+
return total;
|
|
193
|
+
}
|
|
194
|
+
export { staticInvocationCu } from './vm-cost.js';
|
|
195
|
+
export function feeRequirement(shape, tokenOutputs, policy) {
|
|
196
|
+
assertFeePolicy(policy);
|
|
197
|
+
const p = policy.parameters, rule = policy.rule ?? 'cu-share';
|
|
198
|
+
const linearCostCu = linearCost(shape, p), transactionCostCu = transactionCost(linearCostCu, p);
|
|
199
|
+
const byte = indexedByteFee(shape.wireBytes, p), burn = tokenOutputBurn(tokenOutputs, p);
|
|
200
|
+
const share = cuShareAtoms(transactionCostCu, p);
|
|
201
|
+
const minimumFeeAtoms = byte > burn ? byte : burn;
|
|
202
|
+
// The token burn is burned on its own and does not count toward R (C16: G = F - T_tok).
|
|
203
|
+
const withShare = burn + share;
|
|
204
|
+
const requiredFeeAtoms = rule === 'consensus' ? minimumFeeAtoms : withShare > minimumFeeAtoms ? withShare : minimumFeeAtoms;
|
|
205
|
+
const maxFeeAtoms = policy.maxFeeAtoms ?? DEFAULT_MAX_FEE_MULTIPLE * requiredFeeAtoms;
|
|
206
|
+
return { wireBytes: shape.wireBytes, linearCostCu, transactionCostCu, byteFeeAtoms: byte, tokenOutputBurnAtoms: burn,
|
|
207
|
+
cuShareAtoms: share, minimumFeeAtoms, requiredFeeAtoms, maxFeeAtoms, rule };
|
|
208
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { buildPaymentFixture } from './fixtures.js';
|
|
4
|
+
function object(x) { if (!x || typeof x !== 'object' || Array.isArray(x))
|
|
5
|
+
throw new Error('expected object'); return x; }
|
|
6
|
+
function string(x) { if (typeof x !== 'string')
|
|
7
|
+
throw new Error('expected string'); return x; }
|
|
8
|
+
function number(x) { if (!Number.isInteger(x))
|
|
9
|
+
throw new Error('expected integer'); return x; }
|
|
10
|
+
function decimal(x) { const s = string(x); if (!/^(0|[1-9][0-9]*)$/.test(s))
|
|
11
|
+
throw new Error('expected canonical decimal atom string'); return BigInt(s); }
|
|
12
|
+
function output(x) {
|
|
13
|
+
const o = object(x);
|
|
14
|
+
if (o.flags !== 0 || !Array.isArray(o.branches) || !Array.isArray(o.paths))
|
|
15
|
+
throw new Error('payment output shape');
|
|
16
|
+
return { flags: 0, value: decimal(o.valueAtoms), branches: o.branches.map(string), paths: o.paths.map(p => { if (!Array.isArray(p))
|
|
17
|
+
throw new Error('path array'); return p.map(number); }) };
|
|
18
|
+
}
|
|
19
|
+
function parse(x) {
|
|
20
|
+
const o = object(x);
|
|
21
|
+
if (o.schema !== 'lotus/payment-fixture-input/1')
|
|
22
|
+
throw new Error('fixture input schema');
|
|
23
|
+
const outpoint = object(o.outpoint);
|
|
24
|
+
if (!Array.isArray(o.outputs))
|
|
25
|
+
throw new Error('outputs array');
|
|
26
|
+
if (o.signingMode !== 0 || o.profile !== 'payment-fixture-p01-v1')
|
|
27
|
+
throw new Error('FULL fixture profile only');
|
|
28
|
+
return { source: string(o.source), owner: string(o.owner), testSecret: string(o.testSecret), chainId: string(o.chainId),
|
|
29
|
+
outpoint: { txid: string(outpoint.txid), index: number(outpoint.index) }, sequence: number(o.sequence), lock: decimal(o.lock),
|
|
30
|
+
coin: output(o.coin), outputs: o.outputs.map(output), profile: o.profile, signingMode: 0 };
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
if (process.argv.length !== 4)
|
|
34
|
+
throw new Error('usage: lotus-payment-fixture INPUT.json OUTPUT.json');
|
|
35
|
+
const fixture = buildPaymentFixture(parse(JSON.parse(readFileSync(process.argv[2], 'utf8'))));
|
|
36
|
+
writeFileSync(process.argv[3], JSON.stringify(fixture, null, 2) + '\n');
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
process.stderr.write(`${err.message}\n`);
|
|
40
|
+
process.exitCode = 1;
|
|
41
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { compilePayment } from './compiler.js';
|
|
2
|
+
import { finalizePayment, type PaymentOutput } from './runtime.js';
|
|
3
|
+
export type PaymentFixtureInput = {
|
|
4
|
+
source: string;
|
|
5
|
+
owner: string;
|
|
6
|
+
testSecret: string;
|
|
7
|
+
chainId: string;
|
|
8
|
+
outpoint: {
|
|
9
|
+
txid: string;
|
|
10
|
+
index: number;
|
|
11
|
+
};
|
|
12
|
+
sequence: number;
|
|
13
|
+
lock: bigint;
|
|
14
|
+
coin: PaymentOutput;
|
|
15
|
+
outputs: PaymentOutput[];
|
|
16
|
+
profile: 'payment-fixture-p01-v1';
|
|
17
|
+
signingMode: 0;
|
|
18
|
+
};
|
|
19
|
+
type JsonOutput = {
|
|
20
|
+
valueAtoms: string;
|
|
21
|
+
branches: string[];
|
|
22
|
+
paths: number[][];
|
|
23
|
+
flags: 0;
|
|
24
|
+
};
|
|
25
|
+
export type PaymentFixture = {
|
|
26
|
+
schema: 'lotus/payment-fixture/1';
|
|
27
|
+
source: string;
|
|
28
|
+
artifact: ReturnType<typeof compilePayment>;
|
|
29
|
+
context: {
|
|
30
|
+
chainId: string;
|
|
31
|
+
outpoint: {
|
|
32
|
+
txid: string;
|
|
33
|
+
index: number;
|
|
34
|
+
};
|
|
35
|
+
sequence: number;
|
|
36
|
+
lock: string;
|
|
37
|
+
profile: 'payment-fixture-p01-v1';
|
|
38
|
+
signingMode: 0;
|
|
39
|
+
coin: JsonOutput;
|
|
40
|
+
coinWire: string;
|
|
41
|
+
outputs: JsonOutput[];
|
|
42
|
+
};
|
|
43
|
+
valid: {
|
|
44
|
+
wire: string;
|
|
45
|
+
txid: string;
|
|
46
|
+
txhash: string;
|
|
47
|
+
message: string;
|
|
48
|
+
signature: string;
|
|
49
|
+
feeAtoms: string;
|
|
50
|
+
expectedStage: 'signature';
|
|
51
|
+
stages: ReturnType<typeof finalizePayment>['stages'];
|
|
52
|
+
};
|
|
53
|
+
mutations: {
|
|
54
|
+
name: string;
|
|
55
|
+
wire: string;
|
|
56
|
+
context: {
|
|
57
|
+
chainId: string;
|
|
58
|
+
owner: string;
|
|
59
|
+
coin: JsonOutput;
|
|
60
|
+
coinWire: string;
|
|
61
|
+
outputs: JsonOutput[];
|
|
62
|
+
};
|
|
63
|
+
expectedStage: 'signature';
|
|
64
|
+
expectedReason: string;
|
|
65
|
+
}[];
|
|
66
|
+
};
|
|
67
|
+
export declare function buildPaymentFixture(input: PaymentFixtureInput): PaymentFixture;
|
|
68
|
+
export {};
|