@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,160 @@
|
|
|
1
|
+
//#region src/appchain-sovereign-hub.d.ts
|
|
2
|
+
declare const MAX_FREE_RELAY_CREDITS_PER_EPOCH = 1000000;
|
|
3
|
+
/**
|
|
4
|
+
* Deterministically derives the Sovereign Reserve Vault DID for a given `spokeChainDid`
|
|
5
|
+
* (Polkadot XCM Sovereign Account model).
|
|
6
|
+
*/
|
|
7
|
+
declare function deriveSovereignVaultDid(spokeChainDid: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* Computes the deterministic VLedger state root transition commitment:
|
|
10
|
+
* `SHA3-256("ocap:vledger-checkpoint:v1:" + spoke.length + ":" + spokeChainDid + ":" + blockHeight + ":" + prevStateRoot + ":" + stateDiffMerkleRoot)`
|
|
11
|
+
*/
|
|
12
|
+
declare function computeVLedgerCheckpointStateRoot(params: {
|
|
13
|
+
spokeChainDid: string;
|
|
14
|
+
blockHeight: number;
|
|
15
|
+
prevStateRoot: string;
|
|
16
|
+
stateDiffMerkleRoot: string;
|
|
17
|
+
}): string;
|
|
18
|
+
interface SovereignReserveState {
|
|
19
|
+
spokeChainDid: string;
|
|
20
|
+
sovereignVaultDid: string;
|
|
21
|
+
tokens: Record<string, string>;
|
|
22
|
+
nfts: string[];
|
|
23
|
+
lastCheckpointedHeight: number;
|
|
24
|
+
currentStateRoot: string;
|
|
25
|
+
registeredValidators: string[];
|
|
26
|
+
}
|
|
27
|
+
interface CrowdloanContributorPosition {
|
|
28
|
+
contributorDid: string;
|
|
29
|
+
stakedAbt: string;
|
|
30
|
+
rewardDebtScaled: string;
|
|
31
|
+
accruedUnclaimedRewards: string;
|
|
32
|
+
}
|
|
33
|
+
interface SpokeCrowdloanState {
|
|
34
|
+
spokeChainDid: string;
|
|
35
|
+
totalStakedAbt: string;
|
|
36
|
+
accRewardPerShareScaled: string;
|
|
37
|
+
unclaimedRewardReserveAbt: string;
|
|
38
|
+
freeRelayCreditsPerEpoch: number;
|
|
39
|
+
remainingEpochRelayCredits: number;
|
|
40
|
+
contributors: Record<string, CrowdloanContributorPosition>;
|
|
41
|
+
}
|
|
42
|
+
interface VLedgerCheckpointInput {
|
|
43
|
+
spokeChainDid: string;
|
|
44
|
+
blockHeight: number;
|
|
45
|
+
prevStateRoot: string;
|
|
46
|
+
stateDiffMerkleRoot: string;
|
|
47
|
+
newStateRoot: string;
|
|
48
|
+
validatorSigners: string[];
|
|
49
|
+
}
|
|
50
|
+
interface PfmCrossSpokePacketInput {
|
|
51
|
+
packetId: string;
|
|
52
|
+
senderDid: string;
|
|
53
|
+
recipientDid: string;
|
|
54
|
+
/** Must be `[originSpokeDid, arcHubDid, destinationSpokeDid]` */
|
|
55
|
+
hopRoute: [string, string, string];
|
|
56
|
+
tokenIn: string;
|
|
57
|
+
amountIn: string;
|
|
58
|
+
tokenOut: string;
|
|
59
|
+
quotedAmountOut: string;
|
|
60
|
+
minAmountOut: string;
|
|
61
|
+
ofacBlocklist?: Iterable<string>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Polkadot XCM Sovereign Reserve Vault + Crowdloan Quota Staking + VLedger Checkpoint + Cosmos PFM Multi-Hop Hub Engine (#1173).
|
|
65
|
+
*/
|
|
66
|
+
declare class OcapSovereignAppChainHubEngine {
|
|
67
|
+
readonly arcHubDid: string;
|
|
68
|
+
readonly abtTokenAddress: string;
|
|
69
|
+
readonly relayCreditsPerAbtUnit: number;
|
|
70
|
+
private readonly reserves;
|
|
71
|
+
private readonly crowdloans;
|
|
72
|
+
private readonly hubAmmReserves;
|
|
73
|
+
private readonly consumedPacketIds;
|
|
74
|
+
private readonly ofacSet;
|
|
75
|
+
constructor(options: {
|
|
76
|
+
arcHubDid: string;
|
|
77
|
+
abtTokenAddress: string;
|
|
78
|
+
relayCreditsPerAbtUnit?: number;
|
|
79
|
+
ofacBlocklist?: Iterable<string>;
|
|
80
|
+
});
|
|
81
|
+
/**
|
|
82
|
+
* Registers an isomorphic Spoke AppChain with its own isolated `SovereignReserveState` and validator set.
|
|
83
|
+
*/
|
|
84
|
+
registerSpokeChain(params: {
|
|
85
|
+
spokeChainDid: string;
|
|
86
|
+
genesisStateRoot: string;
|
|
87
|
+
validators: string[];
|
|
88
|
+
initialTokens?: Record<string, string>;
|
|
89
|
+
initialNfts?: string[];
|
|
90
|
+
}): SovereignReserveState;
|
|
91
|
+
/**
|
|
92
|
+
* Seeds Hub AMM liquidity for cross-spoke token conversion during Cosmos PFM multi-hop routing.
|
|
93
|
+
*/
|
|
94
|
+
seedHubSwapLiquidity(tokenAddress: string, amount: string): void;
|
|
95
|
+
/**
|
|
96
|
+
* Deposits fungible tokens into a Spoke's `SovereignReserveState` on `ArcHub`.
|
|
97
|
+
*/
|
|
98
|
+
depositToSpokeReserve(params: {
|
|
99
|
+
spokeChainDid: string;
|
|
100
|
+
tokenAddress: string;
|
|
101
|
+
amount: string;
|
|
102
|
+
}): SovereignReserveState;
|
|
103
|
+
/**
|
|
104
|
+
* Withdraws fungible tokens from a Spoke's `SovereignReserveState` on `ArcHub`.
|
|
105
|
+
* Enforces the Polkadot XCM Sovereign Containment Invariant: a compromised Spoke can NEVER
|
|
106
|
+
* withdraw more than its own `SovereignReserveState` balance.
|
|
107
|
+
*/
|
|
108
|
+
withdrawFromSpokeReserve(params: {
|
|
109
|
+
spokeChainDid: string;
|
|
110
|
+
tokenAddress: string;
|
|
111
|
+
amount: string;
|
|
112
|
+
}): SovereignReserveState;
|
|
113
|
+
/**
|
|
114
|
+
* Polkadot Crowdloan & Agile Coretime `ABT` Quota Staking (`CrowdloanContributeTx`):
|
|
115
|
+
* Locks `ABT` for a target `spokeChainDid`, dynamically increasing its `freeRelayCreditsPerEpoch`
|
|
116
|
+
* and tracking `O(1)` `accRewardPerShare` revenue shares without Sybil split inflation.
|
|
117
|
+
*/
|
|
118
|
+
contributeCrowdloanAbt(params: {
|
|
119
|
+
spokeChainDid: string;
|
|
120
|
+
contributorDid: string;
|
|
121
|
+
abtAmount: string;
|
|
122
|
+
}): SpokeCrowdloanState;
|
|
123
|
+
/**
|
|
124
|
+
* Distributes Spoke business revenue to all Crowdloan `ABT` contributors in `O(1)` time via `accRewardPerShare`.
|
|
125
|
+
* Enforces 100% reserve backing by debiting `revenueAmount` from the Spoke's `SovereignReserveState` `ABT` balance.
|
|
126
|
+
*/
|
|
127
|
+
distributeSpokeRevenue(params: {
|
|
128
|
+
spokeChainDid: string;
|
|
129
|
+
revenueAmount: string;
|
|
130
|
+
}): SpokeCrowdloanState;
|
|
131
|
+
/**
|
|
132
|
+
* Claims accrued Crowdloan business revenue for a contributor in `O(1)` time.
|
|
133
|
+
*/
|
|
134
|
+
claimCrowdloanRewards(params: {
|
|
135
|
+
spokeChainDid: string;
|
|
136
|
+
contributorDid: string;
|
|
137
|
+
}): {
|
|
138
|
+
claimedAmount: string;
|
|
139
|
+
contributorPosition: CrowdloanContributorPosition;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* Verifies a Spoke's `CheckpointRollupTx` using both `2f + 1` Validator Quorum and VLedger incremental
|
|
143
|
+
* state-root transition commitment (`prevStateRoot -> newStateRoot`).
|
|
144
|
+
*/
|
|
145
|
+
verifyAndApplySpokeCheckpoint(input: VLedgerCheckpointInput): SovereignReserveState;
|
|
146
|
+
/**
|
|
147
|
+
* Cosmos PFM (Packet Forward Middleware) Atomic Multi-Hop Cross-Spoke Routing (`Spoke A -> ArcHub -> Spoke B`):
|
|
148
|
+
* Atomically verifies `Spoke A` reserve solvency, consumes 1 Crowdloan free relay credit,
|
|
149
|
+
* executes optional Hub token conversion (`tokenIn -> tokenOut` with `minAmountOut` slippage guard),
|
|
150
|
+
* and credits `Spoke B`'s `SovereignReserveState`.
|
|
151
|
+
*/
|
|
152
|
+
executeForwardCrossSpokePacket(input: PfmCrossSpokePacketInput): {
|
|
153
|
+
originReserve: SovereignReserveState;
|
|
154
|
+
destinationReserve: SovereignReserveState;
|
|
155
|
+
remainingOriginRelayCredits: number;
|
|
156
|
+
};
|
|
157
|
+
getSpokeReserve(spokeChainDid: string): SovereignReserveState | undefined;
|
|
158
|
+
}
|
|
159
|
+
//#endregion
|
|
160
|
+
export { CrowdloanContributorPosition, MAX_FREE_RELAY_CREDITS_PER_EPOCH, OcapSovereignAppChainHubEngine, PfmCrossSpokePacketInput, SovereignReserveState, SpokeCrowdloanState, VLedgerCheckpointInput, computeVLedgerCheckpointStateRoot, deriveSovereignVaultDid };
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { assertNotOfacSanctioned, normalizeScreeningAddress } from "./ofac-screening.mjs";
|
|
2
|
+
import "./uniswap-router.mjs";
|
|
3
|
+
import { Hasher } from "@ocap/mcrypto";
|
|
4
|
+
import { BN } from "@ocap/util";
|
|
5
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
6
|
+
|
|
7
|
+
//#region src/appchain-sovereign-hub.ts
|
|
8
|
+
const FORBIDDEN_KEYS = new Set([
|
|
9
|
+
"__proto__",
|
|
10
|
+
"constructor",
|
|
11
|
+
"prototype"
|
|
12
|
+
]);
|
|
13
|
+
const CANONICAL_UINT_REGEX = /^\d+$/;
|
|
14
|
+
const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
|
|
15
|
+
const ACC_PRECISION = new BN("1000000000000000000", 10);
|
|
16
|
+
const MAX_FREE_RELAY_CREDITS_PER_EPOCH = 1e6;
|
|
17
|
+
const MAX_FREE_RELAY_CREDITS_BN = new BN(MAX_FREE_RELAY_CREDITS_PER_EPOCH);
|
|
18
|
+
function assertSafeId(val, label) {
|
|
19
|
+
if (typeof val !== "string") throw new CustomError("INVALID_SOVEREIGN_HUB", `${label} must be a non-empty string`);
|
|
20
|
+
const trimmed = val.trim();
|
|
21
|
+
if (!trimmed || FORBIDDEN_KEYS.has(trimmed)) throw new CustomError("INVALID_SOVEREIGN_HUB", `Invalid or unsafe ${label}`);
|
|
22
|
+
return trimmed;
|
|
23
|
+
}
|
|
24
|
+
function normalizeDelimiterSafeId(val, label) {
|
|
25
|
+
const normalized = normalizeScreeningAddress(assertSafeId(val, label));
|
|
26
|
+
if (normalized.includes(":") || normalized.includes("|")) throw new CustomError("INVALID_SOVEREIGN_HUB", `${label} must not contain reserved delimiter characters (':' or '|') after normalization`);
|
|
27
|
+
return normalized;
|
|
28
|
+
}
|
|
29
|
+
function parsePositiveBn(val, label) {
|
|
30
|
+
if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new CustomError("INVALID_SOVEREIGN_HUB", `${label} must be a canonical base-10 integer string`);
|
|
31
|
+
const bn = new BN(val, 10);
|
|
32
|
+
if (bn.lte(new BN(0))) throw new CustomError("INVALID_SOVEREIGN_HUB", `${label} must be strictly positive`);
|
|
33
|
+
return bn;
|
|
34
|
+
}
|
|
35
|
+
function parseNonNegativeBn(val, label) {
|
|
36
|
+
if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new CustomError("INVALID_SOVEREIGN_HUB", `${label} must be a canonical non-negative integer string`);
|
|
37
|
+
return new BN(val, 10);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Deterministically derives the Sovereign Reserve Vault DID for a given `spokeChainDid`
|
|
41
|
+
* (Polkadot XCM Sovereign Account model).
|
|
42
|
+
*/
|
|
43
|
+
function deriveSovereignVaultDid(spokeChainDid) {
|
|
44
|
+
const normalizedSpoke = normalizeDelimiterSafeId(spokeChainDid, "spokeChainDid");
|
|
45
|
+
return `zSovVault_${Hasher.SHA3.hash256(Buffer.from(`ocap:sovereign-reserve:v1:${normalizedSpoke.length}:${normalizedSpoke}`, "utf8")).replace(/^0x/, "").slice(0, 36).toLowerCase()}`;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Computes the deterministic VLedger state root transition commitment:
|
|
49
|
+
* `SHA3-256("ocap:vledger-checkpoint:v1:" + spoke.length + ":" + spokeChainDid + ":" + blockHeight + ":" + prevStateRoot + ":" + stateDiffMerkleRoot)`
|
|
50
|
+
*/
|
|
51
|
+
function computeVLedgerCheckpointStateRoot(params) {
|
|
52
|
+
const spoke = normalizeDelimiterSafeId(params.spokeChainDid, "spokeChainDid");
|
|
53
|
+
if (!Number.isSafeInteger(params.blockHeight) || params.blockHeight <= 0) throw new CustomError("INVALID_SOVEREIGN_HUB", "blockHeight must be a positive safe integer");
|
|
54
|
+
if (typeof params.prevStateRoot !== "string" || !BYTES32_HEX_REGEX.test(params.prevStateRoot)) throw new CustomError("INVALID_SOVEREIGN_HUB", "prevStateRoot must be a 32-byte 0x hex string");
|
|
55
|
+
if (typeof params.stateDiffMerkleRoot !== "string" || !BYTES32_HEX_REGEX.test(params.stateDiffMerkleRoot)) throw new CustomError("INVALID_SOVEREIGN_HUB", "stateDiffMerkleRoot must be a 32-byte 0x hex string");
|
|
56
|
+
const payload = `ocap:vledger-checkpoint:v1:${spoke.length}:${spoke}:${params.blockHeight}:${params.prevStateRoot.toLowerCase()}:${params.stateDiffMerkleRoot.toLowerCase()}`;
|
|
57
|
+
return `0x${Hasher.SHA3.hash256(Buffer.from(payload, "utf8")).replace(/^0x/, "").toLowerCase()}`;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Polkadot XCM Sovereign Reserve Vault + Crowdloan Quota Staking + VLedger Checkpoint + Cosmos PFM Multi-Hop Hub Engine (#1173).
|
|
61
|
+
*/
|
|
62
|
+
var OcapSovereignAppChainHubEngine = class {
|
|
63
|
+
constructor(options) {
|
|
64
|
+
this.reserves = /* @__PURE__ */ new Map();
|
|
65
|
+
this.crowdloans = /* @__PURE__ */ new Map();
|
|
66
|
+
this.hubAmmReserves = /* @__PURE__ */ new Map();
|
|
67
|
+
this.consumedPacketIds = /* @__PURE__ */ new Set();
|
|
68
|
+
this.ofacSet = /* @__PURE__ */ new Set();
|
|
69
|
+
if (!options || typeof options !== "object") throw new CustomError("INVALID_SOVEREIGN_HUB", "Missing OcapSovereignAppChainHubEngine options");
|
|
70
|
+
this.arcHubDid = normalizeScreeningAddress(assertSafeId(options.arcHubDid, "arcHubDid"));
|
|
71
|
+
this.abtTokenAddress = normalizeScreeningAddress(assertSafeId(options.abtTokenAddress, "abtTokenAddress"));
|
|
72
|
+
const creditsPerUnit = options.relayCreditsPerAbtUnit ?? 10;
|
|
73
|
+
if (!Number.isSafeInteger(creditsPerUnit) || creditsPerUnit <= 0 || creditsPerUnit > 1e4) throw new CustomError("INVALID_SOVEREIGN_HUB", "relayCreditsPerAbtUnit must be an integer between 1 and 10000");
|
|
74
|
+
this.relayCreditsPerAbtUnit = creditsPerUnit;
|
|
75
|
+
if (options.ofacBlocklist) for (const a of options.ofacBlocklist) this.ofacSet.add(normalizeScreeningAddress(a));
|
|
76
|
+
assertNotOfacSanctioned([this.arcHubDid, this.abtTokenAddress], this.ofacSet);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Registers an isomorphic Spoke AppChain with its own isolated `SovereignReserveState` and validator set.
|
|
80
|
+
*/
|
|
81
|
+
registerSpokeChain(params) {
|
|
82
|
+
const spokeChainDid = normalizeScreeningAddress(assertSafeId(params.spokeChainDid, "spokeChainDid"));
|
|
83
|
+
if (spokeChainDid === this.arcHubDid) throw new CustomError("INVALID_SOVEREIGN_HUB", "spokeChainDid cannot equal arcHubDid");
|
|
84
|
+
if (this.reserves.has(spokeChainDid)) throw new CustomError("DUPLICATE_SPOKE_CHAIN", `Spoke chain ${spokeChainDid} is already registered`);
|
|
85
|
+
if (typeof params.genesisStateRoot !== "string" || !BYTES32_HEX_REGEX.test(params.genesisStateRoot)) throw new CustomError("INVALID_SOVEREIGN_HUB", "genesisStateRoot must be a 32-byte 0x hex string");
|
|
86
|
+
if (!Array.isArray(params.validators) || params.validators.length === 0) throw new CustomError("INVALID_SOVEREIGN_HUB", "validators must be a non-empty array");
|
|
87
|
+
const normalizedValidators = Array.from(new Set(params.validators.map((v, i) => normalizeScreeningAddress(assertSafeId(v, `validators[${i}]`)))));
|
|
88
|
+
if (normalizedValidators.length !== params.validators.length) throw new CustomError("INVALID_SOVEREIGN_HUB", "validators must not contain duplicate DIDs");
|
|
89
|
+
assertNotOfacSanctioned([spokeChainDid, ...normalizedValidators], this.ofacSet);
|
|
90
|
+
const tokens = {};
|
|
91
|
+
for (const [k, v] of Object.entries(params.initialTokens || {})) {
|
|
92
|
+
const tokAddr = normalizeScreeningAddress(assertSafeId(k, "tokenAddress"));
|
|
93
|
+
tokens[tokAddr] = parseNonNegativeBn(v, `initialTokens[${tokAddr}]`).toString(10);
|
|
94
|
+
}
|
|
95
|
+
const nfts = Array.from(new Set((params.initialNfts || []).map((n, idx) => normalizeScreeningAddress(assertSafeId(n, `initialNfts[${idx}]`)))));
|
|
96
|
+
const state = {
|
|
97
|
+
spokeChainDid,
|
|
98
|
+
sovereignVaultDid: deriveSovereignVaultDid(spokeChainDid),
|
|
99
|
+
tokens,
|
|
100
|
+
nfts,
|
|
101
|
+
lastCheckpointedHeight: 0,
|
|
102
|
+
currentStateRoot: params.genesisStateRoot.toLowerCase(),
|
|
103
|
+
registeredValidators: normalizedValidators
|
|
104
|
+
};
|
|
105
|
+
this.reserves.set(spokeChainDid, state);
|
|
106
|
+
this.crowdloans.set(spokeChainDid, {
|
|
107
|
+
spokeChainDid,
|
|
108
|
+
totalStakedAbt: "0",
|
|
109
|
+
accRewardPerShareScaled: "0",
|
|
110
|
+
unclaimedRewardReserveAbt: "0",
|
|
111
|
+
freeRelayCreditsPerEpoch: 0,
|
|
112
|
+
remainingEpochRelayCredits: 0,
|
|
113
|
+
contributors: {}
|
|
114
|
+
});
|
|
115
|
+
return JSON.parse(JSON.stringify(state));
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Seeds Hub AMM liquidity for cross-spoke token conversion during Cosmos PFM multi-hop routing.
|
|
119
|
+
*/
|
|
120
|
+
seedHubSwapLiquidity(tokenAddress, amount) {
|
|
121
|
+
const tok = normalizeScreeningAddress(assertSafeId(tokenAddress, "tokenAddress"));
|
|
122
|
+
const amtBn = parsePositiveBn(amount, "amount");
|
|
123
|
+
const cur = this.hubAmmReserves.get(tok) || new BN(0);
|
|
124
|
+
this.hubAmmReserves.set(tok, cur.add(amtBn));
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Deposits fungible tokens into a Spoke's `SovereignReserveState` on `ArcHub`.
|
|
128
|
+
*/
|
|
129
|
+
depositToSpokeReserve(params) {
|
|
130
|
+
const spoke = normalizeScreeningAddress(assertSafeId(params.spokeChainDid, "spokeChainDid"));
|
|
131
|
+
const reserve = this.reserves.get(spoke);
|
|
132
|
+
if (!reserve) throw new CustomError("NOT_FOUND", `Spoke chain ${spoke} not found`);
|
|
133
|
+
const tok = normalizeScreeningAddress(assertSafeId(params.tokenAddress, "tokenAddress"));
|
|
134
|
+
const amtBn = parsePositiveBn(params.amount, "amount");
|
|
135
|
+
const cur = new BN(Object.hasOwn(reserve.tokens, tok) ? reserve.tokens[tok] : "0", 10);
|
|
136
|
+
reserve.tokens[tok] = cur.add(amtBn).toString(10);
|
|
137
|
+
return JSON.parse(JSON.stringify(reserve));
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Withdraws fungible tokens from a Spoke's `SovereignReserveState` on `ArcHub`.
|
|
141
|
+
* Enforces the Polkadot XCM Sovereign Containment Invariant: a compromised Spoke can NEVER
|
|
142
|
+
* withdraw more than its own `SovereignReserveState` balance.
|
|
143
|
+
*/
|
|
144
|
+
withdrawFromSpokeReserve(params) {
|
|
145
|
+
const spoke = normalizeScreeningAddress(assertSafeId(params.spokeChainDid, "spokeChainDid"));
|
|
146
|
+
const reserve = this.reserves.get(spoke);
|
|
147
|
+
if (!reserve) throw new CustomError("NOT_FOUND", `Spoke chain ${spoke} not found`);
|
|
148
|
+
const tok = normalizeScreeningAddress(assertSafeId(params.tokenAddress, "tokenAddress"));
|
|
149
|
+
const amtBn = parsePositiveBn(params.amount, "amount");
|
|
150
|
+
const cur = new BN(Object.hasOwn(reserve.tokens, tok) ? reserve.tokens[tok] : "0", 10);
|
|
151
|
+
if (cur.lt(amtBn)) throw new CustomError("SOVEREIGN_RESERVE_EXCEEDED", `Spoke ${spoke} attempted to withdraw ${amtBn.toString(10)} of ${tok}, exceeding its SovereignReserveState balance (${cur.toString(10)})`);
|
|
152
|
+
reserve.tokens[tok] = cur.sub(amtBn).toString(10);
|
|
153
|
+
return JSON.parse(JSON.stringify(reserve));
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Polkadot Crowdloan & Agile Coretime `ABT` Quota Staking (`CrowdloanContributeTx`):
|
|
157
|
+
* Locks `ABT` for a target `spokeChainDid`, dynamically increasing its `freeRelayCreditsPerEpoch`
|
|
158
|
+
* and tracking `O(1)` `accRewardPerShare` revenue shares without Sybil split inflation.
|
|
159
|
+
*/
|
|
160
|
+
contributeCrowdloanAbt(params) {
|
|
161
|
+
const spoke = normalizeScreeningAddress(assertSafeId(params.spokeChainDid, "spokeChainDid"));
|
|
162
|
+
const contributor = normalizeScreeningAddress(assertSafeId(params.contributorDid, "contributorDid"));
|
|
163
|
+
assertNotOfacSanctioned([spoke, contributor], this.ofacSet);
|
|
164
|
+
const pool = this.crowdloans.get(spoke);
|
|
165
|
+
if (!pool) throw new CustomError("NOT_FOUND", `Spoke chain ${spoke} not found`);
|
|
166
|
+
const addAmtBn = parsePositiveBn(params.abtAmount, "abtAmount");
|
|
167
|
+
const accBn = new BN(pool.accRewardPerShareScaled, 10);
|
|
168
|
+
const existing = Object.hasOwn(pool.contributors, contributor) ? pool.contributors[contributor] : {
|
|
169
|
+
contributorDid: contributor,
|
|
170
|
+
stakedAbt: "0",
|
|
171
|
+
rewardDebtScaled: "0",
|
|
172
|
+
accruedUnclaimedRewards: "0"
|
|
173
|
+
};
|
|
174
|
+
const prevStakeBn = new BN(existing.stakedAbt, 10);
|
|
175
|
+
const prevDebtScaledBn = new BN(existing.rewardDebtScaled, 10);
|
|
176
|
+
const prevAccruedBn = new BN(existing.accruedUnclaimedRewards, 10);
|
|
177
|
+
const pendingBn = prevStakeBn.mul(accBn).sub(prevDebtScaledBn).div(ACC_PRECISION);
|
|
178
|
+
const nextStakeBn = prevStakeBn.add(addAmtBn);
|
|
179
|
+
const nextDebtScaledBn = nextStakeBn.mul(accBn);
|
|
180
|
+
pool.contributors[contributor] = {
|
|
181
|
+
contributorDid: contributor,
|
|
182
|
+
stakedAbt: nextStakeBn.toString(10),
|
|
183
|
+
rewardDebtScaled: nextDebtScaledBn.toString(10),
|
|
184
|
+
accruedUnclaimedRewards: prevAccruedBn.add(pendingBn).toString(10)
|
|
185
|
+
};
|
|
186
|
+
const nextTotalStakedBn = new BN(pool.totalStakedAbt, 10).add(addAmtBn);
|
|
187
|
+
pool.totalStakedAbt = nextTotalStakedBn.toString(10);
|
|
188
|
+
const totalCreditsBn = nextTotalStakedBn.muln(this.relayCreditsPerAbtUnit);
|
|
189
|
+
const cappedTotalCredits = (totalCreditsBn.gt(MAX_FREE_RELAY_CREDITS_BN) ? MAX_FREE_RELAY_CREDITS_BN : totalCreditsBn).toNumber();
|
|
190
|
+
const addedCredits = Math.max(0, cappedTotalCredits - pool.freeRelayCreditsPerEpoch);
|
|
191
|
+
pool.freeRelayCreditsPerEpoch = cappedTotalCredits;
|
|
192
|
+
pool.remainingEpochRelayCredits = Math.min(MAX_FREE_RELAY_CREDITS_PER_EPOCH, pool.remainingEpochRelayCredits + addedCredits);
|
|
193
|
+
return JSON.parse(JSON.stringify(pool));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Distributes Spoke business revenue to all Crowdloan `ABT` contributors in `O(1)` time via `accRewardPerShare`.
|
|
197
|
+
* Enforces 100% reserve backing by debiting `revenueAmount` from the Spoke's `SovereignReserveState` `ABT` balance.
|
|
198
|
+
*/
|
|
199
|
+
distributeSpokeRevenue(params) {
|
|
200
|
+
const spoke = normalizeScreeningAddress(assertSafeId(params.spokeChainDid, "spokeChainDid"));
|
|
201
|
+
const pool = this.crowdloans.get(spoke);
|
|
202
|
+
const reserve = this.reserves.get(spoke);
|
|
203
|
+
if (!pool || !reserve) throw new CustomError("NOT_FOUND", `Spoke chain ${spoke} not found`);
|
|
204
|
+
const revBn = parsePositiveBn(params.revenueAmount, "revenueAmount");
|
|
205
|
+
const totalStakedBn = new BN(pool.totalStakedAbt, 10);
|
|
206
|
+
if (totalStakedBn.isZero()) throw new CustomError("EMPTY_CROWDLOAN_POOL", `Cannot distribute revenue when Spoke ${spoke} has 0 staked ABT`);
|
|
207
|
+
const reserveAbtBn = new BN(Object.hasOwn(reserve.tokens, this.abtTokenAddress) ? reserve.tokens[this.abtTokenAddress] : "0", 10);
|
|
208
|
+
if (reserveAbtBn.lt(revBn)) throw new CustomError("UNBACKED_SPOKE_REVENUE", `Spoke ${spoke} lacks SovereignReserveState ABT (${reserveAbtBn.toString(10)}) to back revenue distribution (${revBn.toString(10)})`);
|
|
209
|
+
const deltaAccScaled = revBn.mul(ACC_PRECISION).div(totalStakedBn);
|
|
210
|
+
if (deltaAccScaled.isZero()) throw new CustomError("REVENUE_TOO_SMALL_FOR_PRECISION", `Revenue amount (${revBn.toString(10)}) is too small relative to totalStakedAbt (${totalStakedBn.toString(10)}) and would round to 0`);
|
|
211
|
+
reserve.tokens[this.abtTokenAddress] = reserveAbtBn.sub(revBn).toString(10);
|
|
212
|
+
pool.unclaimedRewardReserveAbt = new BN(pool.unclaimedRewardReserveAbt, 10).add(revBn).toString(10);
|
|
213
|
+
pool.accRewardPerShareScaled = new BN(pool.accRewardPerShareScaled, 10).add(deltaAccScaled).toString(10);
|
|
214
|
+
return JSON.parse(JSON.stringify(pool));
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Claims accrued Crowdloan business revenue for a contributor in `O(1)` time.
|
|
218
|
+
*/
|
|
219
|
+
claimCrowdloanRewards(params) {
|
|
220
|
+
const spoke = normalizeScreeningAddress(assertSafeId(params.spokeChainDid, "spokeChainDid"));
|
|
221
|
+
const contributor = normalizeScreeningAddress(assertSafeId(params.contributorDid, "contributorDid"));
|
|
222
|
+
const pool = this.crowdloans.get(spoke);
|
|
223
|
+
if (!pool) throw new CustomError("NOT_FOUND", `Spoke chain ${spoke} not found`);
|
|
224
|
+
const pos = Object.hasOwn(pool.contributors, contributor) ? pool.contributors[contributor] : void 0;
|
|
225
|
+
if (!pos) throw new CustomError("NOT_FOUND", `Contributor ${contributor} not found in Spoke ${spoke} crowdloan`);
|
|
226
|
+
const stakeBn = new BN(pos.stakedAbt, 10);
|
|
227
|
+
const accBn = new BN(pool.accRewardPerShareScaled, 10);
|
|
228
|
+
const debtScaledBn = new BN(pos.rewardDebtScaled, 10);
|
|
229
|
+
const accruedBn = new BN(pos.accruedUnclaimedRewards, 10);
|
|
230
|
+
const newlyEarnedBn = stakeBn.mul(accBn).sub(debtScaledBn).div(ACC_PRECISION);
|
|
231
|
+
const totalClaimableBn = accruedBn.add(newlyEarnedBn);
|
|
232
|
+
const unclaimedReserveBn = new BN(pool.unclaimedRewardReserveAbt, 10);
|
|
233
|
+
if (unclaimedReserveBn.lt(totalClaimableBn)) throw new CustomError("INSUFFICIENT_REWARD_RESERVE", "Insufficient unclaimed reward reserve");
|
|
234
|
+
pool.unclaimedRewardReserveAbt = unclaimedReserveBn.sub(totalClaimableBn).toString(10);
|
|
235
|
+
pos.rewardDebtScaled = stakeBn.mul(accBn).toString(10);
|
|
236
|
+
pos.accruedUnclaimedRewards = "0";
|
|
237
|
+
return {
|
|
238
|
+
claimedAmount: totalClaimableBn.toString(10),
|
|
239
|
+
contributorPosition: { ...pos }
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Verifies a Spoke's `CheckpointRollupTx` using both `2f + 1` Validator Quorum and VLedger incremental
|
|
244
|
+
* state-root transition commitment (`prevStateRoot -> newStateRoot`).
|
|
245
|
+
*/
|
|
246
|
+
verifyAndApplySpokeCheckpoint(input) {
|
|
247
|
+
if (!input || typeof input !== "object") throw new CustomError("INVALID_SOVEREIGN_HUB", "Missing VLedgerCheckpointInput");
|
|
248
|
+
const spoke = normalizeScreeningAddress(assertSafeId(input.spokeChainDid, "spokeChainDid"));
|
|
249
|
+
const reserve = this.reserves.get(spoke);
|
|
250
|
+
if (!reserve) throw new CustomError("NOT_FOUND", `Spoke chain ${spoke} not found`);
|
|
251
|
+
if (!Number.isSafeInteger(input.blockHeight) || input.blockHeight <= reserve.lastCheckpointedHeight) throw new CustomError("STALE_CHECKPOINT_HEIGHT", `Checkpoint height (${input.blockHeight}) must be strictly greater than lastCheckpointedHeight (${reserve.lastCheckpointedHeight})`);
|
|
252
|
+
if (typeof input.prevStateRoot !== "string" || input.prevStateRoot.toLowerCase() !== reserve.currentStateRoot) throw new CustomError("STATE_ROOT_DISCONTINUITY", `Checkpoint prevStateRoot (${input.prevStateRoot}) does not match currentStateRoot (${reserve.currentStateRoot})`);
|
|
253
|
+
const expectedNewRoot = computeVLedgerCheckpointStateRoot({
|
|
254
|
+
spokeChainDid: spoke,
|
|
255
|
+
blockHeight: input.blockHeight,
|
|
256
|
+
prevStateRoot: input.prevStateRoot,
|
|
257
|
+
stateDiffMerkleRoot: input.stateDiffMerkleRoot
|
|
258
|
+
});
|
|
259
|
+
if (typeof input.newStateRoot !== "string" || input.newStateRoot.toLowerCase() !== expectedNewRoot) throw new CustomError("VLEDGER_COMMITMENT_MISMATCH", `Checkpoint newStateRoot (${input.newStateRoot}) does not match VLedger commitment (${expectedNewRoot})`);
|
|
260
|
+
if (!Array.isArray(input.validatorSigners)) throw new CustomError("INVALID_SOVEREIGN_HUB", "validatorSigners must be an array");
|
|
261
|
+
const registeredSet = new Set(reserve.registeredValidators);
|
|
262
|
+
const validUniqueSigners = /* @__PURE__ */ new Set();
|
|
263
|
+
for (const signer of input.validatorSigners) {
|
|
264
|
+
const norm = normalizeScreeningAddress(assertSafeId(signer, "validatorSigner"));
|
|
265
|
+
if (!registeredSet.has(norm)) throw new CustomError("UNAUTHORIZED_VALIDATOR", `Signer ${norm} is not a registered validator for Spoke ${spoke}`);
|
|
266
|
+
validUniqueSigners.add(norm);
|
|
267
|
+
}
|
|
268
|
+
const minQuorum = Math.floor(2 * reserve.registeredValidators.length / 3) + 1;
|
|
269
|
+
if (validUniqueSigners.size < minQuorum) throw new CustomError("INSUFFICIENT_VALIDATOR_QUORUM", `Checkpoint signed by ${validUniqueSigners.size} validators, fewer than BFT quorum (${minQuorum} of ${reserve.registeredValidators.length})`);
|
|
270
|
+
reserve.lastCheckpointedHeight = input.blockHeight;
|
|
271
|
+
reserve.currentStateRoot = expectedNewRoot;
|
|
272
|
+
return JSON.parse(JSON.stringify(reserve));
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Cosmos PFM (Packet Forward Middleware) Atomic Multi-Hop Cross-Spoke Routing (`Spoke A -> ArcHub -> Spoke B`):
|
|
276
|
+
* Atomically verifies `Spoke A` reserve solvency, consumes 1 Crowdloan free relay credit,
|
|
277
|
+
* executes optional Hub token conversion (`tokenIn -> tokenOut` with `minAmountOut` slippage guard),
|
|
278
|
+
* and credits `Spoke B`'s `SovereignReserveState`.
|
|
279
|
+
*/
|
|
280
|
+
executeForwardCrossSpokePacket(input) {
|
|
281
|
+
if (!input || typeof input !== "object") throw new CustomError("INVALID_PFM_PACKET", "Missing PfmCrossSpokePacketInput");
|
|
282
|
+
const packetId = assertSafeId(input.packetId, "packetId");
|
|
283
|
+
if (this.consumedPacketIds.has(packetId)) throw new CustomError("REPLAYED_PFM_PACKET", `PFM packet ${packetId} has already been processed`);
|
|
284
|
+
if (!Array.isArray(input.hopRoute) || input.hopRoute.length !== 3) throw new CustomError("INVALID_PFM_ROUTE", "hopRoute must be a 3-hop tuple [originSpokeDid, arcHubDid, destinationSpokeDid]");
|
|
285
|
+
const originSpoke = normalizeScreeningAddress(assertSafeId(input.hopRoute[0], "hopRoute[0]"));
|
|
286
|
+
const hubHop = normalizeScreeningAddress(assertSafeId(input.hopRoute[1], "hopRoute[1]"));
|
|
287
|
+
const destSpoke = normalizeScreeningAddress(assertSafeId(input.hopRoute[2], "hopRoute[2]"));
|
|
288
|
+
if (hubHop !== this.arcHubDid) throw new CustomError("INVALID_PFM_ROUTE", `Intermediate hop (${hubHop}) must equal arcHubDid (${this.arcHubDid})`);
|
|
289
|
+
if (originSpoke === destSpoke) throw new CustomError("INVALID_PFM_ROUTE", "originSpokeDid and destinationSpokeDid must be distinct");
|
|
290
|
+
const senderDid = normalizeScreeningAddress(assertSafeId(input.senderDid, "senderDid"));
|
|
291
|
+
const recipientDid = normalizeScreeningAddress(assertSafeId(input.recipientDid, "recipientDid"));
|
|
292
|
+
const tokenIn = normalizeScreeningAddress(assertSafeId(input.tokenIn, "tokenIn"));
|
|
293
|
+
const tokenOut = normalizeScreeningAddress(assertSafeId(input.tokenOut, "tokenOut"));
|
|
294
|
+
const combinedOfac = new Set(this.ofacSet);
|
|
295
|
+
if (input.ofacBlocklist) for (const a of input.ofacBlocklist) combinedOfac.add(normalizeScreeningAddress(a));
|
|
296
|
+
assertNotOfacSanctioned([
|
|
297
|
+
originSpoke,
|
|
298
|
+
destSpoke,
|
|
299
|
+
senderDid,
|
|
300
|
+
recipientDid,
|
|
301
|
+
tokenIn,
|
|
302
|
+
tokenOut
|
|
303
|
+
], combinedOfac);
|
|
304
|
+
const originReserve = this.reserves.get(originSpoke);
|
|
305
|
+
const destReserve = this.reserves.get(destSpoke);
|
|
306
|
+
if (!originReserve) throw new CustomError("NOT_FOUND", `Origin Spoke ${originSpoke} not found`);
|
|
307
|
+
if (!destReserve) throw new CustomError("NOT_FOUND", `Destination Spoke ${destSpoke} not found`);
|
|
308
|
+
const originCrowdloan = this.crowdloans.get(originSpoke);
|
|
309
|
+
if (originCrowdloan.remainingEpochRelayCredits <= 0) throw new CustomError("INSUFFICIENT_RELAY_QUOTA", `Origin Spoke ${originSpoke} has exhausted its Crowdloan freeRelayCreditsPerEpoch`);
|
|
310
|
+
const amountInBn = parsePositiveBn(input.amountIn, "amountIn");
|
|
311
|
+
const quotedOutBn = parsePositiveBn(input.quotedAmountOut, "quotedAmountOut");
|
|
312
|
+
const minOutBn = parsePositiveBn(input.minAmountOut, "minAmountOut");
|
|
313
|
+
if (quotedOutBn.lt(minOutBn)) throw new CustomError("PFM_SLIPPAGE_EXCEEDED", `quotedAmountOut (${quotedOutBn.toString(10)}) is below minAmountOut (${minOutBn.toString(10)})`);
|
|
314
|
+
const originAvailBn = new BN(Object.hasOwn(originReserve.tokens, tokenIn) ? originReserve.tokens[tokenIn] : "0", 10);
|
|
315
|
+
if (originAvailBn.lt(amountInBn)) throw new CustomError("SOVEREIGN_RESERVE_EXCEEDED", `Origin Spoke ${originSpoke} has insufficient SovereignReserveState balance (${originAvailBn.toString(10)}) for ${amountInBn.toString(10)} ${tokenIn}`);
|
|
316
|
+
if (tokenIn === tokenOut) {
|
|
317
|
+
if (!quotedOutBn.eq(amountInBn)) throw new CustomError("INVALID_PFM_SWAP", "Same-token PFM forwarding requires quotedAmountOut === amountIn");
|
|
318
|
+
} else {
|
|
319
|
+
const hubAvailOut = this.hubAmmReserves.get(tokenOut) || new BN(0);
|
|
320
|
+
if (hubAvailOut.lt(quotedOutBn)) throw new CustomError("INSUFFICIENT_HUB_SWAP_LIQUIDITY", `ArcHub lacks ${tokenOut} liquidity (${hubAvailOut.toString(10)}) for cross-spoke swap (${quotedOutBn.toString(10)})`);
|
|
321
|
+
const hubCurIn = this.hubAmmReserves.get(tokenIn) || new BN(0);
|
|
322
|
+
if (!hubCurIn.isZero()) {
|
|
323
|
+
const maxConstantProductOut = hubAvailOut.mul(amountInBn).div(hubCurIn.add(amountInBn));
|
|
324
|
+
if (quotedOutBn.gt(maxConstantProductOut)) throw new CustomError("AMM_INVARIANT_VIOLATION", `Quoted output (${quotedOutBn.toString(10)}) exceeds constant-product AMM bound (${maxConstantProductOut.toString(10)})`);
|
|
325
|
+
}
|
|
326
|
+
this.hubAmmReserves.set(tokenIn, hubCurIn.add(amountInBn));
|
|
327
|
+
this.hubAmmReserves.set(tokenOut, hubAvailOut.sub(quotedOutBn));
|
|
328
|
+
}
|
|
329
|
+
originReserve.tokens[tokenIn] = originAvailBn.sub(amountInBn).toString(10);
|
|
330
|
+
const destCurOutBn = new BN(Object.hasOwn(destReserve.tokens, tokenOut) ? destReserve.tokens[tokenOut] : "0", 10);
|
|
331
|
+
destReserve.tokens[tokenOut] = destCurOutBn.add(quotedOutBn).toString(10);
|
|
332
|
+
originCrowdloan.remainingEpochRelayCredits -= 1;
|
|
333
|
+
this.consumedPacketIds.add(packetId);
|
|
334
|
+
return {
|
|
335
|
+
originReserve: JSON.parse(JSON.stringify(originReserve)),
|
|
336
|
+
destinationReserve: JSON.parse(JSON.stringify(destReserve)),
|
|
337
|
+
remainingOriginRelayCredits: originCrowdloan.remainingEpochRelayCredits
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
getSpokeReserve(spokeChainDid) {
|
|
341
|
+
const spoke = normalizeScreeningAddress(assertSafeId(spokeChainDid, "spokeChainDid"));
|
|
342
|
+
const r = this.reserves.get(spoke);
|
|
343
|
+
return r ? JSON.parse(JSON.stringify(r)) : void 0;
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
//#endregion
|
|
348
|
+
export { MAX_FREE_RELAY_CREDITS_PER_EPOCH, OcapSovereignAppChainHubEngine, computeVLedgerCheckpointStateRoot, deriveSovereignVaultDid };
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { BN } from "@ocap/util";
|
|
2
|
+
|
|
3
|
+
//#region src/arcvault-external-adapter.d.ts
|
|
4
|
+
/** Forbidden raw ERC-20 / Permit2 selectors that could drain vault funds if called on an arbitrary target */
|
|
5
|
+
declare const FORBIDDEN_EXTERNAL_CALL_SELECTORS: Set<string>;
|
|
6
|
+
declare const MIN_VAULT_LIQUID_BUFFER_BPS = 2000;
|
|
7
|
+
declare const MAX_VAULT_STRATEGY_DEPLOYED_BPS = 8000;
|
|
8
|
+
declare const MAX_ZAP_PRICE_IMPACT_BPS = 500;
|
|
9
|
+
declare const MAX_HARVEST_YIELD_BPS = 5000;
|
|
10
|
+
declare const MAX_ZAP_ABT_PER_SETTLEMENT_SCALAR: BN;
|
|
11
|
+
interface ExternalSwapHookInput {
|
|
12
|
+
swapId: string;
|
|
13
|
+
routerAddress: string;
|
|
14
|
+
callSelector: string;
|
|
15
|
+
tokenIn: string;
|
|
16
|
+
tokenOut: string;
|
|
17
|
+
amountIn: string;
|
|
18
|
+
minAmountOut: string;
|
|
19
|
+
preBalanceIn: string;
|
|
20
|
+
postBalanceIn: string;
|
|
21
|
+
preBalanceOut: string;
|
|
22
|
+
postBalanceOut: string;
|
|
23
|
+
ofacBlocklist?: Iterable<string>;
|
|
24
|
+
}
|
|
25
|
+
interface ExternalSwapHookResult {
|
|
26
|
+
swapId: string;
|
|
27
|
+
routerAddress: string;
|
|
28
|
+
tokenIn: string;
|
|
29
|
+
tokenOut: string;
|
|
30
|
+
exactAmountSpent: string;
|
|
31
|
+
actualAmountReceived: string;
|
|
32
|
+
transientApprovalBeforeCall: string;
|
|
33
|
+
transientApprovalAfterCall: string;
|
|
34
|
+
balanceInvariantDigest: string;
|
|
35
|
+
}
|
|
36
|
+
interface ArcVaultShareholderPosition {
|
|
37
|
+
holderDid: string;
|
|
38
|
+
principalShares: string;
|
|
39
|
+
yieldDebtScaled: string;
|
|
40
|
+
accruedUnclaimedYield: string;
|
|
41
|
+
}
|
|
42
|
+
interface ArcVaultLiquidityState {
|
|
43
|
+
vaultId: string;
|
|
44
|
+
settlementToken: string;
|
|
45
|
+
erc4626StrategyVault: string;
|
|
46
|
+
liquidBufferBalance: string;
|
|
47
|
+
strategyDeployedBalance: string;
|
|
48
|
+
totalPrincipalShares: string;
|
|
49
|
+
accYieldPerShareScaled: string;
|
|
50
|
+
unclaimedYieldReserve: string;
|
|
51
|
+
shareholders: Record<string, ArcVaultShareholderPosition>;
|
|
52
|
+
}
|
|
53
|
+
interface UniversalAbtZapInInput {
|
|
54
|
+
zapId: string;
|
|
55
|
+
senderAddress: string;
|
|
56
|
+
recipientDid: string;
|
|
57
|
+
routerAddress: string;
|
|
58
|
+
callSelector: string;
|
|
59
|
+
tokenIn: string;
|
|
60
|
+
amountIn: string;
|
|
61
|
+
quotedSettlementOut: string;
|
|
62
|
+
minSettlementOut: string;
|
|
63
|
+
quotedAbtOut: string;
|
|
64
|
+
minAbtOut: string;
|
|
65
|
+
slippageBps: number;
|
|
66
|
+
preSettlementBalance?: string;
|
|
67
|
+
postSettlementBalance?: string;
|
|
68
|
+
ofacBlocklist?: Iterable<string>;
|
|
69
|
+
}
|
|
70
|
+
interface UniversalAbtZapInResult {
|
|
71
|
+
zapId: string;
|
|
72
|
+
recipientDid: string;
|
|
73
|
+
settlementDepositedToVault: string;
|
|
74
|
+
abtMintedOnOcap: string;
|
|
75
|
+
vaultState: ArcVaultLiquidityState;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* ArcVault External Swap Hook + ERC-4626 Non-Commingled Yield Adapter + Universal ABT Zap-In Engine (#1170).
|
|
79
|
+
*/
|
|
80
|
+
declare class OcapArcVaultExternalAdapterEngine {
|
|
81
|
+
readonly vaultId: string;
|
|
82
|
+
readonly settlementToken: string;
|
|
83
|
+
readonly abtTokenAddress: string;
|
|
84
|
+
readonly erc4626StrategyVault: string;
|
|
85
|
+
private readonly allowlistedRouters;
|
|
86
|
+
private readonly allowlistedSelectors;
|
|
87
|
+
private readonly consumedSwapIds;
|
|
88
|
+
private readonly consumedZapIds;
|
|
89
|
+
private readonly ofacSet;
|
|
90
|
+
private liquidBufferBn;
|
|
91
|
+
private strategyDeployedBn;
|
|
92
|
+
private totalPrincipalSharesBn;
|
|
93
|
+
private accYieldPerShareScaledBn;
|
|
94
|
+
private unclaimedYieldReserveBn;
|
|
95
|
+
private readonly shareholders;
|
|
96
|
+
constructor(options: {
|
|
97
|
+
vaultId: string;
|
|
98
|
+
settlementToken: string;
|
|
99
|
+
abtTokenAddress: string;
|
|
100
|
+
erc4626StrategyVault: string;
|
|
101
|
+
allowlistedRouters: string[];
|
|
102
|
+
allowlistedSelectors: string[];
|
|
103
|
+
ofacBlocklist?: Iterable<string>;
|
|
104
|
+
});
|
|
105
|
+
private assertNotProtectedProtocolAddress;
|
|
106
|
+
private mergeOfacSet;
|
|
107
|
+
/**
|
|
108
|
+
* Executes an allowlisted external DEX swap (`executeExternalSwap`) with:
|
|
109
|
+
* - Strict router & selector allowlist enforcement (blocking ERC-20 & Permit2 `approve`/`transferFrom`)
|
|
110
|
+
* - Token pair anchor verification (at least one leg must be `settlementToken` or `abtTokenAddress`, and neither leg can be `erc4626StrategyVault` or a router)
|
|
111
|
+
* - Transient exact-amount approval (`amountIn` before call, `0` immediately after call)
|
|
112
|
+
* - Pre/post balance snapshot verification (`actualAmountOut >= minAmountOut` and exact `amountIn` debit)
|
|
113
|
+
*/
|
|
114
|
+
executeExternalSwap(input: ExternalSwapHookInput): ExternalSwapHookResult;
|
|
115
|
+
/**
|
|
116
|
+
* Deposits settlement tokens directly into ArcVault, minting 1:1 principal shares for `holderDid`
|
|
117
|
+
* and routing liquidity according to the 20% Liquid Buffer / 80% ERC-4626 Strategy policy.
|
|
118
|
+
*/
|
|
119
|
+
depositAndAllocate(params: {
|
|
120
|
+
holderDid: string;
|
|
121
|
+
amount: string;
|
|
122
|
+
autoDeployToStrategy?: boolean;
|
|
123
|
+
ofacBlocklist?: Iterable<string>;
|
|
124
|
+
}): ArcVaultLiquidityState;
|
|
125
|
+
/**
|
|
126
|
+
* Enforces the 20% Liquid Buffer / 80% Allowlisted ERC-4626 Strategy allocation invariant.
|
|
127
|
+
* Uses ceiling division for the 20% minimum liquid buffer so `liquidBufferBalance` is NEVER
|
|
128
|
+
* even 1 wei below 20% of total backing (`liquidBufferBalance + strategyDeployedBalance`).
|
|
129
|
+
*/
|
|
130
|
+
rebalanceToTargetAllocation(): ArcVaultLiquidityState;
|
|
131
|
+
/**
|
|
132
|
+
* Withdraws principal shares for `holderDid`. If `withdrawAmount > liquidBufferBalance`,
|
|
133
|
+
* automatically recalls the shortfall from the ERC-4626 strategy adapter AND restores the 20%
|
|
134
|
+
* minimum liquid buffer on the remaining vault backing.
|
|
135
|
+
*/
|
|
136
|
+
withdrawWithAutoRecall(params: {
|
|
137
|
+
holderDid: string;
|
|
138
|
+
withdrawAmount: string;
|
|
139
|
+
ofacBlocklist?: Iterable<string>;
|
|
140
|
+
}): {
|
|
141
|
+
withdrawnAmount: string;
|
|
142
|
+
recalledFromStrategy: string;
|
|
143
|
+
vaultState: ArcVaultLiquidityState;
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Harvests yield generated by the allowlisted ERC-4626 strategy vault and distributes it
|
|
147
|
+
* in `O(1)` time via `accYieldPerShareScaled` backed 100% by `unclaimedYieldReserve`.
|
|
148
|
+
*/
|
|
149
|
+
harvestVaultYield(yieldAmount: string): ArcVaultLiquidityState;
|
|
150
|
+
/**
|
|
151
|
+
* Claims accrued ERC-4626 strategy yield for `holderDid` in `O(1)` time.
|
|
152
|
+
*/
|
|
153
|
+
claimVaultYield(holderDid: string, ofacBlocklist?: Iterable<string>): {
|
|
154
|
+
claimedYield: string;
|
|
155
|
+
shareholderPosition: ArcVaultShareholderPosition;
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* Universal `ABT` Zap-In Funnel (`zapInAndBridge`):
|
|
159
|
+
* Converts arbitrary origin-chain `tokenIn` -> `settlementToken` (deposited & allocated into ArcVault)
|
|
160
|
+
* -> `OCAP ABT` for `recipientDid` with router/selector allowlist, slippage caps, exchange-rate bounds, and OFAC screening.
|
|
161
|
+
*/
|
|
162
|
+
zapInAndBridge(input: UniversalAbtZapInInput): UniversalAbtZapInResult;
|
|
163
|
+
getVaultState(): ArcVaultLiquidityState;
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
export { ArcVaultLiquidityState, ArcVaultShareholderPosition, ExternalSwapHookInput, ExternalSwapHookResult, FORBIDDEN_EXTERNAL_CALL_SELECTORS, MAX_HARVEST_YIELD_BPS, MAX_VAULT_STRATEGY_DEPLOYED_BPS, MAX_ZAP_ABT_PER_SETTLEMENT_SCALAR, MAX_ZAP_PRICE_IMPACT_BPS, MIN_VAULT_LIQUID_BUFFER_BPS, OcapArcVaultExternalAdapterEngine, UniversalAbtZapInInput, UniversalAbtZapInResult };
|