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