@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,578 @@
|
|
|
1
|
+
import { CHAINALYSIS_OFAC_ORACLE_ADDRESS, assertNotOfacSanctioned, normalizeScreeningAddress } from "./ofac-screening.mjs";
|
|
2
|
+
import { Hasher } from "@ocap/mcrypto";
|
|
3
|
+
import { BN } from "@ocap/util";
|
|
4
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
5
|
+
|
|
6
|
+
//#region src/uniswap-router.ts
|
|
7
|
+
/**
|
|
8
|
+
* Default Integrator Tag for Uniswap Universal Router & Base Builder Attribution.
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_OCAP_INTEGRATOR_ID = "arcblock-ocap-checkout";
|
|
11
|
+
/**
|
|
12
|
+
* Maximum allowed slippage in basis points (5.00% = 500 bps) for 1-click cross-chain zaps.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_ALLOWED_ZAP_SLIPPAGE_BPS = 500;
|
|
15
|
+
/**
|
|
16
|
+
* Maximum allowed token hops in a single Universal Router path (up to 5 tokens = 4 pool hops).
|
|
17
|
+
*/
|
|
18
|
+
const MAX_ROUTE_PATH_LENGTH = 5;
|
|
19
|
+
/**
|
|
20
|
+
* Standard Uniswap Universal Router command bytes.
|
|
21
|
+
*/
|
|
22
|
+
const UNIVERSAL_ROUTER_COMMANDS = {
|
|
23
|
+
V3_SWAP_EXACT_IN: 0,
|
|
24
|
+
SWEEP: 4,
|
|
25
|
+
TRANSFER: 5,
|
|
26
|
+
PAY_PORTION: 6,
|
|
27
|
+
PERMIT2_PERMIT: 10,
|
|
28
|
+
V4_SWAP: 16
|
|
29
|
+
};
|
|
30
|
+
const FORBIDDEN_KEYS = new Set([
|
|
31
|
+
"__proto__",
|
|
32
|
+
"constructor",
|
|
33
|
+
"prototype"
|
|
34
|
+
]);
|
|
35
|
+
const CANONICAL_UINT_REGEX = /^\d+$/;
|
|
36
|
+
const EVM_HEX_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
|
|
37
|
+
const EVEN_HEX_BYTES_REGEX = /^0x(?:[0-9a-fA-F]{2})+$/;
|
|
38
|
+
const SAFE_INTEGRATOR_ID_REGEX = /^[a-zA-Z0-9._-]{3,64}$/;
|
|
39
|
+
const ALLOWED_SERVICE_TYPES = new Set([
|
|
40
|
+
"blocklet_subscription",
|
|
41
|
+
"aigne_compute_credits",
|
|
42
|
+
"nft_purchase",
|
|
43
|
+
"utility_stake"
|
|
44
|
+
]);
|
|
45
|
+
function assertSafeIdentifier(value, fieldName) {
|
|
46
|
+
if (typeof value !== "string") throw new CustomError("INVALID_UNISWAP_ZAP", `${fieldName} must be a non-empty string`);
|
|
47
|
+
const trimmed = value.trim();
|
|
48
|
+
if (!trimmed || FORBIDDEN_KEYS.has(trimmed)) throw new CustomError("INVALID_UNISWAP_ZAP", `Unsafe or empty ${fieldName}: ${String(value)}`);
|
|
49
|
+
return trimmed;
|
|
50
|
+
}
|
|
51
|
+
function parsePositiveUint(raw, fieldName) {
|
|
52
|
+
if (typeof raw !== "string" || !CANONICAL_UINT_REGEX.test(raw)) throw new CustomError("INVALID_UNISWAP_ZAP", `${fieldName} must be a canonical integer string`);
|
|
53
|
+
const bn = new BN(raw, 10);
|
|
54
|
+
if (bn.lte(new BN(0))) throw new CustomError("INVALID_UNISWAP_ZAP", `${fieldName} must be strictly positive`);
|
|
55
|
+
return bn;
|
|
56
|
+
}
|
|
57
|
+
function parseNonNegativeUint(raw, fieldName) {
|
|
58
|
+
if (typeof raw !== "string" || !CANONICAL_UINT_REGEX.test(raw)) throw new CustomError("INVALID_UNISWAP_ZAP", `${fieldName} must be a canonical non-negative integer string`);
|
|
59
|
+
return new BN(raw, 10);
|
|
60
|
+
}
|
|
61
|
+
function assertEvmAddress(address, fieldName) {
|
|
62
|
+
if (typeof address !== "string" || !EVM_HEX_ADDRESS_REGEX.test(address)) throw new CustomError("INVALID_UNISWAP_ZAP", `${fieldName} must be a valid 20-byte 0x EVM address`);
|
|
63
|
+
return address.toLowerCase();
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Builds a deterministic, router-friendly Uniswap Universal Router + Permit2 payload
|
|
67
|
+
* that swaps any ERC-20 token into settlement token (`USDC` or `ABT`) and transfers it
|
|
68
|
+
* into the OCAP Rollup Vault in a single EVM transaction.
|
|
69
|
+
*
|
|
70
|
+
* Security & Compliance Invariants:
|
|
71
|
+
* 1. Rejects any non-zero `brokerageFeeBps` or `PAY_PORTION` fee-skimming (SEC Section 15(a) Safe Harbor).
|
|
72
|
+
* 2. Screens sender, router, vault, token addresses, and OCAP buyer DID against OFAC blocklist.
|
|
73
|
+
* 3. Enforces strict `maxSlippageBps <= 500` (5%), loop-free route paths (`<= 5` tokens), and valid Permit2 hex signatures.
|
|
74
|
+
* 4. Embeds official `ocap:v1:<integratorId>` attribution tag for Uniswap & Base ecosystem alignment.
|
|
75
|
+
*/
|
|
76
|
+
function buildUniversalRouterCrossChainPayload(input) {
|
|
77
|
+
if (!input || typeof input !== "object") throw new CustomError("INVALID_UNISWAP_ZAP", "Missing Universal Router zap input");
|
|
78
|
+
if (input.brokerageFeeBps !== void 0 && input.brokerageFeeBps !== 0) throw new CustomError("ILLEGAL_BROKERAGE_COMMISSION", "Variable bps brokerage commission on swaps is strictly prohibited (must be 0 bps for SEC Section 15(a) Safe Harbor)");
|
|
79
|
+
const chainId = assertSafeIdentifier(input.chainId, "chainId");
|
|
80
|
+
const buyerOcapDid = assertSafeIdentifier(input.buyerOcapDid, "buyerOcapDid");
|
|
81
|
+
const senderEvmAddress = assertEvmAddress(input.senderEvmAddress, "senderEvmAddress");
|
|
82
|
+
const universalRouterAddress = assertEvmAddress(input.universalRouterAddress, "universalRouterAddress");
|
|
83
|
+
const ocapVaultAddress = assertEvmAddress(input.ocapVaultAddress, "ocapVaultAddress");
|
|
84
|
+
const tokenIn = assertEvmAddress(input.tokenIn, "tokenIn");
|
|
85
|
+
const tokenOut = assertEvmAddress(input.tokenOut, "tokenOut");
|
|
86
|
+
if (tokenIn === tokenOut) throw new CustomError("INVALID_UNISWAP_ZAP", "tokenIn and tokenOut must be distinct addresses");
|
|
87
|
+
if (!Array.isArray(input.routePath) || input.routePath.length < 2 || input.routePath.length > MAX_ROUTE_PATH_LENGTH) throw new CustomError("INVALID_UNISWAP_ZAP", `routePath must contain between 2 and ${MAX_ROUTE_PATH_LENGTH} token addresses`);
|
|
88
|
+
const normalizedRoute = input.routePath.map((hop, i) => assertEvmAddress(hop, `routePath[${i}]`));
|
|
89
|
+
if (normalizedRoute[0] !== tokenIn || normalizedRoute[normalizedRoute.length - 1] !== tokenOut) throw new CustomError("INVALID_UNISWAP_ZAP", "routePath endpoints must match tokenIn and tokenOut");
|
|
90
|
+
if (new Set(normalizedRoute).size !== normalizedRoute.length) throw new CustomError("INVALID_UNISWAP_ZAP", "routePath cannot contain duplicate tokens or routing loops");
|
|
91
|
+
assertNotOfacSanctioned([
|
|
92
|
+
senderEvmAddress,
|
|
93
|
+
buyerOcapDid,
|
|
94
|
+
universalRouterAddress,
|
|
95
|
+
ocapVaultAddress,
|
|
96
|
+
...normalizedRoute
|
|
97
|
+
], input.ofacBlocklist);
|
|
98
|
+
const amountIn = parsePositiveUint(input.amountIn, "amountIn");
|
|
99
|
+
const expectedAmountOut = parsePositiveUint(input.expectedAmountOut, "expectedAmountOut");
|
|
100
|
+
if (typeof input.maxSlippageBps !== "number" || !Number.isSafeInteger(input.maxSlippageBps) || input.maxSlippageBps < 0 || input.maxSlippageBps > MAX_ALLOWED_ZAP_SLIPPAGE_BPS) throw new CustomError("INVALID_UNISWAP_ZAP", `maxSlippageBps must be an integer between 0 and ${MAX_ALLOWED_ZAP_SLIPPAGE_BPS}`);
|
|
101
|
+
const amountOutMinimum = expectedAmountOut.mul(new BN(1e4 - input.maxSlippageBps)).div(new BN(1e4));
|
|
102
|
+
if (amountOutMinimum.lte(new BN(0))) throw new CustomError("INVALID_UNISWAP_ZAP", "Computed amountOutMinimum must be strictly positive");
|
|
103
|
+
const now = input.currentTimestamp ?? Math.floor(Date.now() / 1e3);
|
|
104
|
+
if (typeof now !== "number" || !Number.isSafeInteger(now) || now < 0) throw new CustomError("INVALID_UNISWAP_ZAP", "currentTimestamp must be a valid non-negative integer");
|
|
105
|
+
if (typeof input.deadline !== "number" || !Number.isSafeInteger(input.deadline) || input.deadline <= now) throw new CustomError("INVALID_UNISWAP_ZAP", "Swap deadline must be a future Unix timestamp");
|
|
106
|
+
const integratorId = input.integratorId ?? DEFAULT_OCAP_INTEGRATOR_ID;
|
|
107
|
+
if (!SAFE_INTEGRATOR_ID_REGEX.test(integratorId)) throw new CustomError("INVALID_UNISWAP_ZAP", `Invalid integratorId format: ${integratorId}`);
|
|
108
|
+
const integratorTag = `ocap:v1:${integratorId}`;
|
|
109
|
+
const commandBytes = [];
|
|
110
|
+
const commandNames = [];
|
|
111
|
+
let canonicalPermit2 = null;
|
|
112
|
+
if (input.permit2) {
|
|
113
|
+
const permitToken = assertEvmAddress(input.permit2.token, "permit2.token");
|
|
114
|
+
const permitSpender = assertEvmAddress(input.permit2.spender, "permit2.spender");
|
|
115
|
+
if (permitToken !== tokenIn) throw new CustomError("INVALID_UNISWAP_ZAP", "permit2.token must match tokenIn");
|
|
116
|
+
if (permitSpender !== universalRouterAddress) throw new CustomError("INVALID_UNISWAP_ZAP", "permit2.spender must match universalRouterAddress");
|
|
117
|
+
const permitAmount = parsePositiveUint(input.permit2.amount, "permit2.amount");
|
|
118
|
+
if (permitAmount.lt(amountIn)) throw new CustomError("INVALID_UNISWAP_ZAP", "permit2.amount must be >= amountIn");
|
|
119
|
+
if (typeof input.permit2.expiration !== "number" || !Number.isSafeInteger(input.permit2.expiration) || typeof input.permit2.sigDeadline !== "number" || !Number.isSafeInteger(input.permit2.sigDeadline) || input.permit2.sigDeadline < input.deadline || input.permit2.expiration < input.deadline) throw new CustomError("INVALID_UNISWAP_ZAP", "permit2 expiration and sigDeadline must be valid integers >= swap deadline");
|
|
120
|
+
if (typeof input.permit2.nonce !== "number" || !Number.isSafeInteger(input.permit2.nonce) || input.permit2.nonce < 0) throw new CustomError("INVALID_UNISWAP_ZAP", "permit2.nonce must be a non-negative safe integer");
|
|
121
|
+
if (typeof input.permit2.signature !== "string" || !EVEN_HEX_BYTES_REGEX.test(input.permit2.signature)) throw new CustomError("INVALID_UNISWAP_ZAP", "permit2.signature must be a valid 0x-prefixed hex byte string");
|
|
122
|
+
canonicalPermit2 = {
|
|
123
|
+
token: permitToken,
|
|
124
|
+
spender: permitSpender,
|
|
125
|
+
amount: permitAmount.toString(10),
|
|
126
|
+
expiration: input.permit2.expiration,
|
|
127
|
+
sigDeadline: input.permit2.sigDeadline,
|
|
128
|
+
nonce: input.permit2.nonce,
|
|
129
|
+
signature: input.permit2.signature.toLowerCase()
|
|
130
|
+
};
|
|
131
|
+
commandBytes.push(UNIVERSAL_ROUTER_COMMANDS.PERMIT2_PERMIT);
|
|
132
|
+
commandNames.push("PERMIT2_PERMIT");
|
|
133
|
+
}
|
|
134
|
+
const poolVersion = input.poolVersion ?? "v4";
|
|
135
|
+
if (poolVersion === "v4") {
|
|
136
|
+
commandBytes.push(UNIVERSAL_ROUTER_COMMANDS.V4_SWAP);
|
|
137
|
+
commandNames.push("V4_SWAP");
|
|
138
|
+
} else if (poolVersion === "v3") {
|
|
139
|
+
commandBytes.push(UNIVERSAL_ROUTER_COMMANDS.V3_SWAP_EXACT_IN);
|
|
140
|
+
commandNames.push("V3_SWAP_EXACT_IN");
|
|
141
|
+
} else throw new CustomError("INVALID_UNISWAP_ZAP", `Unsupported poolVersion: ${String(poolVersion)}`);
|
|
142
|
+
commandBytes.push(UNIVERSAL_ROUTER_COMMANDS.SWEEP);
|
|
143
|
+
commandNames.push("SWEEP");
|
|
144
|
+
const commandsHex = `0x${commandBytes.map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
145
|
+
const canonicalPayloadStr = JSON.stringify({
|
|
146
|
+
chainId,
|
|
147
|
+
router: universalRouterAddress,
|
|
148
|
+
sender: senderEvmAddress,
|
|
149
|
+
buyerOcapDid,
|
|
150
|
+
vault: ocapVaultAddress,
|
|
151
|
+
commandsHex,
|
|
152
|
+
route: normalizedRoute,
|
|
153
|
+
amountIn: amountIn.toString(10),
|
|
154
|
+
amountOutMinimum: amountOutMinimum.toString(10),
|
|
155
|
+
deadline: input.deadline,
|
|
156
|
+
permit2: canonicalPermit2,
|
|
157
|
+
integratorTag
|
|
158
|
+
});
|
|
159
|
+
const calldataDigest = Hasher.SHA3.hash256(Buffer.from(canonicalPayloadStr, "utf8"));
|
|
160
|
+
return {
|
|
161
|
+
chainId,
|
|
162
|
+
to: universalRouterAddress,
|
|
163
|
+
senderEvmAddress,
|
|
164
|
+
buyerOcapDid,
|
|
165
|
+
ocapVaultAddress,
|
|
166
|
+
commandsHex,
|
|
167
|
+
commandNames,
|
|
168
|
+
routePath: normalizedRoute,
|
|
169
|
+
amountIn: amountIn.toString(10),
|
|
170
|
+
expectedAmountOut: expectedAmountOut.toString(10),
|
|
171
|
+
amountOutMinimum: amountOutMinimum.toString(10),
|
|
172
|
+
maxSlippageBps: input.maxSlippageBps,
|
|
173
|
+
deadline: input.deadline,
|
|
174
|
+
integratorTag,
|
|
175
|
+
brokerageFeeBps: 0,
|
|
176
|
+
ofacOracleAddress: CHAINALYSIS_OFAC_ORACLE_ADDRESS,
|
|
177
|
+
calldataDigest
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Builds an end-to-end "Invisible ABT Utility Fuel" Pass-Through Plan:
|
|
182
|
+
* 1. User pays any token (`USDC`, `ETH`, etc.) on Base/Ethereum via Uniswap `USDC/ABT` pool.
|
|
183
|
+
* 2. Exact `ABT` needed (`abtServicePrice + abtRelayerFee`) is deposited to OCAP and
|
|
184
|
+
* 100% consumed/staked in the same atomic `TransactionBlock` (`holdingPeriodSeconds = 0`,
|
|
185
|
+
* `netBuyerSpeculativeAbtRetained = '0'`, `treasuryCapitalAtRisk = '0'`).
|
|
186
|
+
*/
|
|
187
|
+
function buildAbtUtilityPassThroughPlan(input) {
|
|
188
|
+
if (!input || typeof input !== "object") throw new CustomError("INVALID_ABT_PASSTHROUGH", "Missing ABT utility pass-through input");
|
|
189
|
+
const buyerOcapDid = assertSafeIdentifier(input.buyerOcapDid, "buyerOcapDid");
|
|
190
|
+
const relayerOcapDid = assertSafeIdentifier(input.relayerOcapDid, "relayerOcapDid");
|
|
191
|
+
const rollupAddress = assertSafeIdentifier(input.rollupAddress, "rollupAddress");
|
|
192
|
+
const abtOcapTokenAddress = assertSafeIdentifier(input.abtOcapTokenAddress, "abtOcapTokenAddress");
|
|
193
|
+
const serviceRecipientDid = assertSafeIdentifier(input.serviceRecipientDid, "serviceRecipientDid");
|
|
194
|
+
const sourceTxEvidenceHash = assertSafeIdentifier(input.sourceTxEvidenceHash, "sourceTxEvidenceHash");
|
|
195
|
+
const targetAssetOrStakeAddress = input.targetAssetOrStakeAddress !== void 0 ? assertSafeIdentifier(input.targetAssetOrStakeAddress, "targetAssetOrStakeAddress") : void 0;
|
|
196
|
+
if (!ALLOWED_SERVICE_TYPES.has(input.serviceType)) throw new CustomError("INVALID_ABT_PASSTHROUGH", `Unsupported serviceType: ${String(input.serviceType)}`);
|
|
197
|
+
if (normalizeScreeningAddress(buyerOcapDid) === normalizeScreeningAddress(serviceRecipientDid) || normalizeScreeningAddress(buyerOcapDid) === normalizeScreeningAddress(relayerOcapDid)) throw new CustomError("SELF_DEALING_CONSUMPTIVE_BYPASS", "buyerOcapDid cannot be identical to serviceRecipientDid or relayerOcapDid in a 0-second consumptive pass-through");
|
|
198
|
+
assertNotOfacSanctioned([
|
|
199
|
+
input.senderEvmAddress,
|
|
200
|
+
buyerOcapDid,
|
|
201
|
+
relayerOcapDid,
|
|
202
|
+
rollupAddress,
|
|
203
|
+
abtOcapTokenAddress,
|
|
204
|
+
serviceRecipientDid,
|
|
205
|
+
targetAssetOrStakeAddress
|
|
206
|
+
], input.ofacBlocklist);
|
|
207
|
+
const abtExpectedOut = parsePositiveUint(input.abtExpectedOut, "abtExpectedOut");
|
|
208
|
+
const abtServicePrice = parsePositiveUint(input.abtServicePrice, "abtServicePrice");
|
|
209
|
+
const abtRelayerFee = parseNonNegativeUint(input.abtRelayerFee, "abtRelayerFee");
|
|
210
|
+
const expectedTotalAbt = abtServicePrice.add(abtRelayerFee);
|
|
211
|
+
if (!abtExpectedOut.eq(expectedTotalAbt)) throw new CustomError("CONSUMPTIVE_USE_MISMATCH", `abtExpectedOut (${abtExpectedOut.toString(10)}) must equal abtServicePrice (${abtServicePrice.toString(10)}) + abtRelayerFee (${abtRelayerFee.toString(10)}) for 0-second consumptive pass-through`);
|
|
212
|
+
const evmSwapPayload = buildUniversalRouterCrossChainPayload({
|
|
213
|
+
chainId: input.chainId,
|
|
214
|
+
senderEvmAddress: input.senderEvmAddress,
|
|
215
|
+
buyerOcapDid,
|
|
216
|
+
universalRouterAddress: input.universalRouterAddress,
|
|
217
|
+
ocapVaultAddress: input.ocapVaultAddress,
|
|
218
|
+
tokenIn: input.paymentTokenEvmAddress,
|
|
219
|
+
tokenOut: input.abtEvmAddress,
|
|
220
|
+
routePath: input.routePath,
|
|
221
|
+
poolVersion: input.poolVersion ?? "v4",
|
|
222
|
+
amountIn: input.paymentAmountIn,
|
|
223
|
+
expectedAmountOut: abtExpectedOut.toString(10),
|
|
224
|
+
maxSlippageBps: input.maxSlippageBps,
|
|
225
|
+
deadline: input.deadline,
|
|
226
|
+
currentTimestamp: input.currentTimestamp,
|
|
227
|
+
integratorId: input.integratorId,
|
|
228
|
+
brokerageFeeBps: 0,
|
|
229
|
+
ofacBlocklist: input.ofacBlocklist
|
|
230
|
+
});
|
|
231
|
+
const consumeStatement = input.serviceType === "nft_purchase" ? {
|
|
232
|
+
type: "acquire_asset_v3",
|
|
233
|
+
typeUrl: "fg:t:acquire_asset_v3",
|
|
234
|
+
from: buyerOcapDid,
|
|
235
|
+
itx: {
|
|
236
|
+
to: serviceRecipientDid,
|
|
237
|
+
factory: targetAssetOrStakeAddress || serviceRecipientDid,
|
|
238
|
+
token: {
|
|
239
|
+
address: abtOcapTokenAddress,
|
|
240
|
+
value: abtServicePrice.toString(10)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
} : {
|
|
244
|
+
type: "transfer_v3",
|
|
245
|
+
typeUrl: "fg:t:transfer_v3",
|
|
246
|
+
from: buyerOcapDid,
|
|
247
|
+
itx: {
|
|
248
|
+
to: serviceRecipientDid,
|
|
249
|
+
tokens: [{
|
|
250
|
+
address: abtOcapTokenAddress,
|
|
251
|
+
value: abtServicePrice.toString(10)
|
|
252
|
+
}],
|
|
253
|
+
data: {
|
|
254
|
+
type: "json",
|
|
255
|
+
value: JSON.stringify({
|
|
256
|
+
consumptiveUse: true,
|
|
257
|
+
serviceType: input.serviceType,
|
|
258
|
+
target: targetAssetOrStakeAddress || serviceRecipientDid
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
return {
|
|
264
|
+
evmSwapPayload,
|
|
265
|
+
ocapPurchaseBlockInput: {
|
|
266
|
+
relayer: relayerOcapDid,
|
|
267
|
+
buyer: buyerOcapDid,
|
|
268
|
+
deposit: {
|
|
269
|
+
rollup: rollupAddress,
|
|
270
|
+
token: {
|
|
271
|
+
address: abtOcapTokenAddress,
|
|
272
|
+
value: abtServicePrice.toString(10)
|
|
273
|
+
},
|
|
274
|
+
actualFee: abtRelayerFee.toString(10),
|
|
275
|
+
proposer: relayerOcapDid,
|
|
276
|
+
evidence: {
|
|
277
|
+
hash: sourceTxEvidenceHash,
|
|
278
|
+
targetType: "EVM",
|
|
279
|
+
targetChainId: input.chainId
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
purchaseStatements: [consumeStatement],
|
|
283
|
+
minDepositValue: input.minDepositValue,
|
|
284
|
+
minRelayerFee: input.minRelayerFee,
|
|
285
|
+
fallbackToDepositOnPurchaseFailure: input.fallbackToDepositOnPurchaseFailure ?? true,
|
|
286
|
+
ofacBlocklist: input.ofacBlocklist ? Array.from(input.ofacBlocklist) : void 0,
|
|
287
|
+
enforceZeroSum: true
|
|
288
|
+
},
|
|
289
|
+
economics: {
|
|
290
|
+
treasuryCapitalAtRisk: "0",
|
|
291
|
+
brokerageFeeBps: 0,
|
|
292
|
+
netBuyerSpeculativeAbtRetained: "0",
|
|
293
|
+
holdingPeriodSeconds: 0,
|
|
294
|
+
abtServicePrice: abtServicePrice.toString(10),
|
|
295
|
+
abtRelayerFee: abtRelayerFee.toString(10),
|
|
296
|
+
totalAbtRouted: abtExpectedOut.toString(10)
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Maximum TTL (in seconds) for a USD-anchored dynamic ABT price quote (#1274).
|
|
302
|
+
*/
|
|
303
|
+
const MAX_USD_QUOTE_TTL_SECONDS = 300;
|
|
304
|
+
/**
|
|
305
|
+
* Default TTL (in seconds) for a USD-anchored dynamic ABT price quote (#1274).
|
|
306
|
+
*/
|
|
307
|
+
const DEFAULT_USD_QUOTE_TTL_SECONDS = 60;
|
|
308
|
+
/**
|
|
309
|
+
* 18-decimal base unit scale for ABT (`10^18`).
|
|
310
|
+
*/
|
|
311
|
+
const ABT_DECIMALS_SCALE = "1000000000000000000";
|
|
312
|
+
const BYTES32_HEX_DIGEST_REGEX = /^0x[0-9a-fA-F]{64}$/;
|
|
313
|
+
function computeUsdAnchoredQuoteDigest(fields) {
|
|
314
|
+
const canonical = JSON.stringify({
|
|
315
|
+
domain: "OCAP_USD_ANCHORED_ABT_QUOTE_V1",
|
|
316
|
+
quoteId: fields.quoteId,
|
|
317
|
+
serviceId: fields.serviceId,
|
|
318
|
+
buyerOcapDid: fields.buyerOcapDid,
|
|
319
|
+
usdPriceMicro: fields.usdPriceMicro,
|
|
320
|
+
abtUsdPriceMicro: fields.abtUsdPriceMicro,
|
|
321
|
+
requiredAbtWei: fields.requiredAbtWei,
|
|
322
|
+
maxAbtWithSlippageWei: fields.maxAbtWithSlippageWei,
|
|
323
|
+
maxSlippageBps: fields.maxSlippageBps,
|
|
324
|
+
oracleSource: fields.oracleSource,
|
|
325
|
+
issuedAt: fields.issuedAt,
|
|
326
|
+
expiresAt: fields.expiresAt
|
|
327
|
+
});
|
|
328
|
+
return Hasher.SHA3.hash256(Buffer.from(canonical, "utf8"));
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Issue #1274:
|
|
332
|
+
* Computes a deterministic, CEX-independent USD-anchored `ABT` price quote from a Uniswap V3/V4
|
|
333
|
+
* TWAP/Spot price (`abtUsdPriceMicro`), giving users stable USD mental pricing (`$0.10`, `$1.00`, `$10.00`)
|
|
334
|
+
* while keeping the on-chain settlement 100% pure `ABT`.
|
|
335
|
+
*/
|
|
336
|
+
function createUsdAnchoredAbtQuote(input) {
|
|
337
|
+
if (!input || typeof input !== "object") throw new CustomError("INVALID_USD_ABT_QUOTE", "Missing USD-anchored ABT quote input");
|
|
338
|
+
const quoteId = assertSafeIdentifier(input.quoteId, "quoteId");
|
|
339
|
+
const serviceId = assertSafeIdentifier(input.serviceId, "serviceId");
|
|
340
|
+
const buyerOcapDid = assertSafeIdentifier(input.buyerOcapDid, "buyerOcapDid");
|
|
341
|
+
const usdPriceMicroBn = parsePositiveUint(input.usdPriceMicro, "usdPriceMicro");
|
|
342
|
+
const abtUsdPriceMicroBn = parsePositiveUint(input.abtUsdPriceMicro, "abtUsdPriceMicro");
|
|
343
|
+
const maxSlippageBps = input.maxSlippageBps ?? 100;
|
|
344
|
+
if (typeof maxSlippageBps !== "number" || !Number.isSafeInteger(maxSlippageBps) || maxSlippageBps < 0 || maxSlippageBps > MAX_ALLOWED_ZAP_SLIPPAGE_BPS) throw new CustomError("INVALID_USD_ABT_QUOTE", `maxSlippageBps must be an integer between 0 and ${MAX_ALLOWED_ZAP_SLIPPAGE_BPS}`);
|
|
345
|
+
if (typeof input.issuedAt !== "number" || !Number.isSafeInteger(input.issuedAt) || input.issuedAt <= 0) throw new CustomError("INVALID_USD_ABT_QUOTE", "issuedAt must be a positive safe integer Unix timestamp");
|
|
346
|
+
const expiresAt = input.expiresAt ?? input.issuedAt + DEFAULT_USD_QUOTE_TTL_SECONDS;
|
|
347
|
+
if (typeof expiresAt !== "number" || !Number.isSafeInteger(expiresAt) || expiresAt <= input.issuedAt || expiresAt - input.issuedAt > MAX_USD_QUOTE_TTL_SECONDS) throw new CustomError("INVALID_USD_ABT_QUOTE", `expiresAt must be strictly after issuedAt and within MAX_USD_QUOTE_TTL_SECONDS (${MAX_USD_QUOTE_TTL_SECONDS}s)`);
|
|
348
|
+
const oracleSource = input.oracleSource ?? "UNISWAP_V4_TWAP";
|
|
349
|
+
if (oracleSource !== "UNISWAP_V4_TWAP" && oracleSource !== "UNISWAP_V3_TWAP") throw new CustomError("INVALID_USD_ABT_QUOTE", `Unsupported oracleSource: ${String(oracleSource)}`);
|
|
350
|
+
const scaleBn = new BN(ABT_DECIMALS_SCALE, 10);
|
|
351
|
+
const requiredAbtBn = usdPriceMicroBn.mul(scaleBn).add(abtUsdPriceMicroBn.sub(new BN(1))).div(abtUsdPriceMicroBn);
|
|
352
|
+
if (requiredAbtBn.lte(new BN(0))) throw new CustomError("INVALID_USD_ABT_QUOTE", "Computed requiredAbtWei must be strictly positive");
|
|
353
|
+
const maxAbtWithSlippageBn = requiredAbtBn.mul(new BN(1e4 + maxSlippageBps)).add(new BN(9999)).div(new BN(1e4));
|
|
354
|
+
const unsignedQuote = {
|
|
355
|
+
quoteId,
|
|
356
|
+
serviceId,
|
|
357
|
+
buyerOcapDid,
|
|
358
|
+
usdPriceMicro: usdPriceMicroBn.toString(10),
|
|
359
|
+
abtUsdPriceMicro: abtUsdPriceMicroBn.toString(10),
|
|
360
|
+
requiredAbtWei: requiredAbtBn.toString(10),
|
|
361
|
+
maxAbtWithSlippageWei: maxAbtWithSlippageBn.toString(10),
|
|
362
|
+
maxSlippageBps,
|
|
363
|
+
oracleSource,
|
|
364
|
+
issuedAt: input.issuedAt,
|
|
365
|
+
expiresAt
|
|
366
|
+
};
|
|
367
|
+
return {
|
|
368
|
+
...unsignedQuote,
|
|
369
|
+
quoteDigest: computeUsdAnchoredQuoteDigest(unsignedQuote)
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Verifies a USD-anchored dynamic `ABT` quote for freshness, digest integrity, anti-replay,
|
|
374
|
+
* and exact slippage-bounded `ABT` payment sufficiency (#1274).
|
|
375
|
+
*/
|
|
376
|
+
function verifyUsdAnchoredAbtQuote(input) {
|
|
377
|
+
if (!input || typeof input !== "object" || !input.quote || typeof input.quote !== "object") throw new CustomError("INVALID_USD_ABT_QUOTE", "Missing quote verification input");
|
|
378
|
+
const { quote } = input;
|
|
379
|
+
const buyerOcapDid = assertSafeIdentifier(input.buyerOcapDid, "buyerOcapDid");
|
|
380
|
+
const serviceId = assertSafeIdentifier(input.serviceId, "serviceId");
|
|
381
|
+
const expectedUsdPriceMicroBn = parsePositiveUint(input.expectedUsdPriceMicro, "expectedUsdPriceMicro");
|
|
382
|
+
const trustedAbtUsdPriceMicroBn = parsePositiveUint(input.trustedAbtUsdPriceMicro, "trustedAbtUsdPriceMicro");
|
|
383
|
+
const paidAbtBn = parsePositiveUint(input.paidAbtWei, "paidAbtWei");
|
|
384
|
+
const maxOracleDeviationBps = input.maxOracleDeviationBps ?? 200;
|
|
385
|
+
if (typeof maxOracleDeviationBps !== "number" || !Number.isSafeInteger(maxOracleDeviationBps) || maxOracleDeviationBps < 0 || maxOracleDeviationBps > MAX_ALLOWED_ZAP_SLIPPAGE_BPS) throw new CustomError("INVALID_USD_ABT_QUOTE", `maxOracleDeviationBps must be an integer between 0 and ${MAX_ALLOWED_ZAP_SLIPPAGE_BPS}`);
|
|
386
|
+
if (typeof input.nowTimestamp !== "number" || !Number.isSafeInteger(input.nowTimestamp) || input.nowTimestamp <= 0) throw new CustomError("INVALID_USD_ABT_QUOTE", "nowTimestamp must be a positive safe integer");
|
|
387
|
+
const recomputed = createUsdAnchoredAbtQuote({
|
|
388
|
+
quoteId: quote.quoteId,
|
|
389
|
+
serviceId: quote.serviceId,
|
|
390
|
+
buyerOcapDid: quote.buyerOcapDid,
|
|
391
|
+
usdPriceMicro: quote.usdPriceMicro,
|
|
392
|
+
abtUsdPriceMicro: quote.abtUsdPriceMicro,
|
|
393
|
+
maxSlippageBps: quote.maxSlippageBps,
|
|
394
|
+
issuedAt: quote.issuedAt,
|
|
395
|
+
expiresAt: quote.expiresAt,
|
|
396
|
+
oracleSource: quote.oracleSource
|
|
397
|
+
});
|
|
398
|
+
if (quote.quoteDigest !== recomputed.quoteDigest || quote.requiredAbtWei !== recomputed.requiredAbtWei || quote.maxAbtWithSlippageWei !== recomputed.maxAbtWithSlippageWei) throw new CustomError("TAMPERED_USD_ABT_QUOTE", "USD-anchored ABT quote digest or computed amount mismatch");
|
|
399
|
+
if (quote.buyerOcapDid !== buyerOcapDid || quote.serviceId !== serviceId) throw new CustomError("MISMATCHED_USD_ABT_QUOTE_CONTEXT", "Quote buyerOcapDid or serviceId does not match checkout context");
|
|
400
|
+
if (recomputed.usdPriceMicro !== expectedUsdPriceMicroBn.toString(10)) throw new CustomError("FORGED_USD_CATALOG_PRICE", `Quote usdPriceMicro (${recomputed.usdPriceMicro}) does not match expectedUsdPriceMicro (${expectedUsdPriceMicroBn.toString(10)})`);
|
|
401
|
+
const quotedRateBn = new BN(recomputed.abtUsdPriceMicro, 10);
|
|
402
|
+
const rateDiffBn = quotedRateBn.gt(trustedAbtUsdPriceMicroBn) ? quotedRateBn.sub(trustedAbtUsdPriceMicroBn) : trustedAbtUsdPriceMicroBn.sub(quotedRateBn);
|
|
403
|
+
const maxAllowedRateDiffBn = trustedAbtUsdPriceMicroBn.mul(new BN(maxOracleDeviationBps)).div(new BN(1e4));
|
|
404
|
+
if (rateDiffBn.gt(maxAllowedRateDiffBn)) throw new CustomError("FORGED_OR_STALE_ORACLE_EXCHANGE_RATE", `Quote abtUsdPriceMicro (${recomputed.abtUsdPriceMicro}) deviates from trustedAbtUsdPriceMicro (${trustedAbtUsdPriceMicroBn.toString(10)}) by more than ${maxOracleDeviationBps} bps`);
|
|
405
|
+
if (input.nowTimestamp < quote.issuedAt || input.nowTimestamp > quote.expiresAt) throw new CustomError("EXPIRED_USD_ABT_QUOTE", `Quote ${quote.quoteId} expired or not yet valid at timestamp ${input.nowTimestamp} (window: ${quote.issuedAt}..${quote.expiresAt})`);
|
|
406
|
+
if (input.usedQuoteIds?.has(quote.quoteId)) throw new CustomError("REPLAYED_USD_ABT_QUOTE", `Quote ${quote.quoteId} has already been consumed`);
|
|
407
|
+
const requiredAbtBn = new BN(recomputed.requiredAbtWei, 10);
|
|
408
|
+
const maxAbtWithSlippageBn = new BN(recomputed.maxAbtWithSlippageWei, 10);
|
|
409
|
+
if (paidAbtBn.lt(requiredAbtBn)) throw new CustomError("INSUFFICIENT_ABT_FOR_USD_QUOTE", `paidAbtWei (${paidAbtBn.toString(10)}) is less than requiredAbtWei (${requiredAbtBn.toString(10)})`);
|
|
410
|
+
if (paidAbtBn.gt(maxAbtWithSlippageBn)) throw new CustomError("EXCESSIVE_ABT_SLIPPAGE_FOR_USD_QUOTE", `paidAbtWei (${paidAbtBn.toString(10)}) exceeds maxAbtWithSlippageWei (${maxAbtWithSlippageBn.toString(10)})`);
|
|
411
|
+
if (input.usedQuoteIds) input.usedQuoteIds.add(quote.quoteId);
|
|
412
|
+
return {
|
|
413
|
+
verified: true,
|
|
414
|
+
quoteId: quote.quoteId,
|
|
415
|
+
requiredAbtWei: recomputed.requiredAbtWei,
|
|
416
|
+
paidAbtWei: paidAbtBn.toString(10)
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Issue #1274:
|
|
421
|
+
* Builds a stateless 1-Click Outbound Withdraw + Uniswap Auto-Swap Plan ("Smooth In, Smooth Out"):
|
|
422
|
+
* - OCAP side: atomically locks/burns `netAbtToSwap` to `ocapBridgeEscrowDid` and pays `relayerExitFeeAbt` to `relayerOcapDid`.
|
|
423
|
+
* - EVM side: `MultiSigVaultV2` (100% unmodified, holding only `ABT`) releases `netAbtToSwap` via `OcapPublishedMultiSigCert`
|
|
424
|
+
* to `withdrawSwapperAddress`, which atomically swaps `ABT -> targetPayoutToken (USDC/USDT/ETH)` via Uniswap Universal Router
|
|
425
|
+
* and sweeps 100% of output to `recipientEvmAddress` (or safely falls back to sending `netAbtToSwap` directly to `recipientEvmAddress`).
|
|
426
|
+
*/
|
|
427
|
+
function buildOutboundWithdrawAndSwapPlan(input) {
|
|
428
|
+
if (!input || typeof input !== "object") throw new CustomError("INVALID_OUTBOUND_WITHDRAW_SWAP", "Missing outbound withdraw-and-swap input");
|
|
429
|
+
const chainId = assertSafeIdentifier(input.chainId, "chainId");
|
|
430
|
+
const sellerOcapDid = assertSafeIdentifier(input.sellerOcapDid, "sellerOcapDid");
|
|
431
|
+
const relayerOcapDid = assertSafeIdentifier(input.relayerOcapDid, "relayerOcapDid");
|
|
432
|
+
const ocapBridgeEscrowDid = assertSafeIdentifier(input.ocapBridgeEscrowDid, "ocapBridgeEscrowDid");
|
|
433
|
+
const abtOcapTokenAddress = assertSafeIdentifier(input.abtOcapTokenAddress, "abtOcapTokenAddress");
|
|
434
|
+
const recipientEvmAddress = assertEvmAddress(input.recipientEvmAddress, "recipientEvmAddress");
|
|
435
|
+
const ocapVaultAddress = assertEvmAddress(input.ocapVaultAddress, "ocapVaultAddress");
|
|
436
|
+
const withdrawSwapperAddress = assertEvmAddress(input.withdrawSwapperAddress, "withdrawSwapperAddress");
|
|
437
|
+
const universalRouterAddress = assertEvmAddress(input.universalRouterAddress, "universalRouterAddress");
|
|
438
|
+
const abtEvmAddress = assertEvmAddress(input.abtEvmAddress, "abtEvmAddress");
|
|
439
|
+
const targetPayoutTokenAddress = assertEvmAddress(input.targetPayoutTokenAddress, "targetPayoutTokenAddress");
|
|
440
|
+
if (typeof input.publishedMultiSigCertHash !== "string" || !BYTES32_HEX_DIGEST_REGEX.test(input.publishedMultiSigCertHash)) throw new CustomError("INVALID_OUTBOUND_WITHDRAW_SWAP", "publishedMultiSigCertHash must be a valid 32-byte 0x hex digest");
|
|
441
|
+
if (normalizeScreeningAddress(sellerOcapDid) === normalizeScreeningAddress(ocapBridgeEscrowDid) || normalizeScreeningAddress(relayerOcapDid) === normalizeScreeningAddress(ocapBridgeEscrowDid)) throw new CustomError("INVALID_OUTBOUND_WITHDRAW_SWAP", "ocapBridgeEscrowDid must be distinct from sellerOcapDid and relayerOcapDid");
|
|
442
|
+
assertNotOfacSanctioned([
|
|
443
|
+
sellerOcapDid,
|
|
444
|
+
relayerOcapDid,
|
|
445
|
+
ocapBridgeEscrowDid,
|
|
446
|
+
abtOcapTokenAddress,
|
|
447
|
+
recipientEvmAddress,
|
|
448
|
+
ocapVaultAddress,
|
|
449
|
+
withdrawSwapperAddress,
|
|
450
|
+
universalRouterAddress,
|
|
451
|
+
abtEvmAddress,
|
|
452
|
+
targetPayoutTokenAddress
|
|
453
|
+
], input.ofacBlocklist);
|
|
454
|
+
const grossAbtBn = parsePositiveUint(input.grossAbtWithdrawAmount, "grossAbtWithdrawAmount");
|
|
455
|
+
const relayerExitFeeBn = parseNonNegativeUint(input.relayerExitFeeAbt, "relayerExitFeeAbt");
|
|
456
|
+
if (grossAbtBn.lte(relayerExitFeeBn)) throw new CustomError("INVALID_OUTBOUND_WITHDRAW_SWAP", `grossAbtWithdrawAmount (${grossAbtBn.toString(10)}) must be strictly greater than relayerExitFeeAbt (${relayerExitFeeBn.toString(10)})`);
|
|
457
|
+
const netAbtToSwapBn = grossAbtBn.sub(relayerExitFeeBn);
|
|
458
|
+
const isDirectAbtExit = abtEvmAddress === targetPayoutTokenAddress;
|
|
459
|
+
let evmSwapPayload;
|
|
460
|
+
let minimumTargetTokenOutStr;
|
|
461
|
+
let expectedTargetTokenOutStr;
|
|
462
|
+
if (isDirectAbtExit) {
|
|
463
|
+
expectedTargetTokenOutStr = netAbtToSwapBn.toString(10);
|
|
464
|
+
minimumTargetTokenOutStr = netAbtToSwapBn.toString(10);
|
|
465
|
+
} else {
|
|
466
|
+
evmSwapPayload = buildUniversalRouterCrossChainPayload({
|
|
467
|
+
chainId,
|
|
468
|
+
senderEvmAddress: withdrawSwapperAddress,
|
|
469
|
+
buyerOcapDid: sellerOcapDid,
|
|
470
|
+
universalRouterAddress,
|
|
471
|
+
ocapVaultAddress: recipientEvmAddress,
|
|
472
|
+
tokenIn: abtEvmAddress,
|
|
473
|
+
tokenOut: targetPayoutTokenAddress,
|
|
474
|
+
routePath: input.routePath,
|
|
475
|
+
poolVersion: input.poolVersion ?? "v4",
|
|
476
|
+
amountIn: netAbtToSwapBn.toString(10),
|
|
477
|
+
expectedAmountOut: input.expectedTargetTokenOut,
|
|
478
|
+
maxSlippageBps: input.maxSlippageBps,
|
|
479
|
+
deadline: input.deadline,
|
|
480
|
+
currentTimestamp: input.currentTimestamp,
|
|
481
|
+
integratorId: input.integratorId,
|
|
482
|
+
brokerageFeeBps: 0,
|
|
483
|
+
ofacBlocklist: input.ofacBlocklist
|
|
484
|
+
});
|
|
485
|
+
expectedTargetTokenOutStr = evmSwapPayload.expectedAmountOut;
|
|
486
|
+
minimumTargetTokenOutStr = evmSwapPayload.amountOutMinimum;
|
|
487
|
+
}
|
|
488
|
+
const ocapBurnAndFeeStatements = [{
|
|
489
|
+
type: "transfer_v3",
|
|
490
|
+
typeUrl: "fg:t:transfer_v3",
|
|
491
|
+
from: sellerOcapDid,
|
|
492
|
+
itx: {
|
|
493
|
+
to: ocapBridgeEscrowDid,
|
|
494
|
+
tokens: [{
|
|
495
|
+
address: abtOcapTokenAddress,
|
|
496
|
+
value: netAbtToSwapBn.toString(10)
|
|
497
|
+
}],
|
|
498
|
+
data: {
|
|
499
|
+
type: "json",
|
|
500
|
+
value: JSON.stringify({
|
|
501
|
+
bridgeAction: "WITHDRAW_ABT_AND_SWAP",
|
|
502
|
+
chainId,
|
|
503
|
+
recipientEvmAddress,
|
|
504
|
+
targetPayoutTokenAddress,
|
|
505
|
+
publishedMultiSigCertHash: input.publishedMultiSigCertHash.toLowerCase()
|
|
506
|
+
})
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}];
|
|
510
|
+
if (relayerExitFeeBn.gt(new BN(0))) ocapBurnAndFeeStatements.push({
|
|
511
|
+
type: "transfer_v3",
|
|
512
|
+
typeUrl: "fg:t:transfer_v3",
|
|
513
|
+
from: sellerOcapDid,
|
|
514
|
+
itx: {
|
|
515
|
+
to: relayerOcapDid,
|
|
516
|
+
tokens: [{
|
|
517
|
+
address: abtOcapTokenAddress,
|
|
518
|
+
value: relayerExitFeeBn.toString(10)
|
|
519
|
+
}],
|
|
520
|
+
data: {
|
|
521
|
+
type: "json",
|
|
522
|
+
value: JSON.stringify({
|
|
523
|
+
bridgeAction: "OUTBOUND_EXIT_RELAYER_FEE",
|
|
524
|
+
chainId,
|
|
525
|
+
publishedMultiSigCertHash: input.publishedMultiSigCertHash.toLowerCase()
|
|
526
|
+
})
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
const ocapPostConditions = {
|
|
531
|
+
signer: sellerOcapDid,
|
|
532
|
+
maxTokenOutflow: { [abtOcapTokenAddress]: grossAbtBn.toString(10) },
|
|
533
|
+
strictZeroUnlistedOutflow: true
|
|
534
|
+
};
|
|
535
|
+
const fallbackToDirectAbt = input.fallbackToDirectAbtOnSwapFailure ?? true;
|
|
536
|
+
return {
|
|
537
|
+
mode: isDirectAbtExit ? "DIRECT_ABT_WITHDRAW" : "WITHDRAW_AND_UNISWAP_SWAP",
|
|
538
|
+
ocapBurnAndFeeStatements,
|
|
539
|
+
ocapPostConditions,
|
|
540
|
+
evmVaultReleaseSpec: {
|
|
541
|
+
vaultAddress: ocapVaultAddress,
|
|
542
|
+
vaultContractModified: false,
|
|
543
|
+
vaultTokenReleased: abtEvmAddress,
|
|
544
|
+
releaseRecipientAddress: isDirectAbtExit ? recipientEvmAddress : withdrawSwapperAddress,
|
|
545
|
+
netAbtReleased: netAbtToSwapBn.toString(10),
|
|
546
|
+
publishedMultiSigCertHash: input.publishedMultiSigCertHash.toLowerCase()
|
|
547
|
+
},
|
|
548
|
+
evmSwapPayload,
|
|
549
|
+
fallbackSafetySpec: {
|
|
550
|
+
fallbackToDirectAbtOnSwapFailure: fallbackToDirectAbt,
|
|
551
|
+
fallbackRecipientEvmAddress: recipientEvmAddress,
|
|
552
|
+
fallbackTokenAddress: abtEvmAddress,
|
|
553
|
+
fallbackAmountAbt: netAbtToSwapBn.toString(10),
|
|
554
|
+
swapperRetainsZeroBalanceAfterTx: true
|
|
555
|
+
},
|
|
556
|
+
economics: {
|
|
557
|
+
userBearsExitCost: true,
|
|
558
|
+
protocolSubsidyAbt: "0",
|
|
559
|
+
grossAbtWithdrawAmount: grossAbtBn.toString(10),
|
|
560
|
+
relayerExitFeeAbt: relayerExitFeeBn.toString(10),
|
|
561
|
+
netAbtToSwap: netAbtToSwapBn.toString(10),
|
|
562
|
+
expectedTargetTokenOut: expectedTargetTokenOutStr,
|
|
563
|
+
minimumTargetTokenOut: minimumTargetTokenOutStr
|
|
564
|
+
},
|
|
565
|
+
clearSigningSummary: {
|
|
566
|
+
youPay: `${grossAbtBn.toString(10)} ABT (Net Swap: ${netAbtToSwapBn.toString(10)} ABT + Exit Fee: ${relayerExitFeeBn.toString(10)} ABT)`,
|
|
567
|
+
actions: isDirectAbtExit ? [`Lock ${netAbtToSwapBn.toString(10)} ABT in OCAP Bridge Escrow (${ocapBridgeEscrowDid})`, `Release ${netAbtToSwapBn.toString(10)} ABT from MultiSigVaultV2 (${ocapVaultAddress}) to ${recipientEvmAddress}`] : [
|
|
568
|
+
`Lock ${netAbtToSwapBn.toString(10)} ABT in OCAP Bridge Escrow (${ocapBridgeEscrowDid})`,
|
|
569
|
+
`Release ${netAbtToSwapBn.toString(10)} ABT from MultiSigVaultV2 (${ocapVaultAddress}) to Stateless Swapper (${withdrawSwapperAddress})`,
|
|
570
|
+
`Swap ${netAbtToSwapBn.toString(10)} ABT -> ${targetPayoutTokenAddress} via Uniswap Universal Router (${universalRouterAddress})`
|
|
571
|
+
],
|
|
572
|
+
youReceiveMinimum: `${minimumTargetTokenOutStr} (${targetPayoutTokenAddress}) at ${recipientEvmAddress}`
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
//#endregion
|
|
578
|
+
export { ABT_DECIMALS_SCALE, CHAINALYSIS_OFAC_ORACLE_ADDRESS, DEFAULT_OCAP_INTEGRATOR_ID, DEFAULT_USD_QUOTE_TTL_SECONDS, MAX_ALLOWED_ZAP_SLIPPAGE_BPS, MAX_ROUTE_PATH_LENGTH, MAX_USD_QUOTE_TTL_SECONDS, UNIVERSAL_ROUTER_COMMANDS, assertNotOfacSanctioned, buildAbtUtilityPassThroughPlan, buildOutboundWithdrawAndSwapPlan, buildUniversalRouterCrossChainPayload, createUsdAnchoredAbtQuote, normalizeScreeningAddress, verifyUsdAnchoredAbtQuote };
|