@ocap/tx-pipeline 1.30.26 → 1.31.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/esm/appchain-sovereign-hub.d.mts +160 -0
- package/esm/appchain-sovereign-hub.mjs +348 -0
- package/esm/arcvault-external-adapter.d.mts +166 -0
- package/esm/arcvault-external-adapter.mjs +376 -0
- package/esm/encrypted-nft-envelope.d.mts +172 -0
- package/esm/encrypted-nft-envelope.mjs +458 -0
- package/esm/evm-simplified-bridge.d.mts +1370 -0
- package/esm/evm-simplified-bridge.mjs +3875 -0
- package/esm/give-to-mint-karma.d.mts +472 -0
- package/esm/give-to-mint-karma.mjs +1057 -0
- package/esm/helpers/replay-guard.d.mts +15 -0
- package/esm/helpers/replay-guard.mjs +23 -0
- package/esm/index.d.mts +10 -5
- package/esm/index.mjs +14 -10
- package/esm/legacy-protocol-sunset.d.mts +251 -0
- package/esm/legacy-protocol-sunset.mjs +1519 -0
- package/esm/library.d.mts +16 -0
- package/esm/library.mjs +17 -0
- package/esm/native-abt-exchange.d.mts +2055 -0
- package/esm/native-abt-exchange.mjs +7250 -0
- package/esm/ofac-screening.d.mts +17 -0
- package/esm/ofac-screening.mjs +39 -0
- package/esm/pipes/anti-land-attack.mjs +1 -1
- package/esm/pipes/decode-itx.mjs +43 -4
- package/esm/pipes/decode-tx.d.mts +2 -3
- package/esm/pipes/decode-tx.mjs +53 -115
- package/esm/pipes/extract-signer.mjs +2 -2
- package/esm/pipes/extract-state.mjs +14 -3
- package/esm/pipes/post-execution-invariant-gate.d.mts +61 -0
- package/esm/pipes/post-execution-invariant-gate.mjs +789 -0
- package/esm/pipes/pre-flight-waf.d.mts +34 -0
- package/esm/pipes/pre-flight-waf.mjs +603 -0
- package/esm/pipes/take-state-snapshot.mjs +3 -2
- package/esm/pipes/update-owner.mjs +39 -4
- package/esm/pipes/verify-account-migration.mjs +14 -4
- package/esm/pipes/verify-blocked.mjs +1 -1
- package/esm/pipes/verify-delegation.d.mts +22 -3
- package/esm/pipes/verify-delegation.mjs +259 -36
- package/esm/pipes/verify-list-size.mjs +1 -1
- package/esm/pipes/verify-multisig-v2.mjs +15 -7
- package/esm/pipes/verify-multisig.mjs +15 -7
- package/esm/pipes/verify-sender.mjs +1 -1
- package/esm/pipes/verify-signature.mjs +35 -6
- package/esm/pipes/verify-signer.mjs +2 -2
- package/esm/pipes/verify-state-diff.mjs +3 -3
- package/esm/pipes/verify-token-access.mjs +1 -1
- package/esm/pipes/verify-token-balance.mjs +13 -5
- package/esm/pipes/verify-transferrable.d.mts +8 -1
- package/esm/pipes/verify-transferrable.mjs +3 -3
- package/esm/pipes/verify-tx-input.mjs +2 -2
- package/esm/pipes/verify-tx-size.mjs +46 -2
- package/esm/pipes/verify-tx.mjs +5 -7
- package/esm/pipes/verify-updater.mjs +1 -1
- package/esm/social-economy-factories.d.mts +346 -0
- package/esm/social-economy-factories.mjs +845 -0
- package/esm/super-suites-foundation.d.mts +513 -0
- package/esm/super-suites-foundation.mjs +1241 -0
- package/esm/transaction-block.d.mts +471 -0
- package/esm/transaction-block.mjs +1906 -0
- package/esm/uniswap-erc7683-solver.d.mts +201 -0
- package/esm/uniswap-erc7683-solver.mjs +321 -0
- package/esm/uniswap-lp-copilot.d.mts +113 -0
- package/esm/uniswap-lp-copilot.mjs +320 -0
- package/esm/uniswap-router.d.mts +335 -0
- package/esm/uniswap-router.mjs +578 -0
- package/esm/uniswap-token-factory-graduation.d.mts +187 -0
- package/esm/uniswap-token-factory-graduation.mjs +426 -0
- package/esm/uniswap-v4-hook.d.mts +173 -0
- package/esm/uniswap-v4-hook.mjs +517 -0
- package/lib/appchain-sovereign-hub.cjs +352 -0
- package/lib/appchain-sovereign-hub.d.cts +160 -0
- package/lib/arcvault-external-adapter.cjs +383 -0
- package/lib/arcvault-external-adapter.d.cts +166 -0
- package/lib/encrypted-nft-envelope.cjs +477 -0
- package/lib/encrypted-nft-envelope.d.cts +172 -0
- package/lib/evm-simplified-bridge.cjs +3943 -0
- package/lib/evm-simplified-bridge.d.cts +1370 -0
- package/lib/give-to-mint-karma.cjs +1084 -0
- package/lib/give-to-mint-karma.d.cts +472 -0
- package/lib/helpers/replay-guard.cjs +27 -0
- package/lib/helpers/replay-guard.d.cts +15 -0
- package/lib/index.cjs +49 -16
- package/lib/index.d.cts +10 -5
- package/lib/legacy-protocol-sunset.cjs +1543 -0
- package/lib/legacy-protocol-sunset.d.cts +251 -0
- package/lib/library.cjs +303 -0
- package/lib/library.d.cts +16 -0
- package/lib/native-abt-exchange.cjs +7322 -0
- package/lib/native-abt-exchange.d.cts +2055 -0
- package/lib/ofac-screening.cjs +42 -0
- package/lib/ofac-screening.d.cts +17 -0
- package/lib/pipes/anti-land-attack.cjs +2 -2
- package/lib/pipes/decode-itx.cjs +43 -4
- package/lib/pipes/decode-itx.d.cts +1 -1
- package/lib/pipes/decode-tx.cjs +52 -116
- package/lib/pipes/decode-tx.d.cts +3 -4
- package/lib/pipes/extract-signer.cjs +2 -2
- package/lib/pipes/extract-state.cjs +14 -3
- package/lib/pipes/post-execution-invariant-gate.cjs +800 -0
- package/lib/pipes/post-execution-invariant-gate.d.cts +61 -0
- package/lib/pipes/pre-flight-waf.cjs +616 -0
- package/lib/pipes/pre-flight-waf.d.cts +34 -0
- package/lib/pipes/take-state-snapshot.cjs +3 -2
- package/lib/pipes/update-owner.cjs +40 -5
- package/lib/pipes/update-owner.d.cts +1 -1
- package/lib/pipes/verify-account-migration.cjs +14 -4
- package/lib/pipes/verify-blocked.cjs +1 -1
- package/lib/pipes/verify-delegation.cjs +259 -36
- package/lib/pipes/verify-delegation.d.cts +22 -3
- package/lib/pipes/verify-list-size.cjs +1 -1
- package/lib/pipes/verify-multisig-v2.cjs +15 -7
- package/lib/pipes/verify-multisig.cjs +15 -7
- package/lib/pipes/verify-sender.cjs +1 -1
- package/lib/pipes/verify-service-fee.d.cts +1 -1
- package/lib/pipes/verify-signature.cjs +35 -6
- package/lib/pipes/verify-signature.d.cts +1 -1
- package/lib/pipes/verify-signer.cjs +2 -2
- package/lib/pipes/verify-state-diff.cjs +4 -4
- package/lib/pipes/verify-token-access.cjs +2 -2
- package/lib/pipes/verify-token-balance.cjs +13 -5
- package/lib/pipes/verify-transferrable.cjs +3 -3
- package/lib/pipes/verify-transferrable.d.cts +8 -1
- package/lib/pipes/verify-tx-input.cjs +3 -3
- package/lib/pipes/verify-tx-size.cjs +46 -2
- package/lib/pipes/verify-tx-size.d.cts +1 -1
- package/lib/pipes/verify-tx.cjs +6 -8
- package/lib/pipes/verify-tx.d.cts +1 -1
- package/lib/pipes/verify-updater.cjs +1 -1
- package/lib/social-economy-factories.cjs +852 -0
- package/lib/social-economy-factories.d.cts +346 -0
- package/lib/super-suites-foundation.cjs +1257 -0
- package/lib/super-suites-foundation.d.cts +513 -0
- package/lib/transaction-block.cjs +1941 -0
- package/lib/transaction-block.d.cts +471 -0
- package/lib/uniswap-erc7683-solver.cjs +327 -0
- package/lib/uniswap-erc7683-solver.d.cts +201 -0
- package/lib/uniswap-lp-copilot.cjs +328 -0
- package/lib/uniswap-lp-copilot.d.cts +113 -0
- package/lib/uniswap-router.cjs +593 -0
- package/lib/uniswap-router.d.cts +335 -0
- package/lib/uniswap-token-factory-graduation.cjs +431 -0
- package/lib/uniswap-token-factory-graduation.d.cts +187 -0
- package/lib/uniswap-v4-hook.cjs +527 -0
- package/lib/uniswap-v4-hook.d.cts +173 -0
- package/package.json +11 -10
- package/esm/helpers/dedup-height.d.mts +0 -16
- package/esm/helpers/dedup-height.mjs +0 -61
- package/lib/helpers/dedup-height.cjs +0 -72
- package/lib/helpers/dedup-height.d.cts +0 -16
|
@@ -0,0 +1,1057 @@
|
|
|
1
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
//#region src/give-to-mint-karma.ts
|
|
5
|
+
const ErrorCode = {
|
|
6
|
+
InvalidTx: "INVALID_GIVE_TO_MINT",
|
|
7
|
+
Forbidden: "FORBIDDEN_GIVE_TO_MINT"
|
|
8
|
+
};
|
|
9
|
+
const GIVE_TO_MINT_TOKEN_TYPE = "give_to_mint";
|
|
10
|
+
const DEFAULT_KARMA_TOKEN_ADDRESS = "did:abt:token:karma";
|
|
11
|
+
const DEFAULT_EPOCH_KARMA_ALLOWANCE = 100n;
|
|
12
|
+
const MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE = 100n;
|
|
13
|
+
const DEFAULT_MAX_HISTORICAL_KARMA_CLAIM = 500n;
|
|
14
|
+
const MAX_HISTORICAL_KARMA_PER_VERIFIED_ITEM = 10n;
|
|
15
|
+
const MAX_CUSTOM_TOKEN_EPOCH_ALLOWANCE = 10000n;
|
|
16
|
+
const MAX_CUSTOM_TOKEN_HISTORICAL_CLAIM_CAP = 50000n;
|
|
17
|
+
const HISTORICAL_CLAIM_TRUST_BOOST_BPS = 15e3;
|
|
18
|
+
const MAX_UPSTREAM_CITATIONS = 10;
|
|
19
|
+
const MAX_TOTAL_CITATION_SHARE_BPS = 8e3;
|
|
20
|
+
const BPS_DENOMINATOR = 10000n;
|
|
21
|
+
const DEFAULT_SPONSORED_BADGE_MINT_QUOTA = 100;
|
|
22
|
+
const MAX_SPONSORED_BADGE_MINT_QUOTA_PER_GRANT = 1e3;
|
|
23
|
+
const MAX_ACTIVE_SPONSORED_BADGE_MINT_QUOTA = 1e4;
|
|
24
|
+
const MAX_EPOCH_FORWARD_DRIFT = 365;
|
|
25
|
+
const RECIPROCAL_RING_DAMPING_BPS = 1000n;
|
|
26
|
+
const MIN_KARMA_FOR_THANK_YOU_BADGE = 10n;
|
|
27
|
+
const MIN_GIVE_TO_MINT_DUST_FLOOR = 5n;
|
|
28
|
+
const MAX_CHECKPOINT_VOUCHERS_PER_BATCH = 500;
|
|
29
|
+
const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
|
|
30
|
+
const TOKEN_SYMBOL_REGEX = /^[A-Z0-9_]{2,16}$/;
|
|
31
|
+
const VALID_ARTIFACT_KINDS = new Set([
|
|
32
|
+
"article",
|
|
33
|
+
"video",
|
|
34
|
+
"photo",
|
|
35
|
+
"music",
|
|
36
|
+
"skill",
|
|
37
|
+
"blocklet",
|
|
38
|
+
"nft",
|
|
39
|
+
"comment"
|
|
40
|
+
]);
|
|
41
|
+
const VALID_POOL_KINDS = new Set([
|
|
42
|
+
"PERSONAL_BAT_TIPPING_POOL",
|
|
43
|
+
"CRYPTO_ADSENSE_SPONSOR_POOL",
|
|
44
|
+
"PHILANTHROPY_TAX_DONATION_POOL"
|
|
45
|
+
]);
|
|
46
|
+
const VALID_HISTORICAL_PLATFORMS = new Set([
|
|
47
|
+
"twitter_x",
|
|
48
|
+
"blog_rss",
|
|
49
|
+
"substack_mirror",
|
|
50
|
+
"github",
|
|
51
|
+
"youtube_podcast",
|
|
52
|
+
"arc_archive"
|
|
53
|
+
]);
|
|
54
|
+
const VALID_MEDAL_KINDS = new Set([
|
|
55
|
+
"GREAT_WORK",
|
|
56
|
+
"BRILLIANT",
|
|
57
|
+
"MIND_BLOWN",
|
|
58
|
+
"DEEP_INSIGHT"
|
|
59
|
+
]);
|
|
60
|
+
const VALID_NFT_PAYLOAD_VISIBILITIES = new Set([
|
|
61
|
+
"public",
|
|
62
|
+
"authorized_only",
|
|
63
|
+
"private"
|
|
64
|
+
]);
|
|
65
|
+
function assertNonEmptyIdentifier(value, label) {
|
|
66
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: ${label} must be a non-empty string`);
|
|
67
|
+
const trimmed = value.trim();
|
|
68
|
+
if (trimmed !== value || /[\s/\\?#%]|::|->/.test(trimmed)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: ${label} contains invalid characters`);
|
|
69
|
+
return trimmed;
|
|
70
|
+
}
|
|
71
|
+
function assertValidEpochIndex(epochIndex) {
|
|
72
|
+
if (!Number.isSafeInteger(epochIndex) || epochIndex < 0) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: epochIndex must be a non-negative safe integer");
|
|
73
|
+
}
|
|
74
|
+
function deriveThankYouBadgeDid(creatorDid, recipientDid, epochIndex, serialNumber) {
|
|
75
|
+
return `did:abt:badge:${createHash("sha256").update(`ocap:thank-you-badge:v1:${creatorDid}:${recipientDid}:${epochIndex}:${serialNumber}`).digest("hex").slice(0, 40)}`;
|
|
76
|
+
}
|
|
77
|
+
function deriveCompanionMedalDid(txHash, senderDid, objectDid, medalKind) {
|
|
78
|
+
return `did:abt:medal:${createHash("sha256").update(`ocap:companion-medal:v1:${txHash}:${senderDid}:${objectDid}:${medalKind}`).digest("hex").slice(0, 40)}`;
|
|
79
|
+
}
|
|
80
|
+
function computeNftPayloadCommitmentDigest(nftDid, holderDid, issuerDid, epochIndex) {
|
|
81
|
+
return `0x${createHash("sha256").update(`ocap:nft-holder-arcspace-payload:v1:${nftDid}:${holderDid}:${issuerDid}:${epochIndex}`).digest("hex")}`;
|
|
82
|
+
}
|
|
83
|
+
function computeArcSpaceVoucherDigest(tokenAddress, epochIndex, voucher) {
|
|
84
|
+
const normalizedToken = assertNonEmptyIdentifier(tokenAddress, "tokenAddress");
|
|
85
|
+
assertValidEpochIndex(epochIndex);
|
|
86
|
+
const voucherId = assertNonEmptyIdentifier(voucher.voucherId, "voucherId");
|
|
87
|
+
const senderDid = assertNonEmptyIdentifier(voucher.senderDid, "senderDid");
|
|
88
|
+
const objectDid = assertNonEmptyIdentifier(voucher.objectDid, "objectDid");
|
|
89
|
+
if (typeof voucher.allowanceAmount !== "bigint" || voucher.allowanceAmount < MIN_GIVE_TO_MINT_DUST_FLOOR) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: voucher ${voucherId} allowanceAmount (${voucher.allowanceAmount}) is below anti-dust floor (${MIN_GIVE_TO_MINT_DUST_FLOOR})`);
|
|
90
|
+
if (voucher.medalKind !== void 0 && !VALID_MEDAL_KINDS.has(voucher.medalKind)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid medalKind ${String(voucher.medalKind)}`);
|
|
91
|
+
const visibilityTag = voucher.initialNftPayloadVisibility ?? "public";
|
|
92
|
+
if (!VALID_NFT_PAYLOAD_VISIBILITIES.has(visibilityTag)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid initialNftPayloadVisibility ${String(visibilityTag)}`);
|
|
93
|
+
const medalTag = voucher.medalKind ?? "NONE";
|
|
94
|
+
return `0x${createHash("sha256").update(`ocap:arcspace-karma-voucher:v1:${normalizedToken}:${epochIndex}:${voucherId}:${senderDid}:${objectDid}:${voucher.allowanceAmount.toString()}:${medalTag}:${visibilityTag}`).digest("hex")}`;
|
|
95
|
+
}
|
|
96
|
+
function computeArcSpaceCheckpointRoot(tokenAddress, epochIndex, vouchers) {
|
|
97
|
+
const normalizedToken = assertNonEmptyIdentifier(tokenAddress, "tokenAddress");
|
|
98
|
+
assertValidEpochIndex(epochIndex);
|
|
99
|
+
if (!Array.isArray(vouchers) || vouchers.length === 0 || vouchers.length > MAX_CHECKPOINT_VOUCHERS_PER_BATCH) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: checkpoint vouchers must contain 1..${MAX_CHECKPOINT_VOUCHERS_PER_BATCH} items`);
|
|
100
|
+
const seenVoucherIds = /* @__PURE__ */ new Set();
|
|
101
|
+
const leafDigests = [];
|
|
102
|
+
for (const v of vouchers) {
|
|
103
|
+
const vid = assertNonEmptyIdentifier(v.voucherId, "voucherId");
|
|
104
|
+
if (seenVoucherIds.has(vid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate voucherId ${vid} in checkpoint batch`);
|
|
105
|
+
seenVoucherIds.add(vid);
|
|
106
|
+
leafDigests.push(computeArcSpaceVoucherDigest(normalizedToken, epochIndex, v));
|
|
107
|
+
}
|
|
108
|
+
return `0x${createHash("sha256").update(`ocap:arcspace-checkpoint-root:v1:${normalizedToken}:${epochIndex}:${leafDigests.join(",")}`).digest("hex")}`;
|
|
109
|
+
}
|
|
110
|
+
function computeHistoricalClaimNullifier(tokenAddress, sourcePlatform, externalAccountId) {
|
|
111
|
+
const normalizedToken = assertNonEmptyIdentifier(tokenAddress, "tokenAddress");
|
|
112
|
+
if (!VALID_HISTORICAL_PLATFORMS.has(sourcePlatform)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid sourcePlatform ${String(sourcePlatform)}`);
|
|
113
|
+
const normalizedExternal = assertNonEmptyIdentifier(externalAccountId, "externalAccountId").toLowerCase();
|
|
114
|
+
return `0x${createHash("sha256").update(`ocap:historical-karma-nullifier:v1:${normalizedToken}:${sourcePlatform}:${normalizedExternal}`).digest("hex")}`;
|
|
115
|
+
}
|
|
116
|
+
var OcapGiveToMintEngine = class {
|
|
117
|
+
constructor(options) {
|
|
118
|
+
this.currentEpoch = 0;
|
|
119
|
+
this.totalCreationFeesCollected = 0n;
|
|
120
|
+
this.tokens = /* @__PURE__ */ new Map();
|
|
121
|
+
this.tokenSymbols = /* @__PURE__ */ new Set();
|
|
122
|
+
this.profiles = /* @__PURE__ */ new Map();
|
|
123
|
+
this.tokenAccounts = /* @__PURE__ */ new Map();
|
|
124
|
+
this.objects = /* @__PURE__ */ new Map();
|
|
125
|
+
this.pairwiseEpochCounts = /* @__PURE__ */ new Map();
|
|
126
|
+
this.epochDirectedEdges = /* @__PURE__ */ new Map();
|
|
127
|
+
this.supporterStreaks = /* @__PURE__ */ new Map();
|
|
128
|
+
this.thankYouBadges = /* @__PURE__ */ new Map();
|
|
129
|
+
this.companionMedals = /* @__PURE__ */ new Map();
|
|
130
|
+
this.processedTxHashes = /* @__PURE__ */ new Set();
|
|
131
|
+
this.consumedHistoricalNullifiers = /* @__PURE__ */ new Set();
|
|
132
|
+
this.consumedArchiveProofDigests = /* @__PURE__ */ new Set();
|
|
133
|
+
this.processedClaimIds = /* @__PURE__ */ new Set();
|
|
134
|
+
this.processedCheckpointIds = /* @__PURE__ */ new Set();
|
|
135
|
+
this.archivedEpochCheckpoints = [];
|
|
136
|
+
this.stakeLocks = /* @__PURE__ */ new Map();
|
|
137
|
+
this.settledPools = /* @__PURE__ */ new Set();
|
|
138
|
+
const base = options?.epochBaseAllowance ?? DEFAULT_EPOCH_KARMA_ALLOWANCE;
|
|
139
|
+
if (typeof base !== "bigint" || base <= 0n) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: epochBaseAllowance must be a positive bigint");
|
|
140
|
+
const maxDrift = options?.maxEpochForwardDrift ?? MAX_EPOCH_FORWARD_DRIFT;
|
|
141
|
+
if (!Number.isSafeInteger(maxDrift) || maxDrift <= 0) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: maxEpochForwardDrift must be a positive safe integer");
|
|
142
|
+
this.defaultEpochBaseAllowance = base;
|
|
143
|
+
this.maxEpochForwardDrift = maxDrift;
|
|
144
|
+
this.tokens.set(DEFAULT_KARMA_TOKEN_ADDRESS, {
|
|
145
|
+
tokenAddress: DEFAULT_KARMA_TOKEN_ADDRESS,
|
|
146
|
+
symbol: "KARMA",
|
|
147
|
+
name: "OCAP Network Karma",
|
|
148
|
+
issuerDid: "did:abt:arcblock-governance",
|
|
149
|
+
type: GIVE_TO_MINT_TOKEN_TYPE,
|
|
150
|
+
epochBaseAllowance: base,
|
|
151
|
+
maxHistoricalClaimPerDid: DEFAULT_MAX_HISTORICAL_KARMA_CLAIM,
|
|
152
|
+
transferrable: false,
|
|
153
|
+
creationFeePaid: MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE,
|
|
154
|
+
createdAtEpoch: 0
|
|
155
|
+
});
|
|
156
|
+
this.tokenSymbols.add("KARMA");
|
|
157
|
+
}
|
|
158
|
+
assertEpochWithinHorizon(epochIndex) {
|
|
159
|
+
assertValidEpochIndex(epochIndex);
|
|
160
|
+
if (epochIndex < this.currentEpoch) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: global epoch rollback detected (${epochIndex} < ${this.currentEpoch})`);
|
|
161
|
+
if (epochIndex > this.currentEpoch + this.maxEpochForwardDrift) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: epochIndex (${epochIndex}) exceeds max forward drift (${this.currentEpoch} + ${this.maxEpochForwardDrift})`);
|
|
162
|
+
}
|
|
163
|
+
resolveTokenConfig(tokenAddress) {
|
|
164
|
+
const addr = tokenAddress ? assertNonEmptyIdentifier(tokenAddress, "tokenAddress") : DEFAULT_KARMA_TOKEN_ADDRESS;
|
|
165
|
+
const config = this.tokens.get(addr);
|
|
166
|
+
if (!config) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: token ${addr} is not registered`);
|
|
167
|
+
return config;
|
|
168
|
+
}
|
|
169
|
+
getOrInitTokenAccount(did, tokenAddress) {
|
|
170
|
+
const profile = this.profiles.get(did);
|
|
171
|
+
if (!profile) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: identity ${did} not found`);
|
|
172
|
+
const key = `${tokenAddress}::${did}`;
|
|
173
|
+
let acct = this.tokenAccounts.get(key);
|
|
174
|
+
if (!acct) {
|
|
175
|
+
acct = {
|
|
176
|
+
did,
|
|
177
|
+
tokenAddress,
|
|
178
|
+
earnedKarma: 0n,
|
|
179
|
+
earnedKarmaInEpoch: 0n,
|
|
180
|
+
lastEarnedEpoch: profile.initialEpoch,
|
|
181
|
+
stakedKarma: 0n,
|
|
182
|
+
slashedKarma: 0n,
|
|
183
|
+
claimedHistoricalKarma: 0n,
|
|
184
|
+
lastAllowanceEpoch: profile.initialEpoch,
|
|
185
|
+
usedAllowanceInEpoch: 0n
|
|
186
|
+
};
|
|
187
|
+
this.tokenAccounts.set(key, acct);
|
|
188
|
+
}
|
|
189
|
+
return acct;
|
|
190
|
+
}
|
|
191
|
+
creditEarnedKarma(acct, amount, epochIndex) {
|
|
192
|
+
if (epochIndex > acct.lastEarnedEpoch) {
|
|
193
|
+
acct.earnedKarmaInEpoch = 0n;
|
|
194
|
+
acct.lastEarnedEpoch = epochIndex;
|
|
195
|
+
}
|
|
196
|
+
acct.earnedKarma += amount;
|
|
197
|
+
acct.earnedKarmaInEpoch += amount;
|
|
198
|
+
}
|
|
199
|
+
getDirectedTargets(tokenAddress, epoch, fromDid) {
|
|
200
|
+
if (epoch < 0) return /* @__PURE__ */ new Set();
|
|
201
|
+
return this.epochDirectedEdges.get(`${tokenAddress}::${epoch}::${fromDid}`) ?? /* @__PURE__ */ new Set();
|
|
202
|
+
}
|
|
203
|
+
hasDirectedEdge(tokenAddress, epoch, fromDid, toDid) {
|
|
204
|
+
if (epoch < 0) return false;
|
|
205
|
+
return this.epochDirectedEdges.get(`${tokenAddress}::${epoch}::${fromDid}`)?.has(toDid) ?? false;
|
|
206
|
+
}
|
|
207
|
+
hasReciprocalOrTrianglePath(tokenAddress, epoch, senderDid, recipientDid) {
|
|
208
|
+
if (this.hasDirectedEdge(tokenAddress, epoch, recipientDid, senderDid) || this.hasDirectedEdge(tokenAddress, epoch - 1, recipientDid, senderDid)) return true;
|
|
209
|
+
const nextHops = new Set([...this.getDirectedTargets(tokenAddress, epoch, recipientDid), ...this.getDirectedTargets(tokenAddress, epoch - 1, recipientDid)]);
|
|
210
|
+
for (const midDid of nextHops) if (midDid !== senderDid && (this.hasDirectedEdge(tokenAddress, epoch, midDid, senderDid) || this.hasDirectedEdge(tokenAddress, epoch - 1, midDid, senderDid))) return true;
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Issue #1229: Allows any organization/community to issue its own `type = "give_to_mint"` Karma token
|
|
215
|
+
* on-chain with custom epoch allowance & historical claim cap, provided it pays at least
|
|
216
|
+
* `MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE` to prevent garbage token spam and keeps `transferrable: false`.
|
|
217
|
+
*/
|
|
218
|
+
createGiveToMintToken(input) {
|
|
219
|
+
const tokenAddress = assertNonEmptyIdentifier(input.tokenAddress, "tokenAddress");
|
|
220
|
+
const symbol = assertNonEmptyIdentifier(input.symbol, "symbol").toUpperCase();
|
|
221
|
+
const issuerDid = assertNonEmptyIdentifier(input.issuerDid, "issuerDid");
|
|
222
|
+
if (!TOKEN_SYMBOL_REGEX.test(symbol)) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: token symbol must be 2..16 uppercase alphanumeric/underscore characters");
|
|
223
|
+
if (this.tokenSymbols.has(symbol)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: token symbol ${symbol} is already reserved`);
|
|
224
|
+
if (typeof input.name !== "string" || input.name.trim().length === 0 || input.name.trim().length > 64) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: token name must be 1..64 characters");
|
|
225
|
+
if (input.transferrable === true) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: give_to_mint KARMA tokens must be strictly non-transferable (transferrable: false)");
|
|
226
|
+
const epochIndex = input.epochIndex ?? this.currentEpoch;
|
|
227
|
+
this.assertEpochWithinHorizon(epochIndex);
|
|
228
|
+
if (this.tokens.has(tokenAddress)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: token ${tokenAddress} already exists`);
|
|
229
|
+
const issuerProfile = this.profiles.get(issuerDid);
|
|
230
|
+
if (!issuerProfile || !issuerProfile.verifiedHumanOrStaker || issuerProfile.trustMultiplierBps <= 0) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: only verified identities/organizations can issue a give_to_mint token");
|
|
231
|
+
if (typeof input.creationFeePaid !== "bigint" || input.creationFeePaid < MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: creationFeePaid (${input.creationFeePaid}) is below minimum required fee (${MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE}) to prevent spam tokens`);
|
|
232
|
+
const epochBaseAllowance = input.epochBaseAllowance ?? DEFAULT_EPOCH_KARMA_ALLOWANCE;
|
|
233
|
+
if (typeof epochBaseAllowance !== "bigint" || epochBaseAllowance <= 0n || epochBaseAllowance > MAX_CUSTOM_TOKEN_EPOCH_ALLOWANCE) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: epochBaseAllowance must be between 1 and ${MAX_CUSTOM_TOKEN_EPOCH_ALLOWANCE}`);
|
|
234
|
+
const maxHistoricalClaimPerDid = input.maxHistoricalClaimPerDid ?? DEFAULT_MAX_HISTORICAL_KARMA_CLAIM;
|
|
235
|
+
if (typeof maxHistoricalClaimPerDid !== "bigint" || maxHistoricalClaimPerDid < 0n || maxHistoricalClaimPerDid > MAX_CUSTOM_TOKEN_HISTORICAL_CLAIM_CAP) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: maxHistoricalClaimPerDid must be between 0 and ${MAX_CUSTOM_TOKEN_HISTORICAL_CLAIM_CAP}`);
|
|
236
|
+
this.currentEpoch = epochIndex;
|
|
237
|
+
this.totalCreationFeesCollected += input.creationFeePaid;
|
|
238
|
+
const config = {
|
|
239
|
+
tokenAddress,
|
|
240
|
+
symbol,
|
|
241
|
+
name: input.name.trim(),
|
|
242
|
+
issuerDid,
|
|
243
|
+
type: GIVE_TO_MINT_TOKEN_TYPE,
|
|
244
|
+
epochBaseAllowance,
|
|
245
|
+
maxHistoricalClaimPerDid,
|
|
246
|
+
transferrable: false,
|
|
247
|
+
creationFeePaid: input.creationFeePaid,
|
|
248
|
+
createdAtEpoch: epochIndex
|
|
249
|
+
};
|
|
250
|
+
this.tokens.set(tokenAddress, config);
|
|
251
|
+
this.tokenSymbols.add(symbol);
|
|
252
|
+
return { ...config };
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Explicitly blocks peer-to-peer transfers of any `give_to_mint` KARMA FT (`transferrable: false`).
|
|
256
|
+
*/
|
|
257
|
+
assertTransferForbidden(tokenAddress) {
|
|
258
|
+
const config = this.resolveTokenConfig(tokenAddress);
|
|
259
|
+
throw new CustomError(ErrorCode.Forbidden, `GiveToMint: token ${config.symbol} (${config.tokenAddress}) is a non-transferable give_to_mint reputation token`);
|
|
260
|
+
}
|
|
261
|
+
getTokenConfig(tokenAddress) {
|
|
262
|
+
const config = this.tokens.get(tokenAddress);
|
|
263
|
+
return config ? { ...config } : void 0;
|
|
264
|
+
}
|
|
265
|
+
getTotalCreationFeesCollected() {
|
|
266
|
+
return this.totalCreationFeesCollected;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Registers or updates a DID identity in the KARMA ledger.
|
|
270
|
+
*/
|
|
271
|
+
registerIdentity(params) {
|
|
272
|
+
const did = assertNonEmptyIdentifier(params.did, "did");
|
|
273
|
+
const initialEpoch = params.initialEpoch ?? this.currentEpoch;
|
|
274
|
+
this.assertEpochWithinHorizon(initialEpoch);
|
|
275
|
+
const trustMultiplierBps = params.trustMultiplierBps ?? (params.verifiedHumanOrStaker ? 1e4 : 0);
|
|
276
|
+
if (!Number.isSafeInteger(trustMultiplierBps) || trustMultiplierBps < 0 || trustMultiplierBps > 3e4) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: trustMultiplierBps must be an integer between 0 and 30000 (0.0x - 3.0x)");
|
|
277
|
+
if (!params.verifiedHumanOrStaker && trustMultiplierBps > 0) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: unverified accounts cannot have a positive trustMultiplierBps");
|
|
278
|
+
this.currentEpoch = initialEpoch;
|
|
279
|
+
const existing = this.profiles.get(did);
|
|
280
|
+
if (existing) {
|
|
281
|
+
existing.verifiedHumanOrStaker = Boolean(params.verifiedHumanOrStaker);
|
|
282
|
+
existing.trustMultiplierBps = trustMultiplierBps;
|
|
283
|
+
if (!existing.verifiedHumanOrStaker) existing.sponsoredBadgeMintQuota = 0;
|
|
284
|
+
return this.getIdentityState(did);
|
|
285
|
+
}
|
|
286
|
+
const profile = {
|
|
287
|
+
did,
|
|
288
|
+
verifiedHumanOrStaker: Boolean(params.verifiedHumanOrStaker),
|
|
289
|
+
trustMultiplierBps,
|
|
290
|
+
initialEpoch,
|
|
291
|
+
sponsoredBadgeMintQuota: 0,
|
|
292
|
+
totalThankYouBadgesIssued: 0
|
|
293
|
+
};
|
|
294
|
+
this.profiles.set(did, profile);
|
|
295
|
+
this.getOrInitTokenAccount(did, DEFAULT_KARMA_TOKEN_ADDRESS);
|
|
296
|
+
return this.getIdentityState(did);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Issue #1229: Retroactive Historical Karma Claim (for past Tweets, Articles, Blogs, GitHub repos imported into ARC).
|
|
300
|
+
* - Enforces unique Nullifier per `(tokenAddress, sourcePlatform, externalAccountId)` and unique `archiveProofDigest`
|
|
301
|
+
* so a Twitter account or blog archive cannot be unbound and re-claimed by another DID.
|
|
302
|
+
* - Enforces per-item cap (`MAX_HISTORICAL_KARMA_PER_VERIFIED_ITEM`) and per-`(did, tokenAddress)` cap.
|
|
303
|
+
* - Boosts the creator's `trustMultiplierBps` (to 1.5x) when verified on the flagship `DEFAULT_KARMA_TOKEN_ADDRESS`.
|
|
304
|
+
*/
|
|
305
|
+
claimHistoricalKarma(input) {
|
|
306
|
+
const claimId = assertNonEmptyIdentifier(input.claimId, "claimId");
|
|
307
|
+
const claimantDid = assertNonEmptyIdentifier(input.claimantDid, "claimantDid");
|
|
308
|
+
const tokenConfig = this.resolveTokenConfig(input.tokenAddress);
|
|
309
|
+
this.assertEpochWithinHorizon(input.epochIndex);
|
|
310
|
+
if (this.processedClaimIds.has(claimId)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate historical claimId ${claimId}`);
|
|
311
|
+
if (!Number.isSafeInteger(input.verifiedItemCount) || input.verifiedItemCount <= 0) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: verifiedItemCount must be a positive integer");
|
|
312
|
+
if (typeof input.archiveProofDigest !== "string" || !BYTES32_HEX_REGEX.test(input.archiveProofDigest)) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: archiveProofDigest must be a canonical 32-byte 0x-prefixed hex digest");
|
|
313
|
+
if (typeof input.requestedKarmaAmount !== "bigint" || input.requestedKarmaAmount <= 0n) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: requestedKarmaAmount must be a positive bigint");
|
|
314
|
+
const maxAllowedForItems = BigInt(input.verifiedItemCount) * MAX_HISTORICAL_KARMA_PER_VERIFIED_ITEM;
|
|
315
|
+
if (input.requestedKarmaAmount > maxAllowedForItems) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: requestedKarmaAmount (${input.requestedKarmaAmount}) exceeds per-item cap (${maxAllowedForItems} for ${input.verifiedItemCount} verified items)`);
|
|
316
|
+
const profile = this.profiles.get(claimantDid);
|
|
317
|
+
if (!profile) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: claimant ${claimantDid} is not registered`);
|
|
318
|
+
if (!profile.verifiedHumanOrStaker || profile.trustMultiplierBps <= 0) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: unverified or zero-trust Sybil accounts cannot claim historical KARMA");
|
|
319
|
+
const normalizedProofKey = `${tokenConfig.tokenAddress}:${input.archiveProofDigest.toLowerCase()}`;
|
|
320
|
+
if (this.consumedArchiveProofDigests.has(normalizedProofKey)) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: archiveProofDigest ${input.archiveProofDigest} has already been consumed for token ${tokenConfig.tokenAddress}`);
|
|
321
|
+
const nullifierHash = computeHistoricalClaimNullifier(tokenConfig.tokenAddress, input.sourcePlatform, input.externalAccountId);
|
|
322
|
+
if (this.consumedHistoricalNullifiers.has(nullifierHash)) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: historical source (${input.sourcePlatform}:${input.externalAccountId}) has already been claimed for token ${tokenConfig.tokenAddress}`);
|
|
323
|
+
const acct = this.getOrInitTokenAccount(claimantDid, tokenConfig.tokenAddress);
|
|
324
|
+
if (acct.claimedHistoricalKarma + input.requestedKarmaAmount > tokenConfig.maxHistoricalClaimPerDid) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: historical claim (${acct.claimedHistoricalKarma + input.requestedKarmaAmount}) exceeds token maxHistoricalClaimPerDid (${tokenConfig.maxHistoricalClaimPerDid})`);
|
|
325
|
+
this.currentEpoch = input.epochIndex;
|
|
326
|
+
this.processedClaimIds.add(claimId);
|
|
327
|
+
this.consumedArchiveProofDigests.add(normalizedProofKey);
|
|
328
|
+
this.consumedHistoricalNullifiers.add(nullifierHash);
|
|
329
|
+
acct.claimedHistoricalKarma += input.requestedKarmaAmount;
|
|
330
|
+
this.creditEarnedKarma(acct, input.requestedKarmaAmount, input.epochIndex);
|
|
331
|
+
if (tokenConfig.tokenAddress === DEFAULT_KARMA_TOKEN_ADDRESS && acct.claimedHistoricalKarma >= 100n) profile.trustMultiplierBps = Math.max(profile.trustMultiplierBps, HISTORICAL_CLAIM_TRUST_BOOST_BPS);
|
|
332
|
+
return {
|
|
333
|
+
claimId,
|
|
334
|
+
claimantDid,
|
|
335
|
+
tokenAddress: tokenConfig.tokenAddress,
|
|
336
|
+
sourcePlatform: input.sourcePlatform,
|
|
337
|
+
nullifierHash,
|
|
338
|
+
verifiedItemCount: input.verifiedItemCount,
|
|
339
|
+
mintedHistoricalKarma: input.requestedKarmaAmount,
|
|
340
|
+
totalClaimedHistoricalKarma: acct.claimedHistoricalKarma,
|
|
341
|
+
updatedTrustMultiplierBps: profile.trustMultiplierBps
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Anti-Sybil Creator Grant: allocates non-transferable badge minting quota (e.g., 100 fan badges)
|
|
346
|
+
* instead of liquid ABT so airdrop farmers cannot dump tokens.
|
|
347
|
+
*/
|
|
348
|
+
grantSponsoredBadgeMintQuota(creatorDid, quotaToAdd = DEFAULT_SPONSORED_BADGE_MINT_QUOTA) {
|
|
349
|
+
const normalizedCreator = assertNonEmptyIdentifier(creatorDid, "creatorDid");
|
|
350
|
+
if (!Number.isSafeInteger(quotaToAdd) || quotaToAdd <= 0 || quotaToAdd > MAX_SPONSORED_BADGE_MINT_QUOTA_PER_GRANT) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: quotaToAdd must be between 1 and ${MAX_SPONSORED_BADGE_MINT_QUOTA_PER_GRANT}`);
|
|
351
|
+
const creator = this.profiles.get(normalizedCreator);
|
|
352
|
+
if (!creator || !creator.verifiedHumanOrStaker || creator.trustMultiplierBps <= 0) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: only verified creators can receive sponsored badge minting quota");
|
|
353
|
+
if (creator.sponsoredBadgeMintQuota + quotaToAdd > MAX_ACTIVE_SPONSORED_BADGE_MINT_QUOTA) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: creator sponsoredBadgeMintQuota cannot exceed ${MAX_ACTIVE_SPONSORED_BADGE_MINT_QUOTA}`);
|
|
354
|
+
creator.sponsoredBadgeMintQuota += quotaToAdd;
|
|
355
|
+
return creator.sponsoredBadgeMintQuota;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Registers a creation object (article, video, photo, music, AI skill, blocklet, NFT, comment)
|
|
359
|
+
* along with its upstream Karma citation graph.
|
|
360
|
+
*/
|
|
361
|
+
registerCreationObject(input) {
|
|
362
|
+
const objectDid = assertNonEmptyIdentifier(input.objectDid, "objectDid");
|
|
363
|
+
const authorDid = assertNonEmptyIdentifier(input.authorDid, "authorDid");
|
|
364
|
+
if (!VALID_ARTIFACT_KINDS.has(input.kind)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid object kind ${String(input.kind)}`);
|
|
365
|
+
if (this.objects.has(objectDid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: object ${objectDid} is already registered`);
|
|
366
|
+
if (!this.profiles.has(authorDid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: author ${authorDid} is not registered`);
|
|
367
|
+
const citations = input.citations ?? [];
|
|
368
|
+
if (!Array.isArray(citations) || citations.length > MAX_UPSTREAM_CITATIONS) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: citations must be an array with at most ${MAX_UPSTREAM_CITATIONS} upstream entries`);
|
|
369
|
+
let totalShareBps = 0;
|
|
370
|
+
const seenCitedArtifacts = /* @__PURE__ */ new Set();
|
|
371
|
+
const seenContributors = /* @__PURE__ */ new Set();
|
|
372
|
+
const normalizedCitations = [];
|
|
373
|
+
for (const c of citations) {
|
|
374
|
+
if (!VALID_ARTIFACT_KINDS.has(c.artifactKind)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid citation artifactKind ${String(c.artifactKind)}`);
|
|
375
|
+
const contributorDid = assertNonEmptyIdentifier(c.contributorDid, "citation.contributorDid");
|
|
376
|
+
const artifactDid = assertNonEmptyIdentifier(c.artifactDid, "citation.artifactDid");
|
|
377
|
+
if (artifactDid === objectDid) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: object cannot cite itself as an upstream artifact");
|
|
378
|
+
if (contributorDid === authorDid) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: author cannot cite themselves as an upstream contributor");
|
|
379
|
+
if (!this.profiles.has(contributorDid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: cited contributor ${contributorDid} is not registered`);
|
|
380
|
+
if (seenContributors.has(contributorDid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate citation for contributor ${contributorDid}`);
|
|
381
|
+
seenContributors.add(contributorDid);
|
|
382
|
+
if (seenCitedArtifacts.has(artifactDid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate citation for artifact ${artifactDid}`);
|
|
383
|
+
seenCitedArtifacts.add(artifactDid);
|
|
384
|
+
if (!Number.isSafeInteger(c.shareBps) || c.shareBps <= 0 || c.shareBps > MAX_TOTAL_CITATION_SHARE_BPS) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: citation shareBps must be an integer between 1 and ${MAX_TOTAL_CITATION_SHARE_BPS}`);
|
|
385
|
+
totalShareBps += c.shareBps;
|
|
386
|
+
normalizedCitations.push({
|
|
387
|
+
contributorDid,
|
|
388
|
+
artifactKind: c.artifactKind,
|
|
389
|
+
artifactDid,
|
|
390
|
+
shareBps: c.shareBps
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
if (totalShareBps > MAX_TOTAL_CITATION_SHARE_BPS) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: total upstream citation shareBps (${totalShareBps}) exceeds maximum ${MAX_TOTAL_CITATION_SHARE_BPS}`);
|
|
394
|
+
const stored = {
|
|
395
|
+
objectDid,
|
|
396
|
+
authorDid,
|
|
397
|
+
kind: input.kind,
|
|
398
|
+
citations: normalizedCitations,
|
|
399
|
+
enableThankYouBadge: Boolean(input.enableThankYouBadge)
|
|
400
|
+
};
|
|
401
|
+
this.objects.set(objectDid, stored);
|
|
402
|
+
return {
|
|
403
|
+
...stored,
|
|
404
|
+
citations: stored.citations.map((c) => ({ ...c }))
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Computes remaining allowance for `(did, tokenAddress)` at `epochIndex` using lazy epoch reset.
|
|
409
|
+
* Note: Earned KARMA from peers NEVER inflates `epochBaseAllowance`, preventing infinite inflation loops.
|
|
410
|
+
*/
|
|
411
|
+
getRemainingAllowance(did, epochIndex, tokenAddress) {
|
|
412
|
+
const normalizedDid = assertNonEmptyIdentifier(did, "did");
|
|
413
|
+
const tokenConfig = this.resolveTokenConfig(tokenAddress);
|
|
414
|
+
this.assertEpochWithinHorizon(epochIndex);
|
|
415
|
+
const profile = this.profiles.get(normalizedDid);
|
|
416
|
+
if (!profile) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: identity ${normalizedDid} not found`);
|
|
417
|
+
const acct = this.getOrInitTokenAccount(normalizedDid, tokenConfig.tokenAddress);
|
|
418
|
+
if (epochIndex < acct.lastAllowanceEpoch) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: epoch rollback detected (${epochIndex} < ${acct.lastAllowanceEpoch})`);
|
|
419
|
+
if (!profile.verifiedHumanOrStaker || profile.trustMultiplierBps === 0) return 0n;
|
|
420
|
+
if (epochIndex > acct.lastAllowanceEpoch) return tokenConfig.epochBaseAllowance;
|
|
421
|
+
return tokenConfig.epochBaseAllowance > acct.usedAllowanceInEpoch ? tokenConfig.epochBaseAllowance - acct.usedAllowanceInEpoch : 0n;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Executes a `Give-to-Mint` transaction for any registered `give_to_mint` token (`tokenAddress`):
|
|
425
|
+
* 1. Enforces strict altruism (sender cannot be primary author OR any upstream cited contributor).
|
|
426
|
+
* 2. Lazily resets per-`(did, tokenAddress)` epoch allowance (`use-it-or-lose-it`).
|
|
427
|
+
* 3. Applies sender reputation multiplier (strictly decoupled from peer-earned KARMA to prevent infinite loops),
|
|
428
|
+
* same-pair repeat damping across all beneficiaries, and 2-node/3-node collusion ring damping.
|
|
429
|
+
* 4. Atomically splits minted FT tokens across the primary author and all upstream cited creators.
|
|
430
|
+
* 5. Mints a companion visual Medal NFT (`CompanionAppreciationMedalNft`) to the object author and
|
|
431
|
+
* optionally issues a soulbound, numbered `CreatorThankYouBadge` back to the sender.
|
|
432
|
+
*/
|
|
433
|
+
executeGiveToMint(request) {
|
|
434
|
+
const senderDid = assertNonEmptyIdentifier(request.senderDid, "senderDid");
|
|
435
|
+
const objectDid = assertNonEmptyIdentifier(request.objectDid, "objectDid");
|
|
436
|
+
const txHash = assertNonEmptyIdentifier(request.txHash, "txHash");
|
|
437
|
+
const tokenConfig = this.resolveTokenConfig(request.tokenAddress);
|
|
438
|
+
const tokenAddress = tokenConfig.tokenAddress;
|
|
439
|
+
this.assertEpochWithinHorizon(request.epochIndex);
|
|
440
|
+
if (request.medalKind !== void 0 && !VALID_MEDAL_KINDS.has(request.medalKind)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid medalKind ${String(request.medalKind)}`);
|
|
441
|
+
const initialVisibility = request.initialNftPayloadVisibility ?? "public";
|
|
442
|
+
if (!VALID_NFT_PAYLOAD_VISIBILITIES.has(initialVisibility)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid initialNftPayloadVisibility ${String(initialVisibility)}`);
|
|
443
|
+
if (typeof request.allowanceAmount !== "bigint" || request.allowanceAmount <= 0n) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: allowanceAmount must be a positive bigint");
|
|
444
|
+
if (request.allowanceAmount < MIN_GIVE_TO_MINT_DUST_FLOOR) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: allowanceAmount (${request.allowanceAmount}) is below anti-dust floor (${MIN_GIVE_TO_MINT_DUST_FLOOR}); store micro-interactions in ArcSpace and commit via checkpoint`);
|
|
445
|
+
if (this.processedTxHashes.has(txHash)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate txHash ${txHash}`);
|
|
446
|
+
const senderProfile = this.profiles.get(senderDid);
|
|
447
|
+
if (!senderProfile) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: sender ${senderDid} is not registered`);
|
|
448
|
+
if (!senderProfile.verifiedHumanOrStaker || senderProfile.trustMultiplierBps <= 0) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: unverified or zero-trust Sybil accounts cannot execute Give-to-Mint");
|
|
449
|
+
const targetObject = this.objects.get(objectDid);
|
|
450
|
+
if (!targetObject) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: target object ${objectDid} not found`);
|
|
451
|
+
if (senderDid === targetObject.authorDid) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: strict altruism violation — sender cannot Give-to-Mint to their own object");
|
|
452
|
+
for (const citation of targetObject.citations) if (citation.contributorDid === senderDid) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: strict altruism violation — sender is listed as an upstream cited contributor on target object");
|
|
453
|
+
const senderAcct = this.getOrInitTokenAccount(senderDid, tokenAddress);
|
|
454
|
+
if (request.epochIndex < senderAcct.lastAllowanceEpoch) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: epoch rollback detected (${request.epochIndex} < ${senderAcct.lastAllowanceEpoch})`);
|
|
455
|
+
const effectiveEpochUsed = request.epochIndex > senderAcct.lastAllowanceEpoch ? 0n : senderAcct.usedAllowanceInEpoch;
|
|
456
|
+
const availableAllowance = tokenConfig.epochBaseAllowance > effectiveEpochUsed ? tokenConfig.epochBaseAllowance - effectiveEpochUsed : 0n;
|
|
457
|
+
if (request.allowanceAmount > availableAllowance) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: insufficient epoch allowance for token ${tokenAddress} (requested ${request.allowanceAmount}, available ${availableAllowance})`);
|
|
458
|
+
const allRecipients = [targetObject.authorDid, ...targetObject.citations.map((c) => c.contributorDid)];
|
|
459
|
+
let priorForwardCount = 0;
|
|
460
|
+
let reciprocalRingDetected = false;
|
|
461
|
+
for (const recipientDid of allRecipients) {
|
|
462
|
+
const forwardKey = `${tokenAddress}::${request.epochIndex}::${senderDid}->${recipientDid}`;
|
|
463
|
+
const count = this.pairwiseEpochCounts.get(forwardKey) ?? 0;
|
|
464
|
+
if (count > priorForwardCount) priorForwardCount = count;
|
|
465
|
+
if (this.hasReciprocalOrTrianglePath(tokenAddress, request.epochIndex, senderDid, recipientDid)) reciprocalRingDetected = true;
|
|
466
|
+
}
|
|
467
|
+
const repeatInteractionCountInEpoch = priorForwardCount + 1;
|
|
468
|
+
let effectiveMultiplierBps = BigInt(senderProfile.trustMultiplierBps);
|
|
469
|
+
if (reciprocalRingDetected) effectiveMultiplierBps = effectiveMultiplierBps * RECIPROCAL_RING_DAMPING_BPS / BPS_DENOMINATOR;
|
|
470
|
+
if (priorForwardCount > 0) {
|
|
471
|
+
const shift = BigInt(Math.min(priorForwardCount, 10));
|
|
472
|
+
effectiveMultiplierBps = effectiveMultiplierBps >> shift;
|
|
473
|
+
}
|
|
474
|
+
const totalMintedKarma = request.allowanceAmount * effectiveMultiplierBps / BPS_DENOMINATOR;
|
|
475
|
+
if (totalMintedKarma <= 0n) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: effective minted KARMA attenuated to 0 due to anti-Sybil reciprocal/repeat damping");
|
|
476
|
+
this.processedTxHashes.add(txHash);
|
|
477
|
+
this.currentEpoch = request.epochIndex;
|
|
478
|
+
senderAcct.lastAllowanceEpoch = request.epochIndex;
|
|
479
|
+
senderAcct.usedAllowanceInEpoch = effectiveEpochUsed + request.allowanceAmount;
|
|
480
|
+
const edgeKey = `${tokenAddress}::${request.epochIndex}::${senderDid}`;
|
|
481
|
+
let edgeSet = this.epochDirectedEdges.get(edgeKey);
|
|
482
|
+
if (!edgeSet) {
|
|
483
|
+
edgeSet = /* @__PURE__ */ new Set();
|
|
484
|
+
this.epochDirectedEdges.set(edgeKey, edgeSet);
|
|
485
|
+
}
|
|
486
|
+
for (const recipientDid of allRecipients) {
|
|
487
|
+
const forwardKey = `${tokenAddress}::${request.epochIndex}::${senderDid}->${recipientDid}`;
|
|
488
|
+
this.pairwiseEpochCounts.set(forwardKey, (this.pairwiseEpochCounts.get(forwardKey) ?? 0) + 1);
|
|
489
|
+
edgeSet.add(recipientDid);
|
|
490
|
+
}
|
|
491
|
+
const distributions = [];
|
|
492
|
+
let distributedToCitations = 0n;
|
|
493
|
+
for (const citation of targetObject.citations) {
|
|
494
|
+
const shareKarma = totalMintedKarma * BigInt(citation.shareBps) / BPS_DENOMINATOR;
|
|
495
|
+
if (shareKarma > 0n) {
|
|
496
|
+
const citedAcct = this.getOrInitTokenAccount(citation.contributorDid, tokenAddress);
|
|
497
|
+
this.creditEarnedKarma(citedAcct, shareKarma, request.epochIndex);
|
|
498
|
+
distributedToCitations += shareKarma;
|
|
499
|
+
distributions.push({
|
|
500
|
+
recipientDid: citation.contributorDid,
|
|
501
|
+
role: "upstream_citation",
|
|
502
|
+
artifactDid: citation.artifactDid,
|
|
503
|
+
mintedKarma: shareKarma
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
const authorKarma = totalMintedKarma - distributedToCitations;
|
|
508
|
+
const authorAcct = this.getOrInitTokenAccount(targetObject.authorDid, tokenAddress);
|
|
509
|
+
this.creditEarnedKarma(authorAcct, authorKarma, request.epochIndex);
|
|
510
|
+
distributions.unshift({
|
|
511
|
+
recipientDid: targetObject.authorDid,
|
|
512
|
+
role: "primary_author",
|
|
513
|
+
artifactDid: targetObject.objectDid,
|
|
514
|
+
mintedKarma: authorKarma
|
|
515
|
+
});
|
|
516
|
+
let companionMedalNft;
|
|
517
|
+
if (request.medalKind && !reciprocalRingDetected) {
|
|
518
|
+
const medalDid = deriveCompanionMedalDid(txHash, senderDid, objectDid, request.medalKind);
|
|
519
|
+
companionMedalNft = {
|
|
520
|
+
medalDid,
|
|
521
|
+
medalKind: request.medalKind,
|
|
522
|
+
senderDid,
|
|
523
|
+
recipientAuthorDid: targetObject.authorDid,
|
|
524
|
+
targetObjectDid: objectDid,
|
|
525
|
+
tokenAddress,
|
|
526
|
+
accompaniedKarmaAmount: totalMintedKarma,
|
|
527
|
+
epochIndex: request.epochIndex,
|
|
528
|
+
transferrable: false,
|
|
529
|
+
holderArcSpaceUri: `arcspace://${targetObject.authorDid}/nfts/${medalDid}`,
|
|
530
|
+
payloadCommitmentDigest: computeNftPayloadCommitmentDigest(medalDid, targetObject.authorDid, senderDid, request.epochIndex),
|
|
531
|
+
payloadVisibility: initialVisibility,
|
|
532
|
+
authorizedViewerDids: [],
|
|
533
|
+
payloadCustodyState: "ISSUER_TEMP_STAGED"
|
|
534
|
+
};
|
|
535
|
+
this.companionMedals.set(medalDid, companionMedalNft);
|
|
536
|
+
}
|
|
537
|
+
const authorProfile = this.profiles.get(targetObject.authorDid);
|
|
538
|
+
let thankYouBadge;
|
|
539
|
+
if (request.allowanceAmount >= MIN_KARMA_FOR_THANK_YOU_BADGE && totalMintedKarma >= MIN_KARMA_FOR_THANK_YOU_BADGE && !reciprocalRingDetected) {
|
|
540
|
+
const streakKey = `${tokenAddress}:${senderDid}->${targetObject.authorDid}`;
|
|
541
|
+
const priorStreak = this.supporterStreaks.get(streakKey);
|
|
542
|
+
let streakCount = 1;
|
|
543
|
+
if (priorStreak) {
|
|
544
|
+
if (priorStreak.lastSupportedEpoch === request.epochIndex) streakCount = priorStreak.streakCount;
|
|
545
|
+
else if (priorStreak.lastSupportedEpoch === request.epochIndex - 1) streakCount = priorStreak.streakCount + 1;
|
|
546
|
+
}
|
|
547
|
+
const badgeIssuedInEpoch = priorStreak?.badgeIssuedInEpoch ?? -1;
|
|
548
|
+
const alreadyIssuedThisEpoch = badgeIssuedInEpoch === request.epochIndex;
|
|
549
|
+
if (tokenAddress === DEFAULT_KARMA_TOKEN_ADDRESS && targetObject.enableThankYouBadge && authorProfile.verifiedHumanOrStaker && authorProfile.sponsoredBadgeMintQuota > 0 && !alreadyIssuedThisEpoch) {
|
|
550
|
+
authorProfile.sponsoredBadgeMintQuota -= 1;
|
|
551
|
+
authorProfile.totalThankYouBadgesIssued += 1;
|
|
552
|
+
const serialNumber = authorProfile.totalThankYouBadgesIssued;
|
|
553
|
+
this.supporterStreaks.set(streakKey, {
|
|
554
|
+
lastSupportedEpoch: request.epochIndex,
|
|
555
|
+
streakCount,
|
|
556
|
+
badgeIssuedInEpoch: request.epochIndex
|
|
557
|
+
});
|
|
558
|
+
const badgeDid = deriveThankYouBadgeDid(targetObject.authorDid, senderDid, request.epochIndex, serialNumber);
|
|
559
|
+
thankYouBadge = {
|
|
560
|
+
badgeDid,
|
|
561
|
+
creatorDid: targetObject.authorDid,
|
|
562
|
+
recipientDid: senderDid,
|
|
563
|
+
sourceObjectDid: targetObject.objectDid,
|
|
564
|
+
tokenAddress,
|
|
565
|
+
epochIndex: request.epochIndex,
|
|
566
|
+
serialNumber,
|
|
567
|
+
streakCount,
|
|
568
|
+
transferrable: false,
|
|
569
|
+
holderArcSpaceUri: `arcspace://${senderDid}/nfts/${badgeDid}`,
|
|
570
|
+
payloadCommitmentDigest: computeNftPayloadCommitmentDigest(badgeDid, senderDid, targetObject.authorDid, request.epochIndex),
|
|
571
|
+
payloadVisibility: initialVisibility,
|
|
572
|
+
authorizedViewerDids: [],
|
|
573
|
+
payloadCustodyState: "ISSUER_TEMP_STAGED"
|
|
574
|
+
};
|
|
575
|
+
this.thankYouBadges.set(badgeDid, thankYouBadge);
|
|
576
|
+
} else this.supporterStreaks.set(streakKey, {
|
|
577
|
+
lastSupportedEpoch: request.epochIndex,
|
|
578
|
+
streakCount,
|
|
579
|
+
badgeIssuedInEpoch
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
return {
|
|
583
|
+
senderDid,
|
|
584
|
+
objectDid,
|
|
585
|
+
tokenAddress,
|
|
586
|
+
epochIndex: request.epochIndex,
|
|
587
|
+
allowanceConsumed: request.allowanceAmount,
|
|
588
|
+
remainingEpochAllowance: tokenConfig.epochBaseAllowance - senderAcct.usedAllowanceInEpoch,
|
|
589
|
+
effectiveMintMultiplierBps: effectiveMultiplierBps,
|
|
590
|
+
reciprocalRingDamped: reciprocalRingDetected,
|
|
591
|
+
repeatInteractionCountInEpoch,
|
|
592
|
+
totalMintedKarma,
|
|
593
|
+
distributions,
|
|
594
|
+
companionMedalNft,
|
|
595
|
+
thankYouBadge
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Engine 7 Integration: Stake free earned KARMA for attention gates (`Stake-to-Comment / Stake-to-DM`).
|
|
600
|
+
* Good actors get 100% refunded at zero cost; spammers get slashed.
|
|
601
|
+
*/
|
|
602
|
+
lockKarmaForAttentionGate(params) {
|
|
603
|
+
const lockId = assertNonEmptyIdentifier(params.lockId, "lockId");
|
|
604
|
+
const stakerDid = assertNonEmptyIdentifier(params.stakerDid, "stakerDid");
|
|
605
|
+
const targetObjectDid = assertNonEmptyIdentifier(params.targetObjectDid, "targetObjectDid");
|
|
606
|
+
const tokenConfig = this.resolveTokenConfig(params.tokenAddress);
|
|
607
|
+
this.assertEpochWithinHorizon(params.epochIndex);
|
|
608
|
+
if (typeof params.stakeAmount !== "bigint" || params.stakeAmount <= 0n) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: stakeAmount must be a positive bigint");
|
|
609
|
+
if (this.stakeLocks.has(lockId)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate stake lockId ${lockId}`);
|
|
610
|
+
const targetObject = this.objects.get(targetObjectDid);
|
|
611
|
+
if (!targetObject) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: target object ${targetObjectDid} not found`);
|
|
612
|
+
if (targetObject.authorDid === stakerDid) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: author cannot stake KARMA on their own object attention gate");
|
|
613
|
+
if (!this.profiles.has(stakerDid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: staker ${stakerDid} not found`);
|
|
614
|
+
const stakerAcct = this.getOrInitTokenAccount(stakerDid, tokenConfig.tokenAddress);
|
|
615
|
+
const availableKarma = stakerAcct.earnedKarma - stakerAcct.stakedKarma;
|
|
616
|
+
if (params.stakeAmount > availableKarma) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: insufficient available KARMA to stake (requested ${params.stakeAmount}, available ${availableKarma})`);
|
|
617
|
+
this.currentEpoch = params.epochIndex;
|
|
618
|
+
stakerAcct.stakedKarma += params.stakeAmount;
|
|
619
|
+
const lock = {
|
|
620
|
+
lockId,
|
|
621
|
+
stakerDid,
|
|
622
|
+
targetObjectDid,
|
|
623
|
+
tokenAddress: tokenConfig.tokenAddress,
|
|
624
|
+
stakedKarma: params.stakeAmount,
|
|
625
|
+
epochIndex: params.epochIndex,
|
|
626
|
+
status: "LOCKED"
|
|
627
|
+
};
|
|
628
|
+
this.stakeLocks.set(lockId, lock);
|
|
629
|
+
return { ...lock };
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Resolves a KARMA attention gate lock:
|
|
633
|
+
* - `ACCEPT_AND_REFUND`: 100% of staked KARMA is unlocked at zero cost to the commenter/sender.
|
|
634
|
+
* - `SLASH_SPAM`: Staked KARMA is permanently burned/slashed from the spammer's reputation.
|
|
635
|
+
*/
|
|
636
|
+
resolveKarmaAttentionGate(lockId, resolution) {
|
|
637
|
+
const normalizedLockId = assertNonEmptyIdentifier(lockId, "lockId");
|
|
638
|
+
const lock = this.stakeLocks.get(normalizedLockId);
|
|
639
|
+
if (!lock) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: stake lock ${normalizedLockId} not found`);
|
|
640
|
+
if (lock.status !== "LOCKED") throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: stake lock ${normalizedLockId} already resolved`);
|
|
641
|
+
const stakerAcct = this.getOrInitTokenAccount(lock.stakerDid, lock.tokenAddress);
|
|
642
|
+
stakerAcct.stakedKarma -= lock.stakedKarma;
|
|
643
|
+
if (resolution === "ACCEPT_AND_REFUND") lock.status = "REFUNDED";
|
|
644
|
+
else if (resolution === "SLASH_SPAM") {
|
|
645
|
+
stakerAcct.earnedKarma -= lock.stakedKarma;
|
|
646
|
+
if (stakerAcct.earnedKarmaInEpoch >= lock.stakedKarma) stakerAcct.earnedKarmaInEpoch -= lock.stakedKarma;
|
|
647
|
+
else stakerAcct.earnedKarmaInEpoch = 0n;
|
|
648
|
+
stakerAcct.slashedKarma += lock.stakedKarma;
|
|
649
|
+
lock.status = "SLASHED";
|
|
650
|
+
} else throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: invalid attention gate resolution");
|
|
651
|
+
return { ...lock };
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Unified Epoch Pool Settlement (`PersonalEpochTippingPool` $100/mo, `SponsorEpochPool` $1,000/mo Crypto AdSense,
|
|
655
|
+
* and `PhilanthropyKarmaPool` $200,000 tax/donation routing) indexed by verified per-token KARMA weights.
|
|
656
|
+
* Guarantees strict conservation of value (`sum(payouts) === totalPoolAmount`).
|
|
657
|
+
*/
|
|
658
|
+
settleKarmaIndexedPool(input) {
|
|
659
|
+
const poolId = assertNonEmptyIdentifier(input.poolId, "poolId");
|
|
660
|
+
const sponsorDid = assertNonEmptyIdentifier(input.sponsorDid, "sponsorDid");
|
|
661
|
+
const tokenConfig = this.resolveTokenConfig(input.tokenAddress);
|
|
662
|
+
this.assertEpochWithinHorizon(input.epochIndex);
|
|
663
|
+
if (!VALID_POOL_KINDS.has(input.poolKind)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid poolKind ${String(input.poolKind)}`);
|
|
664
|
+
if (this.settledPools.has(poolId)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: pool ${poolId} has already been settled`);
|
|
665
|
+
if (typeof input.totalPoolAmount !== "bigint" || input.totalPoolAmount <= 0n) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: totalPoolAmount must be a positive bigint");
|
|
666
|
+
if (!Array.isArray(input.recipientWeights) || input.recipientWeights.length === 0) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: recipientWeights must be a non-empty array");
|
|
667
|
+
const seenRecipients = /* @__PURE__ */ new Set();
|
|
668
|
+
let totalWeight = 0n;
|
|
669
|
+
for (const entry of input.recipientWeights) {
|
|
670
|
+
const recipientDid = assertNonEmptyIdentifier(entry.recipientDid, "recipientDid");
|
|
671
|
+
if (recipientDid === sponsorDid) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: sponsor cannot self-route epoch pool funds to their own DID");
|
|
672
|
+
if (seenRecipients.has(recipientDid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate recipient ${recipientDid} in pool`);
|
|
673
|
+
seenRecipients.add(recipientDid);
|
|
674
|
+
if (typeof entry.karmaWeight !== "bigint" || entry.karmaWeight <= 0n) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: karmaWeight must be a positive bigint");
|
|
675
|
+
const recipientProfile = this.profiles.get(recipientDid);
|
|
676
|
+
if (!recipientProfile) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: pool recipient ${recipientDid} is not registered`);
|
|
677
|
+
if (!recipientProfile.verifiedHumanOrStaker || recipientProfile.trustMultiplierBps <= 0) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: unverified or zero-trust recipient ${recipientDid} cannot receive pool settlement`);
|
|
678
|
+
const recipientAcct = this.getOrInitTokenAccount(recipientDid, tokenConfig.tokenAddress);
|
|
679
|
+
const unencumberedKarma = recipientAcct.earnedKarma - recipientAcct.stakedKarma;
|
|
680
|
+
if (entry.karmaWeight > unencumberedKarma) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: recipient ${recipientDid} karmaWeight (${entry.karmaWeight}) exceeds verified earnedKarma (${unencumberedKarma} unencumbered) for token ${tokenConfig.tokenAddress}`);
|
|
681
|
+
totalWeight += entry.karmaWeight;
|
|
682
|
+
}
|
|
683
|
+
const payouts = [];
|
|
684
|
+
let allocatedTotal = 0n;
|
|
685
|
+
for (const entry of input.recipientWeights) {
|
|
686
|
+
const exactProRata = input.totalPoolAmount * entry.karmaWeight / totalWeight;
|
|
687
|
+
allocatedTotal += exactProRata;
|
|
688
|
+
payouts.push({
|
|
689
|
+
recipientDid: entry.recipientDid,
|
|
690
|
+
karmaWeight: entry.karmaWeight,
|
|
691
|
+
payoutAmount: exactProRata
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
const remainderDust = input.totalPoolAmount - allocatedTotal;
|
|
695
|
+
if (remainderDust > 0n) {
|
|
696
|
+
let bestIdx = 0;
|
|
697
|
+
for (let i = 1; i < payouts.length; i++) if (payouts[i].karmaWeight > payouts[bestIdx].karmaWeight) bestIdx = i;
|
|
698
|
+
payouts[bestIdx].payoutAmount += remainderDust;
|
|
699
|
+
}
|
|
700
|
+
this.currentEpoch = input.epochIndex;
|
|
701
|
+
this.settledPools.add(poolId);
|
|
702
|
+
return {
|
|
703
|
+
poolId,
|
|
704
|
+
poolKind: input.poolKind,
|
|
705
|
+
tokenAddress: tokenConfig.tokenAddress,
|
|
706
|
+
epochIndex: input.epochIndex,
|
|
707
|
+
totalPoolAmount: input.totalPoolAmount,
|
|
708
|
+
totalWeight,
|
|
709
|
+
payouts
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
getIdentityState(did, tokenAddress) {
|
|
713
|
+
const profile = this.profiles.get(did);
|
|
714
|
+
if (!profile) return;
|
|
715
|
+
const tokenConfig = this.resolveTokenConfig(tokenAddress);
|
|
716
|
+
const acct = this.getOrInitTokenAccount(did, tokenConfig.tokenAddress);
|
|
717
|
+
return {
|
|
718
|
+
did: profile.did,
|
|
719
|
+
verifiedHumanOrStaker: profile.verifiedHumanOrStaker,
|
|
720
|
+
trustMultiplierBps: profile.trustMultiplierBps,
|
|
721
|
+
earnedKarma: acct.earnedKarma,
|
|
722
|
+
stakedKarma: acct.stakedKarma,
|
|
723
|
+
slashedKarma: acct.slashedKarma,
|
|
724
|
+
lastAllowanceEpoch: acct.lastAllowanceEpoch,
|
|
725
|
+
usedAllowanceInEpoch: acct.usedAllowanceInEpoch,
|
|
726
|
+
sponsoredBadgeMintQuota: profile.sponsoredBadgeMintQuota,
|
|
727
|
+
totalThankYouBadgesIssued: profile.totalThankYouBadgesIssued
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
getPerTokenAccountState(did, tokenAddress) {
|
|
731
|
+
if (!this.profiles.has(did)) return;
|
|
732
|
+
const tokenConfig = this.resolveTokenConfig(tokenAddress);
|
|
733
|
+
return { ...this.getOrInitTokenAccount(did, tokenConfig.tokenAddress) };
|
|
734
|
+
}
|
|
735
|
+
getThankYouBadgesForRecipient(recipientDid) {
|
|
736
|
+
const result = [];
|
|
737
|
+
for (const badge of this.thankYouBadges.values()) if (badge.recipientDid === recipientDid) result.push({
|
|
738
|
+
...badge,
|
|
739
|
+
authorizedViewerDids: [...badge.authorizedViewerDids]
|
|
740
|
+
});
|
|
741
|
+
return result;
|
|
742
|
+
}
|
|
743
|
+
getCompanionMedalsForObject(objectDid) {
|
|
744
|
+
const result = [];
|
|
745
|
+
for (const medal of this.companionMedals.values()) if (medal.targetObjectDid === objectDid) result.push({
|
|
746
|
+
...medal,
|
|
747
|
+
authorizedViewerDids: [...medal.authorizedViewerDids]
|
|
748
|
+
});
|
|
749
|
+
return result;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Issue #1231: Holder-Sovereign NFT Payload Visibility Control.
|
|
753
|
+
* Because the NFT payload lives in the holder's own ArcSpace (`holderArcSpaceUri`) rather than
|
|
754
|
+
* being forcibly stored/exposed on-chain, ONLY the current NFT holder (`recipientAuthorDid` for Medal NFTs,
|
|
755
|
+
* `recipientDid` for Thank-You Badges) can grant or revoke external visibility (`public` | `authorized_only` | `private`).
|
|
756
|
+
*/
|
|
757
|
+
configureNftPayloadVisibility(input) {
|
|
758
|
+
const nftDid = assertNonEmptyIdentifier(input.nftDid, "nftDid");
|
|
759
|
+
const callerDid = assertNonEmptyIdentifier(input.callerDid, "callerDid");
|
|
760
|
+
if (!VALID_NFT_PAYLOAD_VISIBILITIES.has(input.visibility)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: invalid NFT payload visibility ${String(input.visibility)}`);
|
|
761
|
+
if (input.updatedPayloadCommitmentDigest !== void 0 && (typeof input.updatedPayloadCommitmentDigest !== "string" || !BYTES32_HEX_REGEX.test(input.updatedPayloadCommitmentDigest))) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: updatedPayloadCommitmentDigest must be a canonical 32-byte 0x-prefixed hex digest");
|
|
762
|
+
const normalizedViewers = [];
|
|
763
|
+
if (input.authorizedViewerDids !== void 0) {
|
|
764
|
+
if (!Array.isArray(input.authorizedViewerDids) || input.authorizedViewerDids.length > 100) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: authorizedViewerDids must be an array with at most 100 DIDs");
|
|
765
|
+
const seen = /* @__PURE__ */ new Set();
|
|
766
|
+
for (const v of input.authorizedViewerDids) {
|
|
767
|
+
const viewerDid = assertNonEmptyIdentifier(v, "authorizedViewerDid");
|
|
768
|
+
if (!seen.has(viewerDid)) {
|
|
769
|
+
seen.add(viewerDid);
|
|
770
|
+
normalizedViewers.push(viewerDid);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
const medal = this.companionMedals.get(nftDid);
|
|
775
|
+
if (medal) {
|
|
776
|
+
if (medal.recipientAuthorDid !== callerDid) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: only the NFT holder (${medal.recipientAuthorDid}) can configure payload visibility for ${nftDid}`);
|
|
777
|
+
if (input.updatedPayloadCommitmentDigest && input.updatedPayloadCommitmentDigest.toLowerCase() !== medal.payloadCommitmentDigest.toLowerCase()) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: payloadCommitmentDigest is immutable after minting and cannot be overwritten");
|
|
778
|
+
medal.payloadVisibility = input.visibility;
|
|
779
|
+
medal.authorizedViewerDids = input.visibility === "authorized_only" ? normalizedViewers : [];
|
|
780
|
+
return {
|
|
781
|
+
...medal,
|
|
782
|
+
authorizedViewerDids: [...medal.authorizedViewerDids]
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
const badge = this.thankYouBadges.get(nftDid);
|
|
786
|
+
if (badge) {
|
|
787
|
+
if (badge.recipientDid !== callerDid) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: only the NFT holder (${badge.recipientDid}) can configure payload visibility for ${nftDid}`);
|
|
788
|
+
if (input.updatedPayloadCommitmentDigest && input.updatedPayloadCommitmentDigest.toLowerCase() !== badge.payloadCommitmentDigest.toLowerCase()) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: payloadCommitmentDigest is immutable after minting and cannot be overwritten");
|
|
789
|
+
badge.payloadVisibility = input.visibility;
|
|
790
|
+
badge.authorizedViewerDids = input.visibility === "authorized_only" ? normalizedViewers : [];
|
|
791
|
+
return {
|
|
792
|
+
...badge,
|
|
793
|
+
authorizedViewerDids: [...badge.authorizedViewerDids]
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: NFT ${nftDid} not found`);
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Issue #1231: Evaluates whether `viewerDid` is permitted by the NFT holder to read the off-chain
|
|
800
|
+
* NFT payload stored in the holder's ArcSpace. If the holder has not consented (`private` or unwhitelisted
|
|
801
|
+
* `authorized_only`), `accessible` is false and `holderArcSpaceUri` is withheld.
|
|
802
|
+
*/
|
|
803
|
+
resolveNftPayloadAccess(params) {
|
|
804
|
+
const nftDid = assertNonEmptyIdentifier(params.nftDid, "nftDid");
|
|
805
|
+
const viewerDid = assertNonEmptyIdentifier(params.viewerDid, "viewerDid");
|
|
806
|
+
const medal = this.companionMedals.get(nftDid);
|
|
807
|
+
const badge = medal ? void 0 : this.thankYouBadges.get(nftDid);
|
|
808
|
+
if (!medal && !badge) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: NFT ${nftDid} not found`);
|
|
809
|
+
const holderDid = medal ? medal.recipientAuthorDid : badge.recipientDid;
|
|
810
|
+
const visibility = medal ? medal.payloadVisibility : badge.payloadVisibility;
|
|
811
|
+
const custodyState = medal ? medal.payloadCustodyState : badge.payloadCustodyState;
|
|
812
|
+
const authorizedViewers = medal ? medal.authorizedViewerDids : badge.authorizedViewerDids;
|
|
813
|
+
const holderArcSpaceUri = medal ? medal.holderArcSpaceUri : badge.holderArcSpaceUri;
|
|
814
|
+
const payloadCommitmentDigest = medal ? medal.payloadCommitmentDigest : badge.payloadCommitmentDigest;
|
|
815
|
+
if (viewerDid === holderDid) return {
|
|
816
|
+
nftDid,
|
|
817
|
+
holderDid,
|
|
818
|
+
viewerDid,
|
|
819
|
+
visibility,
|
|
820
|
+
custodyState,
|
|
821
|
+
accessible: true,
|
|
822
|
+
reason: "ALLOWED_HOLDER",
|
|
823
|
+
holderArcSpaceUri,
|
|
824
|
+
payloadCommitmentDigest
|
|
825
|
+
};
|
|
826
|
+
if (visibility === "public") return {
|
|
827
|
+
nftDid,
|
|
828
|
+
holderDid,
|
|
829
|
+
viewerDid,
|
|
830
|
+
visibility,
|
|
831
|
+
custodyState,
|
|
832
|
+
accessible: true,
|
|
833
|
+
reason: "ALLOWED_PUBLIC",
|
|
834
|
+
holderArcSpaceUri,
|
|
835
|
+
payloadCommitmentDigest
|
|
836
|
+
};
|
|
837
|
+
if (visibility === "authorized_only") {
|
|
838
|
+
if (authorizedViewers.includes(viewerDid)) return {
|
|
839
|
+
nftDid,
|
|
840
|
+
holderDid,
|
|
841
|
+
viewerDid,
|
|
842
|
+
visibility,
|
|
843
|
+
custodyState,
|
|
844
|
+
accessible: true,
|
|
845
|
+
reason: "ALLOWED_AUTHORIZED_VIEWER",
|
|
846
|
+
holderArcSpaceUri,
|
|
847
|
+
payloadCommitmentDigest
|
|
848
|
+
};
|
|
849
|
+
return {
|
|
850
|
+
nftDid,
|
|
851
|
+
holderDid,
|
|
852
|
+
viewerDid,
|
|
853
|
+
visibility,
|
|
854
|
+
custodyState,
|
|
855
|
+
accessible: false,
|
|
856
|
+
reason: "DENIED_UNAUTHORIZED",
|
|
857
|
+
payloadCommitmentDigest
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
return {
|
|
861
|
+
nftDid,
|
|
862
|
+
holderDid,
|
|
863
|
+
viewerDid,
|
|
864
|
+
visibility,
|
|
865
|
+
custodyState,
|
|
866
|
+
accessible: false,
|
|
867
|
+
reason: "DENIED_PRIVATE",
|
|
868
|
+
payloadCommitmentDigest
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Issue #1231: 3-Stage NFT Payload Delivery & Custody Handover (e.g., OnlyFans / Private Circle creator
|
|
873
|
+
* delivering private photo/video binary to a fan).
|
|
874
|
+
* Once the holder verifies `verifiedPayloadDigest === payloadCommitmentDigest` and saves the binary in
|
|
875
|
+
* their own ArcSpace (`HOLDER_SAVED_IN_ARCSPACE` / `ISSUER_STORAGE_RELEASED`), the original creator/issuer
|
|
876
|
+
* has zero obligation to keep storing the binary and can purge their staging buffer.
|
|
877
|
+
*/
|
|
878
|
+
acknowledgeNftPayloadCustody(input) {
|
|
879
|
+
const nftDid = assertNonEmptyIdentifier(input.nftDid, "nftDid");
|
|
880
|
+
const holderDid = assertNonEmptyIdentifier(input.holderDid, "holderDid");
|
|
881
|
+
if (typeof input.verifiedPayloadDigest !== "string" || !BYTES32_HEX_REGEX.test(input.verifiedPayloadDigest)) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: verifiedPayloadDigest must be a canonical 32-byte 0x-prefixed hex digest");
|
|
882
|
+
const medal = this.companionMedals.get(nftDid);
|
|
883
|
+
if (medal) {
|
|
884
|
+
if (medal.recipientAuthorDid !== holderDid) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: only the NFT holder (${medal.recipientAuthorDid}) can acknowledge payload custody for ${nftDid}`);
|
|
885
|
+
if (medal.payloadCommitmentDigest.toLowerCase() !== input.verifiedPayloadDigest.toLowerCase()) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: verifiedPayloadDigest mismatch against on-chain payloadCommitmentDigest for ${nftDid}`);
|
|
886
|
+
if (medal.payloadCustodyState === "ISSUER_STORAGE_RELEASED" && input.releaseIssuerStorageImmediately === false) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: cannot regress payloadCustodyState from ISSUER_STORAGE_RELEASED to HOLDER_SAVED_IN_ARCSPACE");
|
|
887
|
+
medal.payloadCustodyState = input.releaseIssuerStorageImmediately === false ? "HOLDER_SAVED_IN_ARCSPACE" : "ISSUER_STORAGE_RELEASED";
|
|
888
|
+
return {
|
|
889
|
+
...medal,
|
|
890
|
+
authorizedViewerDids: [...medal.authorizedViewerDids]
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
const badge = this.thankYouBadges.get(nftDid);
|
|
894
|
+
if (badge) {
|
|
895
|
+
if (badge.recipientDid !== holderDid) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: only the NFT holder (${badge.recipientDid}) can acknowledge payload custody for ${nftDid}`);
|
|
896
|
+
if (badge.payloadCommitmentDigest.toLowerCase() !== input.verifiedPayloadDigest.toLowerCase()) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: verifiedPayloadDigest mismatch against on-chain payloadCommitmentDigest for ${nftDid}`);
|
|
897
|
+
if (badge.payloadCustodyState === "ISSUER_STORAGE_RELEASED" && input.releaseIssuerStorageImmediately === false) throw new CustomError(ErrorCode.Forbidden, "GiveToMint: cannot regress payloadCustodyState from ISSUER_STORAGE_RELEASED to HOLDER_SAVED_IN_ARCSPACE");
|
|
898
|
+
badge.payloadCustodyState = input.releaseIssuerStorageImmediately === false ? "HOLDER_SAVED_IN_ARCSPACE" : "ISSUER_STORAGE_RELEASED";
|
|
899
|
+
return {
|
|
900
|
+
...badge,
|
|
901
|
+
authorizedViewerDids: [...badge.authorizedViewerDids]
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: NFT ${nftDid} not found`);
|
|
905
|
+
}
|
|
906
|
+
/**
|
|
907
|
+
* Issue #1231: Prunes temporary anti-Sybil graph edges (`pairwiseEpochCounts` and `epochDirectedEdges`)
|
|
908
|
+
* for historical epochs strictly older than `retainFromEpoch` (defaults to `this.currentEpoch - 1`),
|
|
909
|
+
* leaving only a compact 32-byte `VerifiableEpochArchiveCheckpoint` on-chain while detailed history
|
|
910
|
+
* remains in each user's ArcSpace.
|
|
911
|
+
*/
|
|
912
|
+
pruneArchivedEpochGraph(retainFromEpoch) {
|
|
913
|
+
const maxSafeCutoffEpoch = Math.max(0, this.currentEpoch - 1);
|
|
914
|
+
const cutoffEpoch = retainFromEpoch ?? maxSafeCutoffEpoch;
|
|
915
|
+
assertValidEpochIndex(cutoffEpoch);
|
|
916
|
+
if (cutoffEpoch > maxSafeCutoffEpoch) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: retainFromEpoch (${cutoffEpoch}) cannot exceed max safe archive cutoff (${maxSafeCutoffEpoch}) because active anti-Sybil collusion graphs require epochs ${maxSafeCutoffEpoch}..${this.currentEpoch}`);
|
|
917
|
+
const prunedRecords = [];
|
|
918
|
+
let prunedPairwiseEntryCount = 0;
|
|
919
|
+
let prunedDirectedEdgeSetCount = 0;
|
|
920
|
+
for (const [key, count] of this.pairwiseEpochCounts.entries()) {
|
|
921
|
+
const parts = key.split("::");
|
|
922
|
+
const epochNum = Number(parts[1]);
|
|
923
|
+
if (Number.isSafeInteger(epochNum) && epochNum < cutoffEpoch) {
|
|
924
|
+
prunedRecords.push(`pair:${key}=${count}`);
|
|
925
|
+
this.pairwiseEpochCounts.delete(key);
|
|
926
|
+
prunedPairwiseEntryCount += 1;
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
for (const [key, edgeSet] of this.epochDirectedEdges.entries()) {
|
|
930
|
+
const parts = key.split("::");
|
|
931
|
+
const epochNum = Number(parts[1]);
|
|
932
|
+
if (Number.isSafeInteger(epochNum) && epochNum < cutoffEpoch) {
|
|
933
|
+
const sortedTargets = [...edgeSet].sort().join(",");
|
|
934
|
+
prunedRecords.push(`edge:${key}->[${sortedTargets}]`);
|
|
935
|
+
this.epochDirectedEdges.delete(key);
|
|
936
|
+
prunedDirectedEdgeSetCount += 1;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
prunedRecords.sort();
|
|
940
|
+
const archiveStateRoot = `0x${createHash("sha256").update(`ocap:epoch-graph-archive:v1:${cutoffEpoch}:${prunedRecords.join("|")}`).digest("hex")}`;
|
|
941
|
+
const summary = {
|
|
942
|
+
archiveEpochBefore: cutoffEpoch,
|
|
943
|
+
prunedPairwiseEntryCount,
|
|
944
|
+
prunedDirectedEdgeSetCount,
|
|
945
|
+
archiveStateRoot
|
|
946
|
+
};
|
|
947
|
+
this.archivedEpochCheckpoints.push(summary);
|
|
948
|
+
return { ...summary };
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Issue #1231: Commits an aggregated batch of off-chain `ArcSpace` Karma vouchers via a single
|
|
952
|
+
* on-chain `Checkpoint` transaction:
|
|
953
|
+
* - Detailed historical vouchers stay in users' own `ArcSpace`s (user-borne storage);
|
|
954
|
+
* - On-chain state only stores the latest balances, latest `arcSpaceCheckpointRoot`, and automatically
|
|
955
|
+
* prunes expired epoch graph edges (`epoch < epochIndex - 1`).
|
|
956
|
+
*/
|
|
957
|
+
commitArcSpaceKarmaCheckpoint(input) {
|
|
958
|
+
const checkpointId = assertNonEmptyIdentifier(input.checkpointId, "checkpointId");
|
|
959
|
+
const tokenAddress = this.resolveTokenConfig(input.tokenAddress).tokenAddress;
|
|
960
|
+
this.assertEpochWithinHorizon(input.epochIndex);
|
|
961
|
+
if (this.processedCheckpointIds.has(checkpointId)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate checkpointId ${checkpointId}`);
|
|
962
|
+
if (typeof input.expectedCheckpointRoot !== "string" || !BYTES32_HEX_REGEX.test(input.expectedCheckpointRoot)) throw new CustomError(ErrorCode.InvalidTx, "GiveToMint: expectedCheckpointRoot must be a canonical 32-byte 0x-prefixed hex digest");
|
|
963
|
+
if (!Array.isArray(input.vouchers) || input.vouchers.length === 0 || input.vouchers.length > MAX_CHECKPOINT_VOUCHERS_PER_BATCH) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: checkpoint vouchers must contain 1..${MAX_CHECKPOINT_VOUCHERS_PER_BATCH} items`);
|
|
964
|
+
const seenVoucherIds = /* @__PURE__ */ new Set();
|
|
965
|
+
for (const v of input.vouchers) {
|
|
966
|
+
const vid = assertNonEmptyIdentifier(v.voucherId, "voucherId");
|
|
967
|
+
if (seenVoucherIds.has(vid)) throw new CustomError(ErrorCode.InvalidTx, `GiveToMint: duplicate voucherId ${vid} in checkpoint batch`);
|
|
968
|
+
seenVoucherIds.add(vid);
|
|
969
|
+
if (typeof v.allowanceAmount !== "bigint" || v.allowanceAmount < MIN_GIVE_TO_MINT_DUST_FLOOR) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: voucher ${vid} allowanceAmount (${v.allowanceAmount}) is below anti-dust floor (${MIN_GIVE_TO_MINT_DUST_FLOOR})`);
|
|
970
|
+
}
|
|
971
|
+
const computedRoot = computeArcSpaceCheckpointRoot(tokenAddress, input.epochIndex, input.vouchers);
|
|
972
|
+
if (computedRoot.toLowerCase() !== input.expectedCheckpointRoot.toLowerCase()) throw new CustomError(ErrorCode.Forbidden, `GiveToMint: checkpointRoot mismatch (expected ${input.expectedCheckpointRoot}, computed ${computedRoot})`);
|
|
973
|
+
const prevEpoch = this.currentEpoch;
|
|
974
|
+
const snapProfiles = /* @__PURE__ */ new Map();
|
|
975
|
+
for (const [k, p] of this.profiles.entries()) snapProfiles.set(k, { ...p });
|
|
976
|
+
const snapTokenAccounts = /* @__PURE__ */ new Map();
|
|
977
|
+
for (const [k, a] of this.tokenAccounts.entries()) snapTokenAccounts.set(k, { ...a });
|
|
978
|
+
const snapPairwise = new Map(this.pairwiseEpochCounts);
|
|
979
|
+
const snapEdges = /* @__PURE__ */ new Map();
|
|
980
|
+
for (const [k, s] of this.epochDirectedEdges.entries()) snapEdges.set(k, new Set(s));
|
|
981
|
+
const snapStreaks = /* @__PURE__ */ new Map();
|
|
982
|
+
for (const [k, s] of this.supporterStreaks.entries()) snapStreaks.set(k, { ...s });
|
|
983
|
+
const snapThankYouBadges = /* @__PURE__ */ new Map();
|
|
984
|
+
for (const [k, b] of this.thankYouBadges.entries()) snapThankYouBadges.set(k, {
|
|
985
|
+
...b,
|
|
986
|
+
authorizedViewerDids: [...b.authorizedViewerDids]
|
|
987
|
+
});
|
|
988
|
+
const snapCompanionMedals = /* @__PURE__ */ new Map();
|
|
989
|
+
for (const [k, m] of this.companionMedals.entries()) snapCompanionMedals.set(k, {
|
|
990
|
+
...m,
|
|
991
|
+
authorizedViewerDids: [...m.authorizedViewerDids]
|
|
992
|
+
});
|
|
993
|
+
const snapProcessedTxs = new Set(this.processedTxHashes);
|
|
994
|
+
let totalMintedKarmaInBatch = 0n;
|
|
995
|
+
const touchedDids = /* @__PURE__ */ new Set();
|
|
996
|
+
try {
|
|
997
|
+
for (const v of input.vouchers) {
|
|
998
|
+
const res = this.executeGiveToMint({
|
|
999
|
+
senderDid: v.senderDid,
|
|
1000
|
+
objectDid: v.objectDid,
|
|
1001
|
+
tokenAddress,
|
|
1002
|
+
allowanceAmount: v.allowanceAmount,
|
|
1003
|
+
medalKind: v.medalKind,
|
|
1004
|
+
initialNftPayloadVisibility: v.initialNftPayloadVisibility,
|
|
1005
|
+
epochIndex: input.epochIndex,
|
|
1006
|
+
txHash: `chk:${tokenAddress}:${v.voucherId}`
|
|
1007
|
+
});
|
|
1008
|
+
totalMintedKarmaInBatch += res.totalMintedKarma;
|
|
1009
|
+
touchedDids.add(res.senderDid);
|
|
1010
|
+
for (const dist of res.distributions) touchedDids.add(dist.recipientDid);
|
|
1011
|
+
}
|
|
1012
|
+
} catch (err) {
|
|
1013
|
+
this.currentEpoch = prevEpoch;
|
|
1014
|
+
this.profiles.clear();
|
|
1015
|
+
for (const [k, p] of snapProfiles) this.profiles.set(k, p);
|
|
1016
|
+
this.tokenAccounts.clear();
|
|
1017
|
+
for (const [k, a] of snapTokenAccounts) this.tokenAccounts.set(k, a);
|
|
1018
|
+
this.pairwiseEpochCounts.clear();
|
|
1019
|
+
for (const [k, c] of snapPairwise) this.pairwiseEpochCounts.set(k, c);
|
|
1020
|
+
this.epochDirectedEdges.clear();
|
|
1021
|
+
for (const [k, s] of snapEdges) this.epochDirectedEdges.set(k, s);
|
|
1022
|
+
this.supporterStreaks.clear();
|
|
1023
|
+
for (const [k, s] of snapStreaks) this.supporterStreaks.set(k, s);
|
|
1024
|
+
this.thankYouBadges.clear();
|
|
1025
|
+
for (const [k, b] of snapThankYouBadges) this.thankYouBadges.set(k, b);
|
|
1026
|
+
this.companionMedals.clear();
|
|
1027
|
+
for (const [k, m] of snapCompanionMedals) this.companionMedals.set(k, m);
|
|
1028
|
+
this.processedTxHashes.clear();
|
|
1029
|
+
for (const h of snapProcessedTxs) this.processedTxHashes.add(h);
|
|
1030
|
+
throw err;
|
|
1031
|
+
}
|
|
1032
|
+
for (const did of touchedDids) {
|
|
1033
|
+
const acct = this.getOrInitTokenAccount(did, tokenAddress);
|
|
1034
|
+
acct.latestArcSpaceCheckpointRoot = computedRoot;
|
|
1035
|
+
}
|
|
1036
|
+
this.processedCheckpointIds.add(checkpointId);
|
|
1037
|
+
const prunedArchive = this.pruneArchivedEpochGraph(Math.max(0, input.epochIndex - 1));
|
|
1038
|
+
return {
|
|
1039
|
+
checkpointId,
|
|
1040
|
+
tokenAddress,
|
|
1041
|
+
epochIndex: input.epochIndex,
|
|
1042
|
+
checkpointRoot: computedRoot,
|
|
1043
|
+
voucherCount: input.vouchers.length,
|
|
1044
|
+
totalMintedKarmaInBatch,
|
|
1045
|
+
prunedArchive
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
getActiveEpochGraphSize() {
|
|
1049
|
+
return {
|
|
1050
|
+
pairwiseEntries: this.pairwiseEpochCounts.size,
|
|
1051
|
+
directedEdgeSets: this.epochDirectedEdges.size
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
|
|
1056
|
+
//#endregion
|
|
1057
|
+
export { BPS_DENOMINATOR, DEFAULT_EPOCH_KARMA_ALLOWANCE, DEFAULT_KARMA_TOKEN_ADDRESS, DEFAULT_MAX_HISTORICAL_KARMA_CLAIM, DEFAULT_SPONSORED_BADGE_MINT_QUOTA, GIVE_TO_MINT_TOKEN_TYPE, HISTORICAL_CLAIM_TRUST_BOOST_BPS, MAX_ACTIVE_SPONSORED_BADGE_MINT_QUOTA, MAX_CHECKPOINT_VOUCHERS_PER_BATCH, MAX_CUSTOM_TOKEN_EPOCH_ALLOWANCE, MAX_CUSTOM_TOKEN_HISTORICAL_CLAIM_CAP, MAX_EPOCH_FORWARD_DRIFT, MAX_HISTORICAL_KARMA_PER_VERIFIED_ITEM, MAX_SPONSORED_BADGE_MINT_QUOTA_PER_GRANT, MAX_TOTAL_CITATION_SHARE_BPS, MAX_UPSTREAM_CITATIONS, MIN_GIVE_TO_MINT_DUST_FLOOR, MIN_GIVE_TO_MINT_TOKEN_CREATION_FEE, MIN_KARMA_FOR_THANK_YOU_BADGE, OcapGiveToMintEngine, RECIPROCAL_RING_DAMPING_BPS, computeArcSpaceCheckpointRoot, computeArcSpaceVoucherDigest, computeHistoricalClaimNullifier, computeNftPayloadCommitmentDigest, deriveCompanionMedalDid, deriveThankYouBadgeDid };
|