@kaspacom/kcc20-tx-builder 0.7.0 → 0.8.0-fee.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.
@@ -0,0 +1,181 @@
1
+ /** Fee arithmetic for new escrow markets only. Legacy trading is unchanged. */
2
+ export const KCC20_ESCROW_POLICY_VERSION = 1 as const;
3
+ export const KCC20_ESCROW_PROTOCOL_BPS = 100;
4
+ export const KCC20_ESCROW_MAX_CREATOR_BPS = 500;
5
+ export const KCC20_ESCROW_MIN_FEE_SOMPI = 50_000_000n;
6
+ export const KCC20_ESCROW_MAX_CLAIM_RECEIPTS = 5;
7
+ export const KCC20_ESCROW_MAX_INT = 9_223_372_036_854_775_807n;
8
+
9
+ export interface Kcc20EscrowFeeAmounts {
10
+ protocolFeeSompi: bigint;
11
+ creatorFeeSompi: bigint;
12
+ totalFeeSompi: bigint;
13
+ }
14
+
15
+ function amount(value: bigint, name: string): bigint {
16
+ if (typeof value !== "bigint" || value < 0n || value > KCC20_ESCROW_MAX_INT) {
17
+ throw new Error(`${name} must be a nonnegative signed-64-bit bigint`);
18
+ }
19
+ return value;
20
+ }
21
+
22
+ function add(left: bigint, right: bigint): bigint {
23
+ return amount(left + right, "sum");
24
+ }
25
+
26
+ function fee(gross: bigint, bps: number): bigint {
27
+ // Match the contract without overflowing the intermediate multiplication.
28
+ const rate = BigInt(bps);
29
+ const percentage = (gross / 10_000n) * rate + ((gross % 10_000n) * rate) / 10_000n;
30
+ return percentage < KCC20_ESCROW_MIN_FEE_SOMPI ? KCC20_ESCROW_MIN_FEE_SOMPI : percentage;
31
+ }
32
+
33
+ /** A waiver here is a quote assumption, never proof of FeeTicket eligibility. */
34
+ export function calculateKcc20EscrowFees(input: {
35
+ grossSompi: bigint;
36
+ creatorFeeBps: number;
37
+ protocolWaived: boolean;
38
+ }): Kcc20EscrowFeeAmounts {
39
+ const gross = amount(input.grossSompi, "grossSompi");
40
+ if (gross < 50_000_000n) throw new Error("fill gross must be at least 0.5 KAS");
41
+ if (!Number.isInteger(input.creatorFeeBps) || input.creatorFeeBps < 0 || input.creatorFeeBps > KCC20_ESCROW_MAX_CREATOR_BPS) {
42
+ throw new Error("creatorFeeBps must be an integer from 0 to 500");
43
+ }
44
+ if (typeof input.protocolWaived !== "boolean") throw new Error("protocolWaived must be boolean");
45
+ const protocolFeeSompi = input.protocolWaived ? 0n : fee(gross, KCC20_ESCROW_PROTOCOL_BPS);
46
+ const creatorFeeSompi = input.creatorFeeBps === 0 ? 0n : fee(gross, input.creatorFeeBps);
47
+ return { protocolFeeSompi, creatorFeeSompi, totalFeeSompi: add(protocolFeeSompi, creatorFeeSompi) };
48
+ }
49
+
50
+ /** Trading-price components only; excludes network fees and storage deposits.
51
+ * One matched ask/bid is one fill. Call separately for independent fills. */
52
+ export function quoteKcc20EscrowSettlement(input: {
53
+ grossSompi: bigint;
54
+ creatorFeeBps: number;
55
+ protocolWaived: boolean;
56
+ kind: "take-ask" | "fill-bid" | "cross-match";
57
+ }) {
58
+ const fees = calculateKcc20EscrowFees(input);
59
+ if (!["take-ask", "fill-bid", "cross-match"].includes(input.kind)) throw new Error("unsupported settlement kind");
60
+ if (input.kind === "fill-bid" && input.grossSompi < fees.totalFeeSompi) {
61
+ throw new Error("fill gross cannot cover protocol and creator fees");
62
+ }
63
+ return {
64
+ ...fees,
65
+ grossSompi: input.grossSompi,
66
+ buyerPaysSompi: input.kind === "take-ask" ? add(input.grossSompi, fees.totalFeeSompi) : input.grossSompi,
67
+ sellerReceivesSompi: input.kind === "fill-bid" ? input.grossSompi - fees.totalFeeSompi : input.grossSompi,
68
+ matcherPaysSompi: input.kind === "cross-match" ? fees.totalFeeSompi : 0n,
69
+ requiresFeeOutput: fees.totalFeeSompi > 0n,
70
+ };
71
+ }
72
+
73
+ /** Arithmetic for one atomic trade group. Artifact and UTXO checks belong to
74
+ * the signed transaction builder; this quote does not authorize a FeeTicket. */
75
+ export function quoteKcc20EscrowTradeGroup(input: {
76
+ kind: "take-ask" | "fill-bid" | "cross-match";
77
+ fillGrossSompi: readonly bigint[];
78
+ creatorFeeBps: number;
79
+ protocolWaived: boolean;
80
+ }) {
81
+ const maxFills = input.kind === "take-ask" ? 16 : input.kind === "fill-bid" ? 10 : input.kind === "cross-match" ? 1 : 0;
82
+ if (!Array.isArray(input.fillGrossSompi) || input.fillGrossSompi.length < 1 || input.fillGrossSompi.length > maxFills) {
83
+ throw new Error("invalid trade group size");
84
+ }
85
+ if (input.kind === "cross-match" && input.protocolWaived) {
86
+ throw new Error("crossed matches cannot use a FeeTicket");
87
+ }
88
+ const feeVector = input.fillGrossSompi.map(grossSompi =>
89
+ quoteKcc20EscrowSettlement({
90
+ grossSompi, creatorFeeBps: input.creatorFeeBps,
91
+ protocolWaived: input.protocolWaived, kind: input.kind,
92
+ }));
93
+ const totals = feeVector.reduce((sum, fill) => ({
94
+ grossSompi: add(sum.grossSompi, fill.grossSompi),
95
+ protocolFeeSompi: add(sum.protocolFeeSompi, fill.protocolFeeSompi),
96
+ creatorFeeSompi: add(sum.creatorFeeSompi, fill.creatorFeeSompi),
97
+ buyerPaysSompi: add(sum.buyerPaysSompi, fill.buyerPaysSompi),
98
+ sellerReceivesSompi: add(sum.sellerReceivesSompi, fill.sellerReceivesSompi),
99
+ matcherPaysSompi: add(sum.matcherPaysSompi, fill.matcherPaysSompi),
100
+ }), {
101
+ grossSompi: 0n, protocolFeeSompi: 0n, creatorFeeSompi: 0n,
102
+ buyerPaysSompi: 0n, sellerReceivesSompi: 0n, matcherPaysSompi: 0n,
103
+ });
104
+ return {
105
+ ...totals,
106
+ feeVector: feeVector.map(fill => ({
107
+ protocolFeeSompi: fill.protocolFeeSompi,
108
+ creatorFeeSompi: fill.creatorFeeSompi,
109
+ })),
110
+ receiptValueSompi: add(totals.protocolFeeSompi, totals.creatorFeeSompi),
111
+ requiresFeeOutput: totals.protocolFeeSompi + totals.creatorFeeSompi > 0n,
112
+ };
113
+ }
114
+
115
+ /** Accounting description only. The transaction builder must authenticate scripts and live UTXOs. */
116
+ export interface Kcc20FeeReceiptAmounts {
117
+ outpoint: { transactionId: string; index: number };
118
+ tokenId: string;
119
+ marketId: string;
120
+ policyId: string;
121
+ protocolAccountId: string;
122
+ creatorAccountId: string;
123
+ valueSompi: bigint;
124
+ protocolSompi: bigint;
125
+ creatorSompi: bigint;
126
+ }
127
+
128
+ function id(value: string): string {
129
+ if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value)) throw new Error("identity must be 32-byte hex");
130
+ return value.toLowerCase();
131
+ }
132
+
133
+ /** Computes a single claim's conservation amounts, without authorizing a spend. */
134
+ export function calculateKcc20FeeClaim(
135
+ receipts: readonly Kcc20FeeReceiptAmounts[],
136
+ party: "protocol" | "creator",
137
+ ) {
138
+ if (party !== "protocol" && party !== "creator") throw new Error("unknown claiming party");
139
+ if (!Array.isArray(receipts) || receipts.length < 1 || receipts.length > KCC20_ESCROW_MAX_CLAIM_RECEIPTS) {
140
+ throw new Error("claim must select between one and five receipts");
141
+ }
142
+ const seen = new Set<string>();
143
+ let group: string | undefined;
144
+ let protocol = 0n;
145
+ let creator = 0n;
146
+ let consumed = 0n;
147
+ for (const receipt of receipts) {
148
+ const txid = id(receipt.outpoint.transactionId);
149
+ if (!Number.isInteger(receipt.outpoint.index) || receipt.outpoint.index < 0 || receipt.outpoint.index > 0xffffffff) {
150
+ throw new Error("outpoint index must be uint32");
151
+ }
152
+ const outpoint = `${txid}:${receipt.outpoint.index}`;
153
+ if (seen.has(outpoint)) throw new Error("duplicate receipt outpoint");
154
+ seen.add(outpoint);
155
+ const identity = [receipt.tokenId, receipt.marketId, receipt.policyId, receipt.protocolAccountId, receipt.creatorAccountId].map(id).join(":");
156
+ const zero = "0".repeat(64);
157
+ if ([receipt.tokenId, receipt.marketId, receipt.policyId, receipt.protocolAccountId].some(value => id(value) === zero)) {
158
+ throw new Error("token, market, policy and protocol account must be nonzero");
159
+ }
160
+ if (id(receipt.protocolAccountId) === id(receipt.creatorAccountId)) throw new Error("fee accounts must differ");
161
+ if (id(receipt.creatorAccountId) === zero && receipt.creatorSompi !== 0n) throw new Error("disabled creator account cannot hold fees");
162
+ if (group !== undefined && identity !== group) throw new Error("receipts must share token, market, policy and accounts");
163
+ group = identity;
164
+ const p = amount(receipt.protocolSompi, "protocolSompi");
165
+ const c = amount(receipt.creatorSompi, "creatorSompi");
166
+ const value = amount(receipt.valueSompi, "valueSompi");
167
+ if (value === 0n || value !== add(p, c)) throw new Error("receipt value must equal nonzero entitlements");
168
+ if ((p > 0n && p < KCC20_ESCROW_MIN_FEE_SOMPI) || (c > 0n && c < KCC20_ESCROW_MIN_FEE_SOMPI)) {
169
+ throw new Error("nonzero entitlement is below the policy minimum");
170
+ }
171
+ if ((party === "protocol" ? p : c) === 0n) throw new Error("receipt has no entitlement for claimant");
172
+ protocol = add(protocol, p);
173
+ creator = add(creator, c);
174
+ consumed = add(consumed, value);
175
+ }
176
+ const claimSompi = party === "protocol" ? protocol : creator;
177
+ const remainingProtocolSompi = party === "protocol" ? 0n : protocol;
178
+ const remainingCreatorSompi = party === "creator" ? 0n : creator;
179
+ return { claimSompi, remainingProtocolSompi, remainingCreatorSompi, consumedSompi: consumed,
180
+ remainderSompi: add(remainingProtocolSompi, remainingCreatorSompi) };
181
+ }
@@ -0,0 +1,130 @@
1
+ import { blake3 } from "@noble/hashes/blake3";
2
+ import { blake2b } from "@noble/hashes/blake2b";
3
+ import { calculateKcc20FeeClaim, type Kcc20FeeReceiptAmounts } from "./escrow-fee.js";
4
+
5
+ /** Fixed 361-byte policy for the versioned fee roles. Decoding is not artifact authentication. */
6
+ export interface Kcc20EscrowPolicy {
7
+ version: 1;
8
+ creatorFeeBps: number;
9
+ protocolAccountId: string;
10
+ creatorAccountId: string;
11
+ receiptTemplate: { hash: string; prefixLength: number; suffixLength: number };
12
+ rootTemplate: { hash: string; prefixLength: number; suffixLength: number };
13
+ holderTemplate: { hash: string; prefixLength: number; suffixLength: number };
14
+ askTemplate: { hash: string; prefixLength: number; suffixLength: number };
15
+ bidTemplate: { hash: string; prefixLength: number; suffixLength: number };
16
+ ticketTemplate: { hash: string; prefixLength: number; suffixLength: number };
17
+ }
18
+
19
+ const ZERO = "0".repeat(64);
20
+ function hex32(value: string, allowZero = false): Uint8Array {
21
+ if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value) || (!allowZero && value === ZERO)) {
22
+ throw new Error("expected nonzero 32-byte identity");
23
+ }
24
+ return Uint8Array.from(value.match(/../g)!.map(byte => Number.parseInt(byte, 16)));
25
+ }
26
+ function hex(value: Uint8Array): string {
27
+ return Array.from(value, byte => byte.toString(16).padStart(2, "0")).join("");
28
+ }
29
+ function int64(value: bigint): Uint8Array {
30
+ if (typeof value !== "bigint" || value < 0n || value > 0x7fff_ffff_ffff_ffffn) throw new Error("expected nonnegative int64");
31
+ const result = new Uint8Array(8);
32
+ new DataView(result.buffer).setBigUint64(0, value, true);
33
+ return result;
34
+ }
35
+ function concat(...parts: Uint8Array[]): Uint8Array {
36
+ const result = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
37
+ let offset = 0;
38
+ for (const part of parts) { result.set(part, offset); offset += part.length; }
39
+ return result;
40
+ }
41
+ function template(value: Kcc20EscrowPolicy["receiptTemplate"]): Uint8Array {
42
+ for (const length of [value.prefixLength, value.suffixLength]) {
43
+ if (!Number.isSafeInteger(length) || length <= 0) throw new Error("template lengths must be positive safe integers");
44
+ }
45
+ return concat(hex32(value.hash), int64(BigInt(value.prefixLength)), int64(BigInt(value.suffixLength)));
46
+ }
47
+
48
+ export function encodeKcc20EscrowPolicy(policy: Kcc20EscrowPolicy): Uint8Array {
49
+ if (policy.version !== 1) throw new Error("unsupported fee policy version");
50
+ if (!Number.isInteger(policy.creatorFeeBps) || policy.creatorFeeBps < 0 || policy.creatorFeeBps > 500) throw new Error("creator rate must be 0 to 500 bps");
51
+ const protocol = hex32(policy.protocolAccountId);
52
+ const creator = hex32(policy.creatorAccountId, policy.creatorFeeBps === 0);
53
+ if (hex(protocol) === hex(creator)) throw new Error("fee account identities must differ");
54
+ if ((policy.creatorFeeBps === 0) !== (hex(creator) === ZERO)) throw new Error("creator rate and account do not match");
55
+ return concat(Uint8Array.of(1), int64(BigInt(policy.creatorFeeBps)), protocol, creator,
56
+ template(policy.receiptTemplate), template(policy.rootTemplate), template(policy.holderTemplate),
57
+ template(policy.askTemplate), template(policy.bidTemplate), template(policy.ticketTemplate));
58
+ }
59
+
60
+ export function decodeKcc20EscrowPolicy(bytes: Uint8Array): Kcc20EscrowPolicy {
61
+ if (!(bytes instanceof Uint8Array) || bytes.length !== 361 || bytes[0] !== 1) throw new Error("invalid fee policy encoding");
62
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
63
+ const integer = (offset: number): number => {
64
+ const value = view.getBigUint64(offset, true);
65
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("noncanonical or oversized policy integer");
66
+ return Number(value);
67
+ };
68
+ const readTemplate = (offset: number) => ({ hash: hex(bytes.slice(offset, offset + 32)),
69
+ prefixLength: integer(offset + 32), suffixLength: integer(offset + 40) });
70
+ const policy: Kcc20EscrowPolicy = {
71
+ version: 1, creatorFeeBps: integer(1),
72
+ protocolAccountId: hex(bytes.slice(9, 41)), creatorAccountId: hex(bytes.slice(41, 73)),
73
+ receiptTemplate: readTemplate(73), rootTemplate: readTemplate(121),
74
+ holderTemplate: readTemplate(169), askTemplate: readTemplate(217),
75
+ bidTemplate: readTemplate(265), ticketTemplate: readTemplate(313),
76
+ };
77
+ encodeKcc20EscrowPolicy(policy);
78
+ return policy;
79
+ }
80
+
81
+ export function kcc20EscrowPolicyId(input: {
82
+ tokenId: string; feeTicketId: string; priceScale: bigint; policy: Kcc20EscrowPolicy;
83
+ }): string {
84
+ if (typeof input.priceScale !== "bigint" || input.priceScale <= 0n) throw new Error("priceScale must be positive");
85
+ return hex(blake3(concat(hex32(input.tokenId), hex32(input.feeTicketId, true),
86
+ int64(input.priceScale), encodeKcc20EscrowPolicy(input.policy))));
87
+ }
88
+
89
+ /** Public consent can be reused only for this TN10 market and fixed fee policy.
90
+ * Send `message` to the wallet's standard personal-message signing API. A wallet
91
+ * signature is still required; creating this payload does not establish authority.
92
+ */
93
+ export function kcc20CreatorFeeConsent(input: {
94
+ tokenId: string; marketId: string; feeTicketId: string; priceScale: bigint; policy: Kcc20EscrowPolicy;
95
+ }): { commitment: string; message: string; personalMessageHash: string } {
96
+ if (typeof input.priceScale !== "bigint" || input.priceScale <= 0n) throw new Error("priceScale must be positive");
97
+ const policy = encodeKcc20EscrowPolicy(input.policy);
98
+ if (input.policy.creatorFeeBps === 0) throw new Error("creator consent is only used when creator fees are enabled");
99
+ const commitment = hex(blake3(concat(Uint8Array.of(0xc1), hex32(input.tokenId), hex32(input.marketId),
100
+ hex32(input.feeTicketId, true), int64(input.priceScale), policy)));
101
+ const message = `KCC20 creator fee consent v1 (TN10)\n${commitment}`;
102
+ const encoder = new TextEncoder();
103
+ const personalMessageHash = hex(blake2b(encoder.encode(message), {
104
+ dkLen: 32, key: encoder.encode("PersonalMessageSigningHash"),
105
+ }));
106
+ return { commitment, message, personalMessageHash };
107
+ }
108
+
109
+ function outpoint(value: { transactionId: string; index: number }): Uint8Array {
110
+ if (!Number.isInteger(value.index) || value.index < 0 || value.index > 0xffffffff) throw new Error("outpoint index must be uint32");
111
+ return concat(hex32(value.transactionId, true), int64(BigInt(value.index)));
112
+ }
113
+
114
+ /** Input order must match the covenant family's consensus input order. */
115
+ export function kcc20FeeClaimCommitment(input: {
116
+ receipts: readonly Kcc20FeeReceiptAmounts[];
117
+ party: "protocol" | "creator";
118
+ accountOutpoint: { transactionId: string; index: number };
119
+ /** Serialized ScriptPublicKey, including its two-byte little-endian version. */
120
+ payoutScriptPublicKey: Uint8Array;
121
+ }): string {
122
+ const amounts = calculateKcc20FeeClaim(input.receipts, input.party);
123
+ if (!(input.payoutScriptPublicKey instanceof Uint8Array) || input.payoutScriptPublicKey.length < 3) throw new Error("serialized payout ScriptPublicKey is required");
124
+ let receiptHash: Uint8Array = new Uint8Array(32);
125
+ for (const receipt of input.receipts) receiptHash = blake3(concat(receiptHash, outpoint(receipt.outpoint)));
126
+ const first = input.receipts[0];
127
+ return hex(blake3(concat(Uint8Array.of(0xf1), hex32(first.tokenId), hex32(first.marketId), hex32(first.policyId),
128
+ receiptHash, outpoint(input.accountOutpoint), int64(input.party === "creator" ? 1n : 0n),
129
+ int64(amounts.claimSompi), int64(amounts.remainderSompi), blake3(input.payoutScriptPublicKey))));
130
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,8 @@ export * from "./paid-mint-amount.js";
18
18
  export * from "./token-amount.js";
19
19
  export * from "./token-operation.js";
20
20
  export * from "./trade-fee.js";
21
+ export * from "./escrow-fee.js";
22
+ export * from "./escrow-policy.js";
21
23
  export * from "./trading-operation.js";
22
24
  export * from "./protocol.js";
23
25
  export * from "./runtime.js";