@veridex/sdk 1.1.5 → 1.1.7
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/dist/{EVMClient-Bmy9czkE.d.mts → EVMClient-DqDiFak8.d.mts} +1 -1
- package/dist/auth/prepareAuth.d.mts +5 -4
- package/dist/auth/prepareAuth.js +143 -1422
- package/dist/auth/prepareAuth.js.map +1 -1
- package/dist/auth/prepareAuth.mjs +17 -96
- package/dist/auth/prepareAuth.mjs.map +1 -1
- package/dist/chains/aptos/index.d.mts +1 -1
- package/dist/chains/aptos/index.js +11 -33
- package/dist/chains/aptos/index.js.map +1 -1
- package/dist/chains/aptos/index.mjs +2 -2
- package/dist/chains/avalanche/index.d.mts +2 -2
- package/dist/chains/avalanche/index.js +19 -115
- package/dist/chains/avalanche/index.js.map +1 -1
- package/dist/chains/avalanche/index.mjs +3 -3
- package/dist/chains/evm/index.d.mts +5 -4
- package/dist/chains/evm/index.js +19 -115
- package/dist/chains/evm/index.js.map +1 -1
- package/dist/chains/evm/index.mjs +2 -2
- package/dist/chains/solana/index.d.mts +1 -1
- package/dist/chains/solana/index.js +11 -33
- package/dist/chains/solana/index.js.map +1 -1
- package/dist/chains/solana/index.mjs +2 -2
- package/dist/chains/stacks/index.d.mts +1 -1
- package/dist/chains/stacks/index.js +11 -38
- package/dist/chains/stacks/index.js.map +1 -1
- package/dist/chains/stacks/index.mjs +2 -2
- package/dist/chains/starknet/index.d.mts +36 -2
- package/dist/chains/starknet/index.js +208 -37
- package/dist/chains/starknet/index.js.map +1 -1
- package/dist/chains/starknet/index.mjs +9 -4
- package/dist/chains/stellar/index.d.mts +2 -1
- package/dist/chains/sui/index.d.mts +1 -1
- package/dist/chains/sui/index.js +11 -27
- package/dist/chains/sui/index.js.map +1 -1
- package/dist/chains/sui/index.mjs +2 -2
- package/dist/{chunk-ZNIVNPGF.mjs → chunk-3PCAVZUZ.mjs} +173 -37
- package/dist/chunk-3PCAVZUZ.mjs.map +1 -0
- package/dist/{chunk-DQOW3G7M.mjs → chunk-6BINP4RT.mjs} +48 -9
- package/dist/{chunk-DQOW3G7M.mjs.map → chunk-6BINP4RT.mjs.map} +1 -1
- package/dist/{chunk-7KN6Y4GX.mjs → chunk-AK5HWYX4.mjs} +12 -40
- package/dist/chunk-AK5HWYX4.mjs.map +1 -0
- package/dist/{chunk-QVTADARB.mjs → chunk-FPSCAGYS.mjs} +12 -35
- package/dist/chunk-FPSCAGYS.mjs.map +1 -0
- package/dist/{chunk-USVZH4QC.mjs → chunk-H3WRT6Y4.mjs} +20 -117
- package/dist/chunk-H3WRT6Y4.mjs.map +1 -0
- package/dist/{chunk-GXJUY2SC.mjs → chunk-MNH22BM2.mjs} +12 -35
- package/dist/chunk-MNH22BM2.mjs.map +1 -0
- package/dist/chunk-N42LPFPJ.mjs +177 -0
- package/dist/chunk-N42LPFPJ.mjs.map +1 -0
- package/dist/{chunk-D57UJ4L5.mjs → chunk-NKSRF45N.mjs} +12 -29
- package/dist/chunk-NKSRF45N.mjs.map +1 -0
- package/dist/{chunk-BJH5HJL5.mjs → chunk-SKZLZFE2.mjs} +91 -65
- package/dist/chunk-SKZLZFE2.mjs.map +1 -0
- package/dist/{chunk-NVRAQPSF.mjs → chunk-UF5NWMSQ.mjs} +20 -4
- package/dist/chunk-UF5NWMSQ.mjs.map +1 -0
- package/dist/chunk-WC4X3MAO.mjs +58 -0
- package/dist/chunk-WC4X3MAO.mjs.map +1 -0
- package/dist/{chunk-5FH67KLG.mjs → chunk-XHDOSV2F.mjs} +2 -2
- package/dist/{index-CKKUV4J7.d.mts → index-D1nb2JV9.d.mts} +2 -2
- package/dist/index-qyOqd8tx.d.mts +517 -0
- package/dist/index.d.mts +30 -366
- package/dist/index.js +2412 -2486
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +986 -55
- package/dist/index.mjs.map +1 -1
- package/dist/passkey-fh8bo2w-.d.mts +241 -0
- package/dist/passkey.d.mts +2 -182
- package/dist/passkey.js +86 -7
- package/dist/passkey.js.map +1 -1
- package/dist/passkey.mjs +2 -1
- package/dist/payload.d.mts +22 -28
- package/dist/payload.js +50 -9
- package/dist/payload.js.map +1 -1
- package/dist/payload.mjs +7 -3
- package/dist/platform/index.d.mts +3 -0
- package/dist/platform/index.js +216 -0
- package/dist/platform/index.js.map +1 -0
- package/dist/platform/index.mjs +21 -0
- package/dist/platform/index.mjs.map +1 -0
- package/dist/{portfolio-W2FQ2G3O.mjs → portfolio-MLP2JIFK.mjs} +2 -3
- package/dist/queries/index.mjs +324 -10
- package/dist/queries/index.mjs.map +1 -1
- package/dist/{types-DP2CQT8p.d.mts → types-CdlEbixV.d.mts} +12 -1
- package/dist/types.d.mts +1 -0
- package/dist/types.js.map +1 -1
- package/package.json +7 -1
- package/dist/chunk-72ZA3OYQ.mjs +0 -20
- package/dist/chunk-72ZA3OYQ.mjs.map +0 -1
- package/dist/chunk-7KN6Y4GX.mjs.map +0 -1
- package/dist/chunk-BJH5HJL5.mjs.map +0 -1
- package/dist/chunk-D57UJ4L5.mjs.map +0 -1
- package/dist/chunk-GXJUY2SC.mjs.map +0 -1
- package/dist/chunk-NVRAQPSF.mjs.map +0 -1
- package/dist/chunk-QVTADARB.mjs.map +0 -1
- package/dist/chunk-USVZH4QC.mjs.map +0 -1
- package/dist/chunk-XDIIFIW6.mjs +0 -330
- package/dist/chunk-XDIIFIW6.mjs.map +0 -1
- package/dist/chunk-ZNIVNPGF.mjs.map +0 -1
- package/dist/chunk-ZXMTPBSP.mjs +0 -857
- package/dist/chunk-ZXMTPBSP.mjs.map +0 -1
- /package/dist/{chunk-5FH67KLG.mjs.map → chunk-XHDOSV2F.mjs.map} +0 -0
- /package/dist/{portfolio-W2FQ2G3O.mjs.map → portfolio-MLP2JIFK.mjs.map} +0 -0
package/dist/queries/index.mjs
CHANGED
|
@@ -1,19 +1,333 @@
|
|
|
1
1
|
import {
|
|
2
2
|
QueryPortfolioError,
|
|
3
|
-
queryPortfolio
|
|
4
|
-
} from "../chunk-NVRAQPSF.mjs";
|
|
5
|
-
import {
|
|
6
|
-
QueryHubStateError,
|
|
7
|
-
queryHubState
|
|
8
|
-
} from "../chunk-XDIIFIW6.mjs";
|
|
9
|
-
import {
|
|
10
3
|
WORMHOLE_QUERY_CHAIN_IDS,
|
|
11
4
|
WORMHOLE_QUERY_PROXY_URLS,
|
|
12
|
-
WORMHOLE_QUERY_RATE_LIMIT_PER_SECOND
|
|
13
|
-
|
|
5
|
+
WORMHOLE_QUERY_RATE_LIMIT_PER_SECOND,
|
|
6
|
+
queryPortfolio
|
|
7
|
+
} from "../chunk-UF5NWMSQ.mjs";
|
|
14
8
|
import "../chunk-GEVTBQH2.mjs";
|
|
15
9
|
import "../chunk-VABK3ID3.mjs";
|
|
16
|
-
import
|
|
10
|
+
import {
|
|
11
|
+
MAINNET_CHAINS,
|
|
12
|
+
TESTNET_CHAINS
|
|
13
|
+
} from "../chunk-KYOOTSRA.mjs";
|
|
14
|
+
|
|
15
|
+
// src/queries/hubState.ts
|
|
16
|
+
import axios from "axios";
|
|
17
|
+
import { Buffer } from "buffer";
|
|
18
|
+
import { ethers } from "ethers";
|
|
19
|
+
import {
|
|
20
|
+
EthCallQueryRequest,
|
|
21
|
+
EthCallQueryResponse,
|
|
22
|
+
PerChainQueryRequest,
|
|
23
|
+
QueryRequest,
|
|
24
|
+
QueryResponse,
|
|
25
|
+
hexToUint8Array,
|
|
26
|
+
isValidHexString
|
|
27
|
+
} from "@wormhole-foundation/wormhole-query-sdk";
|
|
28
|
+
var QueryHubStateError = class extends Error {
|
|
29
|
+
code;
|
|
30
|
+
cause;
|
|
31
|
+
constructor(code, message, cause) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "QueryHubStateError";
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.cause = cause;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
function resolveNetwork(options) {
|
|
39
|
+
if (options?.network) return options.network;
|
|
40
|
+
const envCandidates = [
|
|
41
|
+
globalThis?.process?.env?.NEXT_PUBLIC_VERIDEX_NETWORK,
|
|
42
|
+
globalThis?.process?.env?.VERIDEX_NETWORK,
|
|
43
|
+
globalThis?.process?.env?.NEXT_PUBLIC_WORMHOLE_NETWORK,
|
|
44
|
+
globalThis?.process?.env?.WORMHOLE_NETWORK
|
|
45
|
+
].filter(Boolean);
|
|
46
|
+
const env = envCandidates[0]?.toLowerCase();
|
|
47
|
+
if (env === "mainnet" || env === "testnet") return env;
|
|
48
|
+
return "testnet";
|
|
49
|
+
}
|
|
50
|
+
function concatBytes(parts) {
|
|
51
|
+
const total = parts.reduce((sum, p) => sum + p.length, 0);
|
|
52
|
+
const out = new Uint8Array(total);
|
|
53
|
+
let offset = 0;
|
|
54
|
+
for (const p of parts) {
|
|
55
|
+
out.set(p, offset);
|
|
56
|
+
offset += p.length;
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
function signaturesToProofBytes(signatures) {
|
|
61
|
+
const chunks = [];
|
|
62
|
+
for (const sig of signatures) {
|
|
63
|
+
if (typeof sig !== "string" || sig.length !== 132 || !/^[0-9a-fA-F]+$/.test(sig)) {
|
|
64
|
+
throw new QueryHubStateError(
|
|
65
|
+
"PROXY_RESPONSE_INVALID",
|
|
66
|
+
`Invalid guardian signature format (expected 132 hex chars): ${String(sig)}`
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
chunks.push(hexToUint8Array(`0x${sig}`));
|
|
70
|
+
}
|
|
71
|
+
return concatBytes(chunks);
|
|
72
|
+
}
|
|
73
|
+
function decodeQueryBytes(bytes) {
|
|
74
|
+
if (typeof bytes !== "string" || bytes.length === 0) {
|
|
75
|
+
throw new QueryHubStateError("PROXY_RESPONSE_INVALID", "Missing query response bytes");
|
|
76
|
+
}
|
|
77
|
+
if (isValidHexString(bytes)) {
|
|
78
|
+
return hexToUint8Array(bytes);
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
if (typeof atob === "function") {
|
|
82
|
+
const raw = atob(bytes);
|
|
83
|
+
const arr = new Uint8Array(raw.length);
|
|
84
|
+
for (let i = 0; i < raw.length; i++) arr[i] = raw.charCodeAt(i);
|
|
85
|
+
return arr;
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
return new Uint8Array(Buffer.from(bytes, "base64"));
|
|
91
|
+
} catch (cause) {
|
|
92
|
+
throw new QueryHubStateError("PROXY_RESPONSE_INVALID", "Unrecognized query response bytes encoding", cause);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function sleep(ms) {
|
|
96
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
97
|
+
}
|
|
98
|
+
async function withExponentialBackoff(fn, maxAttempts) {
|
|
99
|
+
let attempt = 0;
|
|
100
|
+
let lastError;
|
|
101
|
+
while (attempt < maxAttempts) {
|
|
102
|
+
try {
|
|
103
|
+
return await fn();
|
|
104
|
+
} catch (err) {
|
|
105
|
+
lastError = err;
|
|
106
|
+
attempt += 1;
|
|
107
|
+
if (attempt >= maxAttempts) break;
|
|
108
|
+
const baseMs = 250;
|
|
109
|
+
const backoffMs = Math.min(5e3, baseMs * 2 ** (attempt - 1));
|
|
110
|
+
const jitterMs = Math.floor(Math.random() * 100);
|
|
111
|
+
await sleep(backoffMs + jitterMs);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
throw lastError;
|
|
115
|
+
}
|
|
116
|
+
function getHubConfig(network) {
|
|
117
|
+
if (network === "testnet") {
|
|
118
|
+
const baseSepolia = TESTNET_CHAINS.baseSepolia;
|
|
119
|
+
if (!baseSepolia?.contracts?.hub) {
|
|
120
|
+
throw new QueryHubStateError("MISSING_HUB_ADDRESS", "Missing Base Sepolia hub address in SDK constants");
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
wormholeChainId: baseSepolia.wormholeChainId,
|
|
124
|
+
hubAddress: baseSepolia.contracts.hub,
|
|
125
|
+
endpoint: WORMHOLE_QUERY_PROXY_URLS.testnet,
|
|
126
|
+
rpcUrl: baseSepolia.rpcUrl
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
if (network === "mainnet") {
|
|
130
|
+
const base = MAINNET_CHAINS.base;
|
|
131
|
+
const hubAddress = base?.contracts?.hub;
|
|
132
|
+
if (!hubAddress) {
|
|
133
|
+
throw new QueryHubStateError(
|
|
134
|
+
"MISSING_HUB_ADDRESS",
|
|
135
|
+
"Missing mainnet hub address in SDK constants (MAINNET_CHAINS.base.contracts.hub)"
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
wormholeChainId: base.wormholeChainId,
|
|
140
|
+
hubAddress,
|
|
141
|
+
endpoint: WORMHOLE_QUERY_PROXY_URLS.mainnet,
|
|
142
|
+
rpcUrl: base.rpcUrl
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
throw new QueryHubStateError("UNSUPPORTED_NETWORK", `Unsupported network: ${network}`);
|
|
146
|
+
}
|
|
147
|
+
function encodeHubCalls(hubAddress, userKeyHash) {
|
|
148
|
+
const nonceAbiCandidates = [
|
|
149
|
+
"function getUserNonce(bytes32 userKeyHash) view returns (uint256)",
|
|
150
|
+
"function userNonces(bytes32 userKeyHash) view returns (uint256)",
|
|
151
|
+
"function getNonceByHash(bytes32 userKeyHash) view returns (uint256)"
|
|
152
|
+
];
|
|
153
|
+
const registeredAbiCandidates = [
|
|
154
|
+
"function registeredKeys(bytes32 userKeyHash) view returns (bool)",
|
|
155
|
+
"function isKeyRegisteredByHash(bytes32 userKeyHash) view returns (bool)"
|
|
156
|
+
];
|
|
157
|
+
const actionHashAbiCandidates = [
|
|
158
|
+
"function getUserLastActionHash(bytes32 userKeyHash) view returns (bytes32)",
|
|
159
|
+
"function userLastActionHash(bytes32 userKeyHash) view returns (bytes32)"
|
|
160
|
+
];
|
|
161
|
+
const iface = new ethers.Interface([
|
|
162
|
+
...nonceAbiCandidates,
|
|
163
|
+
...registeredAbiCandidates,
|
|
164
|
+
...actionHashAbiCandidates
|
|
165
|
+
]);
|
|
166
|
+
const nonceFnNames = ["getUserNonce", "userNonces", "getNonceByHash"];
|
|
167
|
+
const regFnNames = ["registeredKeys", "isKeyRegisteredByHash"];
|
|
168
|
+
const actionHashFnNames = ["getUserLastActionHash", "userLastActionHash"];
|
|
169
|
+
return [
|
|
170
|
+
...nonceFnNames.map((fn) => ({
|
|
171
|
+
to: hubAddress,
|
|
172
|
+
data: iface.encodeFunctionData(fn, [userKeyHash])
|
|
173
|
+
})),
|
|
174
|
+
...regFnNames.map((fn) => ({
|
|
175
|
+
to: hubAddress,
|
|
176
|
+
data: iface.encodeFunctionData(fn, [userKeyHash])
|
|
177
|
+
})),
|
|
178
|
+
...actionHashFnNames.map((fn) => ({
|
|
179
|
+
to: hubAddress,
|
|
180
|
+
data: iface.encodeFunctionData(fn, [userKeyHash])
|
|
181
|
+
}))
|
|
182
|
+
];
|
|
183
|
+
}
|
|
184
|
+
function decodeFirstNonce(results) {
|
|
185
|
+
const candidates = [
|
|
186
|
+
"function getUserNonce(bytes32 userKeyHash) view returns (uint256)",
|
|
187
|
+
"function userNonces(bytes32 userKeyHash) view returns (uint256)",
|
|
188
|
+
"function getNonceByHash(bytes32 userKeyHash) view returns (uint256)"
|
|
189
|
+
];
|
|
190
|
+
const iface = new ethers.Interface(candidates);
|
|
191
|
+
const fnNames = ["getUserNonce", "userNonces", "getNonceByHash"];
|
|
192
|
+
for (let idx = 0; idx < fnNames.length; idx++) {
|
|
193
|
+
const fnName = fnNames[idx];
|
|
194
|
+
try {
|
|
195
|
+
const data = results[idx];
|
|
196
|
+
if (!data || data === "0x") continue;
|
|
197
|
+
const decoded = iface.decodeFunctionResult(fnName, data);
|
|
198
|
+
return decoded[0];
|
|
199
|
+
} catch {
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
throw new QueryHubStateError("QUERY_RESPONSE_INVALID", "Unable to decode user nonce from query response");
|
|
203
|
+
}
|
|
204
|
+
function decodeFirstIsRegistered(results) {
|
|
205
|
+
const nonceCandidateCount = 3;
|
|
206
|
+
const candidates = [
|
|
207
|
+
"function registeredKeys(bytes32 userKeyHash) view returns (bool)",
|
|
208
|
+
"function isKeyRegisteredByHash(bytes32 userKeyHash) view returns (bool)"
|
|
209
|
+
];
|
|
210
|
+
const iface = new ethers.Interface(candidates);
|
|
211
|
+
const fnNames = ["registeredKeys", "isKeyRegisteredByHash"];
|
|
212
|
+
for (let i = 0; i < fnNames.length; i++) {
|
|
213
|
+
const fnName = fnNames[i];
|
|
214
|
+
try {
|
|
215
|
+
const data = results[nonceCandidateCount + i];
|
|
216
|
+
if (!data || data === "0x") continue;
|
|
217
|
+
const decoded = iface.decodeFunctionResult(fnName, data);
|
|
218
|
+
return Boolean(decoded[0]);
|
|
219
|
+
} catch {
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
function decodeLastActionHash(results) {
|
|
225
|
+
const nonceCandidateCount = 3;
|
|
226
|
+
const registeredCandidateCount = 2;
|
|
227
|
+
const actionHashOffset = nonceCandidateCount + registeredCandidateCount;
|
|
228
|
+
const candidates = [
|
|
229
|
+
"function getUserLastActionHash(bytes32 userKeyHash) view returns (bytes32)",
|
|
230
|
+
"function userLastActionHash(bytes32 userKeyHash) view returns (bytes32)"
|
|
231
|
+
];
|
|
232
|
+
const iface = new ethers.Interface(candidates);
|
|
233
|
+
const fnNames = ["getUserLastActionHash", "userLastActionHash"];
|
|
234
|
+
for (let i = 0; i < fnNames.length; i++) {
|
|
235
|
+
const fnName = fnNames[i];
|
|
236
|
+
try {
|
|
237
|
+
const data = results[actionHashOffset + i];
|
|
238
|
+
if (!data || data === "0x") continue;
|
|
239
|
+
const decoded = iface.decodeFunctionResult(fnName, data);
|
|
240
|
+
return decoded[0];
|
|
241
|
+
} catch {
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return ethers.ZeroHash;
|
|
245
|
+
}
|
|
246
|
+
async function queryHubState(userKeyHash, apiKey, options) {
|
|
247
|
+
if (typeof userKeyHash !== "string" || userKeyHash.length === 0) {
|
|
248
|
+
throw new QueryHubStateError("INVALID_ARGUMENT", "userKeyHash is required");
|
|
249
|
+
}
|
|
250
|
+
if (!isValidHexString(userKeyHash) || hexToUint8Array(userKeyHash).length !== 32) {
|
|
251
|
+
throw new QueryHubStateError("INVALID_ARGUMENT", "userKeyHash must be a 32-byte hex string");
|
|
252
|
+
}
|
|
253
|
+
if (typeof apiKey !== "string" || apiKey.length === 0) {
|
|
254
|
+
throw new QueryHubStateError("INVALID_ARGUMENT", "apiKey is required");
|
|
255
|
+
}
|
|
256
|
+
const network = resolveNetwork(options);
|
|
257
|
+
const maxAgeSeconds = options?.maxAge ?? 60;
|
|
258
|
+
const maxAttempts = options?.maxAttempts ?? 4;
|
|
259
|
+
const { wormholeChainId, hubAddress, endpoint, rpcUrl } = getHubConfig(network);
|
|
260
|
+
const provider = new ethers.JsonRpcProvider(rpcUrl);
|
|
261
|
+
const callData = encodeHubCalls(hubAddress, userKeyHash);
|
|
262
|
+
const doFetch = async () => {
|
|
263
|
+
try {
|
|
264
|
+
const latestBlock = await provider.getBlockNumber();
|
|
265
|
+
const blockTag = Math.max(0, latestBlock - 2);
|
|
266
|
+
const request = new QueryRequest(Date.now() & 4294967295, [
|
|
267
|
+
new PerChainQueryRequest(wormholeChainId, new EthCallQueryRequest(blockTag, callData))
|
|
268
|
+
]);
|
|
269
|
+
const requestHex = Buffer.from(request.serialize()).toString("hex");
|
|
270
|
+
const response = await axios.post(
|
|
271
|
+
endpoint,
|
|
272
|
+
{ bytes: requestHex },
|
|
273
|
+
{
|
|
274
|
+
headers: {
|
|
275
|
+
"X-API-Key": apiKey,
|
|
276
|
+
"Content-Type": "application/json"
|
|
277
|
+
},
|
|
278
|
+
timeout: 1e4
|
|
279
|
+
}
|
|
280
|
+
);
|
|
281
|
+
const data = response.data;
|
|
282
|
+
const signatures = data?.signatures;
|
|
283
|
+
const bytes = data?.bytes;
|
|
284
|
+
if (!Array.isArray(signatures) || typeof bytes !== "string") {
|
|
285
|
+
throw new QueryHubStateError("PROXY_RESPONSE_INVALID", "Query Proxy response missing signatures/bytes");
|
|
286
|
+
}
|
|
287
|
+
const proof = signaturesToProofBytes(signatures);
|
|
288
|
+
const queryBytes = decodeQueryBytes(bytes);
|
|
289
|
+
const parsed = QueryResponse.from(queryBytes);
|
|
290
|
+
const perChain = parsed.responses.find((r) => r.chainId === wormholeChainId);
|
|
291
|
+
if (!perChain) {
|
|
292
|
+
throw new QueryHubStateError("QUERY_RESPONSE_INVALID", "Missing per-chain response for hub chain");
|
|
293
|
+
}
|
|
294
|
+
const chainResp = EthCallQueryResponse.from(perChain.response.serialize());
|
|
295
|
+
const blockTime = Number(chainResp.blockTime);
|
|
296
|
+
const nowSeconds = Math.floor(Date.now() / 1e3);
|
|
297
|
+
if (nowSeconds - blockTime > maxAgeSeconds) {
|
|
298
|
+
throw new QueryHubStateError(
|
|
299
|
+
"ATTESTATION_STALE",
|
|
300
|
+
`Guardian attestation is stale (blockTime=${blockTime}, now=${nowSeconds}, maxAge=${maxAgeSeconds}s)`
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
const nonce = decodeFirstNonce(chainResp.results);
|
|
304
|
+
const isRegistered = decodeFirstIsRegistered(chainResp.results);
|
|
305
|
+
const lastActionHash = decodeLastActionHash(chainResp.results);
|
|
306
|
+
return {
|
|
307
|
+
nonce,
|
|
308
|
+
isRegistered,
|
|
309
|
+
blockTime,
|
|
310
|
+
proof,
|
|
311
|
+
lastActionHash
|
|
312
|
+
};
|
|
313
|
+
} catch (err) {
|
|
314
|
+
if (err instanceof QueryHubStateError) throw err;
|
|
315
|
+
if (axios.isAxiosError(err)) {
|
|
316
|
+
const ax = err;
|
|
317
|
+
const status = ax.response?.status;
|
|
318
|
+
const statusText = ax.response?.statusText;
|
|
319
|
+
const details = typeof ax.response?.data === "string" ? ax.response?.data : void 0;
|
|
320
|
+
throw new QueryHubStateError(
|
|
321
|
+
"PROXY_HTTP_ERROR",
|
|
322
|
+
`Query Proxy request failed${status ? ` (${status} ${statusText ?? ""})` : ""}${details ? `: ${details}` : ""}`,
|
|
323
|
+
err
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
throw new QueryHubStateError("PROXY_HTTP_ERROR", "Query Proxy request failed", err);
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
return await withExponentialBackoff(doFetch, maxAttempts);
|
|
330
|
+
}
|
|
17
331
|
export {
|
|
18
332
|
QueryHubStateError,
|
|
19
333
|
QueryPortfolioError,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/queries/hubState.ts"],"sourcesContent":["import axios, { AxiosError } from 'axios';\nimport { Buffer } from 'buffer';\nimport { ethers } from 'ethers';\nimport {\n EthCallQueryRequest,\n EthCallQueryResponse,\n PerChainQueryRequest,\n QueryRequest,\n QueryResponse,\n hexToUint8Array,\n isValidHexString,\n} from '@wormhole-foundation/wormhole-query-sdk';\n\nimport { MAINNET_CHAINS, TESTNET_CHAINS } from '../constants.js';\nimport { WORMHOLE_QUERY_PROXY_URLS } from './constants.js';\n\nexport type QueryHubStateNetwork = 'testnet' | 'mainnet';\n\nexport type QueryHubStateOptions = {\n /** Max response age in seconds (default: 60). */\n maxAge?: number;\n network?: QueryHubStateNetwork;\n /** Maximum attempts including the first try (default: 4). */\n maxAttempts?: number;\n};\n\nexport type HubStateResult = {\n nonce: bigint;\n isRegistered: boolean;\n blockTime: number;\n proof: Uint8Array;\n /** Last action hash (Issue #9/#10 - for action-hash binding) */\n lastActionHash?: string;\n};\n\nexport type QueryHubStateErrorCode =\n | 'INVALID_ARGUMENT'\n | 'UNSUPPORTED_NETWORK'\n | 'MISSING_HUB_ADDRESS'\n | 'PROXY_HTTP_ERROR'\n | 'PROXY_RESPONSE_INVALID'\n | 'ATTESTATION_STALE'\n | 'QUERY_RESPONSE_INVALID';\n\nexport class QueryHubStateError extends Error {\n code: QueryHubStateErrorCode;\n cause?: unknown;\n\n constructor(code: QueryHubStateErrorCode, message: string, cause?: unknown) {\n super(message);\n this.name = 'QueryHubStateError';\n this.code = code;\n this.cause = cause;\n }\n}\n\nfunction resolveNetwork(options?: QueryHubStateOptions): QueryHubStateNetwork {\n if (options?.network) return options.network;\n\n const envCandidates = [\n (globalThis as any)?.process?.env?.NEXT_PUBLIC_VERIDEX_NETWORK,\n (globalThis as any)?.process?.env?.VERIDEX_NETWORK,\n (globalThis as any)?.process?.env?.NEXT_PUBLIC_WORMHOLE_NETWORK,\n (globalThis as any)?.process?.env?.WORMHOLE_NETWORK,\n ].filter(Boolean);\n\n const env = (envCandidates[0] as string | undefined)?.toLowerCase();\n if (env === 'mainnet' || env === 'testnet') return env;\n\n // Default to testnet to support Base Sepolia out-of-the-box.\n return 'testnet';\n}\n\nfunction concatBytes(parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, p) => sum + p.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nfunction signaturesToProofBytes(signatures: string[]): Uint8Array {\n const chunks: Uint8Array[] = [];\n\n for (const sig of signatures) {\n if (typeof sig !== 'string' || sig.length !== 132 || !/^[0-9a-fA-F]+$/.test(sig)) {\n throw new QueryHubStateError(\n 'PROXY_RESPONSE_INVALID',\n `Invalid guardian signature format (expected 132 hex chars): ${String(sig)}`\n );\n }\n // Avoid Node Buffer-backed Uint8Array (can surface as SharedArrayBuffer in DTS types).\n chunks.push(hexToUint8Array(`0x${sig}`));\n }\n\n return concatBytes(chunks);\n}\n\nfunction decodeQueryBytes(bytes: string): Uint8Array {\n if (typeof bytes !== 'string' || bytes.length === 0) {\n throw new QueryHubStateError('PROXY_RESPONSE_INVALID', 'Missing query response bytes');\n }\n\n // Query Proxy commonly returns a 0x-prefixed hex string.\n if (isValidHexString(bytes)) {\n return hexToUint8Array(bytes);\n }\n\n // Fallback: attempt base64 decoding.\n try {\n if (typeof atob === 'function') {\n const raw = atob(bytes);\n const arr = new Uint8Array(raw.length);\n for (let i = 0; i < raw.length; i++) arr[i] = raw.charCodeAt(i);\n return arr;\n }\n } catch {\n // ignore\n }\n\n try {\n return new Uint8Array(Buffer.from(bytes, 'base64'));\n } catch (cause) {\n throw new QueryHubStateError('PROXY_RESPONSE_INVALID', 'Unrecognized query response bytes encoding', cause);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function withExponentialBackoff<T>(\n fn: () => Promise<T>,\n maxAttempts: number\n): Promise<T> {\n let attempt = 0;\n let lastError: unknown;\n\n while (attempt < maxAttempts) {\n try {\n return await fn();\n } catch (err) {\n lastError = err;\n attempt += 1;\n if (attempt >= maxAttempts) break;\n\n const baseMs = 250;\n const backoffMs = Math.min(5_000, baseMs * 2 ** (attempt - 1));\n const jitterMs = Math.floor(Math.random() * 100);\n await sleep(backoffMs + jitterMs);\n }\n }\n\n throw lastError;\n}\n\nfunction getHubConfig(network: QueryHubStateNetwork): {\n wormholeChainId: number;\n hubAddress: string;\n endpoint: string;\n rpcUrl: string;\n} {\n if (network === 'testnet') {\n const baseSepolia = TESTNET_CHAINS.baseSepolia;\n if (!baseSepolia?.contracts?.hub) {\n throw new QueryHubStateError('MISSING_HUB_ADDRESS', 'Missing Base Sepolia hub address in SDK constants');\n }\n\n return {\n wormholeChainId: baseSepolia.wormholeChainId,\n hubAddress: baseSepolia.contracts.hub,\n endpoint: WORMHOLE_QUERY_PROXY_URLS.testnet,\n rpcUrl: baseSepolia.rpcUrl,\n };\n }\n\n if (network === 'mainnet') {\n const base = MAINNET_CHAINS.base;\n const hubAddress = (base?.contracts as any)?.hub as string | undefined;\n\n if (!hubAddress) {\n throw new QueryHubStateError(\n 'MISSING_HUB_ADDRESS',\n 'Missing mainnet hub address in SDK constants (MAINNET_CHAINS.base.contracts.hub)'\n );\n }\n\n return {\n wormholeChainId: base.wormholeChainId,\n hubAddress,\n endpoint: WORMHOLE_QUERY_PROXY_URLS.mainnet,\n rpcUrl: base.rpcUrl,\n };\n }\n\n throw new QueryHubStateError('UNSUPPORTED_NETWORK', `Unsupported network: ${network}`);\n}\n\nfunction encodeHubCalls(hubAddress: string, userKeyHash: string): { to: string; data: string }[] {\n // Support both the spec name and known on-chain variants.\n const nonceAbiCandidates = [\n 'function getUserNonce(bytes32 userKeyHash) view returns (uint256)',\n 'function userNonces(bytes32 userKeyHash) view returns (uint256)',\n 'function getNonceByHash(bytes32 userKeyHash) view returns (uint256)',\n ];\n\n const registeredAbiCandidates = [\n 'function registeredKeys(bytes32 userKeyHash) view returns (bool)',\n 'function isKeyRegisteredByHash(bytes32 userKeyHash) view returns (bool)',\n ];\n\n // Issue #9/#10: Add getUserLastActionHash for action-hash binding\n const actionHashAbiCandidates = [\n 'function getUserLastActionHash(bytes32 userKeyHash) view returns (bytes32)',\n 'function userLastActionHash(bytes32 userKeyHash) view returns (bytes32)',\n ];\n\n // We encode *all* candidates; the proxy will execute each call, and we decode the first successful one.\n // This makes the client resilient to Hub ABI differences across deployments.\n const iface = new ethers.Interface([\n ...nonceAbiCandidates,\n ...registeredAbiCandidates,\n ...actionHashAbiCandidates,\n ]);\n\n const nonceFnNames = ['getUserNonce', 'userNonces', 'getNonceByHash'] as const;\n const regFnNames = ['registeredKeys', 'isKeyRegisteredByHash'] as const;\n const actionHashFnNames = ['getUserLastActionHash', 'userLastActionHash'] as const;\n\n return [\n ...nonceFnNames.map((fn) => ({\n to: hubAddress,\n data: iface.encodeFunctionData(fn, [userKeyHash]),\n })),\n ...regFnNames.map((fn) => ({\n to: hubAddress,\n data: iface.encodeFunctionData(fn, [userKeyHash]),\n })),\n ...actionHashFnNames.map((fn) => ({\n to: hubAddress,\n data: iface.encodeFunctionData(fn, [userKeyHash]),\n })),\n ];\n}\n\nfunction decodeFirstNonce(results: string[]): bigint {\n const candidates = [\n 'function getUserNonce(bytes32 userKeyHash) view returns (uint256)',\n 'function userNonces(bytes32 userKeyHash) view returns (uint256)',\n 'function getNonceByHash(bytes32 userKeyHash) view returns (uint256)',\n ];\n const iface = new ethers.Interface(candidates);\n const fnNames = ['getUserNonce', 'userNonces', 'getNonceByHash'] as const;\n\n for (let idx = 0; idx < fnNames.length; idx++) {\n const fnName = fnNames[idx];\n try {\n const data = results[idx];\n if (!data || data === '0x') continue;\n const decoded = iface.decodeFunctionResult(fnName, data);\n return decoded[0] as bigint;\n } catch {\n // keep trying\n }\n }\n\n throw new QueryHubStateError('QUERY_RESPONSE_INVALID', 'Unable to decode user nonce from query response');\n}\n\nfunction decodeFirstIsRegistered(results: string[]): boolean {\n const nonceCandidateCount = 3;\n const candidates = [\n 'function registeredKeys(bytes32 userKeyHash) view returns (bool)',\n 'function isKeyRegisteredByHash(bytes32 userKeyHash) view returns (bool)',\n ];\n const iface = new ethers.Interface(candidates);\n const fnNames = ['registeredKeys', 'isKeyRegisteredByHash'] as const;\n\n for (let i = 0; i < fnNames.length; i++) {\n const fnName = fnNames[i];\n try {\n const data = results[nonceCandidateCount + i];\n if (!data || data === '0x') continue;\n const decoded = iface.decodeFunctionResult(fnName, data);\n return Boolean(decoded[0]);\n } catch {\n // keep trying\n }\n }\n\n // If the hub deployment doesn’t support registration, treat as false.\n return false;\n}\n\n/** * Decode last action hash from query results (Issue #9/#10)\n * Returns zero hash if not available (backwards compatibility)\n */\nfunction decodeLastActionHash(results: string[]): string {\n const nonceCandidateCount = 3;\n const registeredCandidateCount = 2;\n const actionHashOffset = nonceCandidateCount + registeredCandidateCount;\n\n const candidates = [\n 'function getUserLastActionHash(bytes32 userKeyHash) view returns (bytes32)',\n 'function userLastActionHash(bytes32 userKeyHash) view returns (bytes32)',\n ];\n const iface = new ethers.Interface(candidates);\n const fnNames = ['getUserLastActionHash', 'userLastActionHash'] as const;\n\n for (let i = 0; i < fnNames.length; i++) {\n const fnName = fnNames[i];\n try {\n const data = results[actionHashOffset + i];\n if (!data || data === '0x') continue;\n const decoded = iface.decodeFunctionResult(fnName, data);\n return decoded[0] as string;\n } catch {\n // keep trying\n }\n }\n\n // Backwards compatibility: return zero hash if not available\n return ethers.ZeroHash;\n}\n\n/** * Fetch Guardian-attested Hub state directly from the Wormhole Query Proxy.\n *\n * Client-side only: this avoids relayer API costs and produces a Guardian-signed proof\n * that can be forwarded to the relayer for on-chain verification/submission.\n */\nexport async function queryHubState(\n userKeyHash: string,\n apiKey: string,\n options?: QueryHubStateOptions\n): Promise<HubStateResult> {\n if (typeof userKeyHash !== 'string' || userKeyHash.length === 0) {\n throw new QueryHubStateError('INVALID_ARGUMENT', 'userKeyHash is required');\n }\n if (!isValidHexString(userKeyHash) || hexToUint8Array(userKeyHash).length !== 32) {\n throw new QueryHubStateError('INVALID_ARGUMENT', 'userKeyHash must be a 32-byte hex string');\n }\n if (typeof apiKey !== 'string' || apiKey.length === 0) {\n throw new QueryHubStateError('INVALID_ARGUMENT', 'apiKey is required');\n }\n\n const network = resolveNetwork(options);\n const maxAgeSeconds = options?.maxAge ?? 60;\n const maxAttempts = options?.maxAttempts ?? 4;\n\n const { wormholeChainId, hubAddress, endpoint, rpcUrl } = getHubConfig(network);\n\n const provider = new ethers.JsonRpcProvider(rpcUrl);\n\n const callData = encodeHubCalls(hubAddress, userKeyHash);\n\n const doFetch = async () => {\n try {\n const latestBlock = await provider.getBlockNumber();\n const blockTag = Math.max(0, latestBlock - 2);\n\n const request = new QueryRequest(Date.now() & 0xffffffff, [\n new PerChainQueryRequest(wormholeChainId, new EthCallQueryRequest(blockTag, callData)),\n ]);\n\n // Wormhole Query Proxy expects raw hex WITHOUT 0x prefix\n const requestHex = Buffer.from(request.serialize()).toString('hex');\n\n const response = await axios.post(\n endpoint,\n { bytes: requestHex },\n {\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n },\n timeout: 10_000,\n }\n );\n\n const data = response.data as any;\n const signatures = data?.signatures as string[] | undefined;\n const bytes = data?.bytes as string | undefined;\n\n if (!Array.isArray(signatures) || typeof bytes !== 'string') {\n throw new QueryHubStateError('PROXY_RESPONSE_INVALID', 'Query Proxy response missing signatures/bytes');\n }\n\n const proof = signaturesToProofBytes(signatures);\n const queryBytes = decodeQueryBytes(bytes);\n const parsed = QueryResponse.from(queryBytes);\n\n const perChain = parsed.responses.find((r) => r.chainId === wormholeChainId);\n if (!perChain) {\n throw new QueryHubStateError('QUERY_RESPONSE_INVALID', 'Missing per-chain response for hub chain');\n }\n\n // The SDK provides a parser for the chain-specific response.\n const chainResp = EthCallQueryResponse.from(perChain.response.serialize());\n const blockTime = Number(chainResp.blockTime);\n\n const nowSeconds = Math.floor(Date.now() / 1000);\n if (nowSeconds - blockTime > maxAgeSeconds) {\n throw new QueryHubStateError(\n 'ATTESTATION_STALE',\n `Guardian attestation is stale (blockTime=${blockTime}, now=${nowSeconds}, maxAge=${maxAgeSeconds}s)`\n );\n }\n\n const nonce = decodeFirstNonce(chainResp.results);\n const isRegistered = decodeFirstIsRegistered(chainResp.results);\n const lastActionHash = decodeLastActionHash(chainResp.results);\n\n return {\n nonce,\n isRegistered,\n blockTime,\n proof,\n lastActionHash,\n } satisfies HubStateResult;\n } catch (err) {\n if (err instanceof QueryHubStateError) throw err;\n if (axios.isAxiosError(err)) {\n const ax = err as AxiosError;\n const status = ax.response?.status;\n const statusText = ax.response?.statusText;\n const details = typeof ax.response?.data === 'string' ? ax.response?.data : undefined;\n\n throw new QueryHubStateError(\n 'PROXY_HTTP_ERROR',\n `Query Proxy request failed${status ? ` (${status} ${statusText ?? ''})` : ''}${details ? `: ${details}` : ''}`,\n err\n );\n }\n\n throw new QueryHubStateError('PROXY_HTTP_ERROR', 'Query Proxy request failed', err);\n }\n };\n\n return await withExponentialBackoff(doFetch, maxAttempts);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,OAAO,WAA2B;AAClC,SAAS,cAAc;AACvB,SAA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AU,OAAO;AAE7D,aAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,eAAe,mBAAoB,OAAM;AAC7C,UAAI,MAAM,aAAa,GAAG,GAAG;AAC3B,cAAM,KAAK;AACX,cAAM,SAAS,GAAG,UAAU;AAC5B,cAAM,aAAa,GAAG,UAAU;AAChC,cAAM,UAAU,OAAO,GAAG,UAAU,SAAS,WAAW,GAAG,UAAU,OAAO;AAE5E,cAAM,IAAI;AAAA,UACR;AAAA,UACA,6BAA6B,SAAS,KAAK,MAAM,IAAI,cAAc,EAAE,MAAM,EAAE,GAAG,UAAU,KAAK,OAAO,KAAK,EAAE;AAAA,UAC7G;AAAA,QACF;AAAA,MACF;AAEA,YAAM,IAAI,mBAAmB,oBAAoB,8BAA8B,GAAG;AAAA,IACpF;AAAA,EACF;AAEA,SAAO,MAAM,uBAAuB,SAAS,WAAW;AAC1D;","names":[]}
|
|
@@ -17,6 +17,8 @@ interface VeridexConfig {
|
|
|
17
17
|
* API key for relayer service authentication
|
|
18
18
|
*/
|
|
19
19
|
relayerApiKey?: string;
|
|
20
|
+
/** Locally trusted v3 destination metadata, keyed by transport chain ID. */
|
|
21
|
+
dispatchDestinations?: Record<number, DispatchDestinationV3>;
|
|
20
22
|
/**
|
|
21
23
|
* API key for Wormhole Query Proxy requests (optional).
|
|
22
24
|
* If omitted, the SDK will fall back to `relayerApiKey` for Queries.
|
|
@@ -42,6 +44,8 @@ interface VeridexConfig {
|
|
|
42
44
|
* Allows platforms to pay for their users' vault creation
|
|
43
45
|
*/
|
|
44
46
|
integratorSponsorKey?: string;
|
|
47
|
+
/** @deprecated Enables legacy in-process raw private-key sponsorship. Prefer relayerUrl. */
|
|
48
|
+
allowLegacyPrivateKeyFallback?: boolean;
|
|
45
49
|
/**
|
|
46
50
|
* Additional chain RPC URLs for multi-chain sponsored vault creation
|
|
47
51
|
* Maps Wormhole chain ID to RPC URL
|
|
@@ -53,6 +57,12 @@ interface VeridexConfig {
|
|
|
53
57
|
*/
|
|
54
58
|
preparedTransferTtl?: number;
|
|
55
59
|
}
|
|
60
|
+
interface DispatchDestinationV3 {
|
|
61
|
+
targetChain: number;
|
|
62
|
+
veridexChainId: number;
|
|
63
|
+
executor: string;
|
|
64
|
+
minTier: number;
|
|
65
|
+
}
|
|
56
66
|
interface WalletManagerConfig {
|
|
57
67
|
/**
|
|
58
68
|
* Whether to cache computed addresses in memory
|
|
@@ -181,6 +191,7 @@ interface PasskeyCredential {
|
|
|
181
191
|
publicKeyX: bigint;
|
|
182
192
|
publicKeyY: bigint;
|
|
183
193
|
keyHash: string;
|
|
194
|
+
assurance?: any;
|
|
184
195
|
}
|
|
185
196
|
interface WebAuthnSignature {
|
|
186
197
|
authenticatorData: string;
|
|
@@ -573,4 +584,4 @@ interface BridgeResult extends DispatchResult {
|
|
|
573
584
|
timestamp: number;
|
|
574
585
|
}
|
|
575
586
|
|
|
576
|
-
export type { AuthorizedKey as A, BridgeParams as B, ChainClient as C,
|
|
587
|
+
export type { AuthorizedKey as A, BridgeParams as B, ChainClient as C, DispatchDestinationV3 as D, ExecuteParams as E, IdentityState as I, PasskeyCredential as P, ReceiveAddress as R, SessionValidationResult as S, TransferParams as T, UnifiedIdentity as U, VaultCreationResult as V, WebAuthnSignature as W, ChainConfig as a, DispatchResult as b, WalletManagerConfig as c, ChainAddress as d, VAA as e, VeridexPayload as f, PreparedTransfer as g, PreparedBridge as h, VeridexConfig as i, BridgeResult as j, TransferResult as k, VaultInfo as l, AddBackupKeyResult as m, RemoveKeyResult as n, ConfigParams as o, TransferAction as p, BridgeAction as q, ExecuteAction as r, ConfigAction as s, ActionPayload as t, VAASignature as u, TestResult as v, TransactionHistoryEntry as w, CrossChainFees as x, RegisterSessionParams as y, RevokeSessionParams as z };
|
package/dist/types.d.mts
CHANGED
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["/**\n * Veridex Protocol SDK - Type Definitions\n */\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\nexport interface VeridexConfig {\n hubChainId: number;\n hubRpcUrl: string;\n hubContractAddress: string;\n relayerUrl?: string;\n}\n\nexport interface ChainConfig {\n name: string;\n chainId: number;\n wormholeChainId: number;\n hubChainId?: number; // Wormhole chain ID of the Hub (for cross-chain auth)\n rpcUrl: string;\n explorerUrl: string;\n isEvm: boolean;\n contracts: {\n hub?: string;\n vaultFactory?: string;\n vaultImplementation?: string;\n wormholeCoreBridge: string;\n tokenBridge?: string;\n /** Wormhole guardian signature verifier (Stacks Phase 2) */\n wormholeVerifier?: string;\n /** VAA-authorized vault for cross-chain transfers (Stacks Phase 2) */\n vaultVaa?: string;\n /** Agent marketplace contract (Monad Agent Gateway) */\n serviceDirectory?: string;\n /** ACP-204 P-256 verifier wrapper (Avalanche) */\n p256Verifier?: string;\n /** ICM Spoke for cross-L1 session bridging (Avalanche Teleporter) */\n icmSpoke?: string;\n /** Chainlink AVAX/USD price feed (Avalanche) */\n chainlinkAvaxUsd?: string;\n /** Chainlink USDC/USD price feed (Avalanche) */\n chainlinkUsdcUsd?: string;\n /** Chainlink USDT/USD price feed (Avalanche) */\n chainlinkUsdtUsd?: string;\n };\n}\n\n// ============================================================================\n// Credential Types\n// ============================================================================\n\nexport interface PasskeyCredential {\n credentialId: string;\n publicKeyX: bigint;\n publicKeyY: bigint;\n keyHash: string;\n}\n\nexport interface WebAuthnSignature {\n authenticatorData: string;\n clientDataJSON: string;\n challengeIndex: number;\n typeIndex: number;\n r: bigint;\n s: bigint;\n}\n\n// ============================================================================\n// Action Types\n// ============================================================================\n\nexport interface TransferParams {\n targetChain: number;\n token: string; // address or \"native\"\n recipient: string;\n amount: bigint;\n}\n\nexport interface ExecuteParams {\n targetChain: number;\n target: string;\n value: bigint;\n data: string;\n}\n\nexport interface BridgeParams {\n sourceChain: number; // Chain where vault holds the tokens\n token: string; // Token address (or \"native\" for native token)\n amount: bigint;\n destinationChain: number; // Wormhole chain ID of destination\n recipient: string; // Recipient address on destination chain (hex string)\n}\n\nexport interface DispatchResult {\n transactionHash: string;\n sequence: bigint;\n userKeyHash: string;\n targetChain: number;\n}\n\n// ============================================================================\n// Action Payload Types\n// ============================================================================\n\nexport interface TransferAction {\n type: 'transfer';\n token: string;\n recipient: string;\n amount: bigint;\n}\n\nexport interface BridgeAction {\n type: 'bridge';\n token: string;\n amount: bigint;\n targetChain: number;\n recipient: string;\n}\n\n// ============================================================================\n// Query Types (Issue #9/#10/#11/#12)\n// ============================================================================\n\n/**\n * Wormhole Query proof for optimistic execution\n * Allows ~5-7 second latency vs ~120+ seconds for VAA\n */\nexport interface QueryProof {\n /** Raw query response bytes from Wormhole Guardians */\n queryResponse: string; // hex\n /** Guardian signatures (13/19 quorum) */\n signatures: string; // hex\n}\n\n/**\n * User preference for execution path\n */\nexport type ExecutionPath = 'query' | 'vaa' | 'auto';\n\n/**\n * Result from query-based submission\n */\nexport interface QuerySubmissionResult {\n /** Whether submission succeeded */\n success: boolean;\n /** Transaction hash on spoke chain */\n txHash?: string;\n /** Execution path used ('query' or 'vaa') */\n path: ExecutionPath;\n /** Latency in milliseconds */\n latencyMs?: number;\n /** Error message if failed */\n error?: string;\n /** Whether fallback to VAA was triggered */\n fellBack?: boolean;\n}\n\n// ============================================================================\n// Session Key Types (Issue #13)\n// ============================================================================\n\n/**\n * Session key structure for temporary authentication\n * Enables native L1 speed for repeat transactions without biometric auth\n */\nexport interface SessionKey {\n /** Hash of the temporary session public key */\n sessionKeyHash: string;\n /** Unix timestamp when session expires */\n expiry: number;\n /** Maximum transaction value for this session (0 = unlimited) */\n maxValue: bigint;\n /** Whether session was manually revoked */\n revoked: boolean;\n}\n\n/**\n * Result from session validation query\n */\nexport interface SessionValidationResult {\n /** Whether session is currently active */\n active: boolean;\n /** Session expiry timestamp (0 if inactive) */\n expiry: number;\n /** Maximum transaction value (0 if inactive) */\n maxValue: bigint;\n /** Index in sessions array */\n sessionIndex: number;\n}\n\n/**\n * Parameters for registering a new session\n */\nexport interface RegisterSessionParams {\n /** Signature for Passkey authentication */\n signature: WebAuthnSignature;\n /** User's Passkey public key X coordinate */\n publicKeyX: bigint;\n /** User's Passkey public key Y coordinate */\n publicKeyY: bigint;\n /** Hash of the temporary session public key */\n sessionKeyHash: string;\n /** Session duration in seconds (max 24 hours) */\n duration: number;\n /** Maximum transaction value (0 = unlimited) */\n maxValue: bigint;\n /** Whether to require user verification */\n requireUV: boolean;\n}\n\n/**\n * Parameters for revoking a session\n */\nexport interface RevokeSessionParams {\n /** Signature for Passkey authentication */\n signature: WebAuthnSignature;\n /** User's Passkey public key X coordinate */\n publicKeyX: bigint;\n /** User's Passkey public key Y coordinate */\n publicKeyY: bigint;\n /** Hash of the session key to revoke */\n sessionKeyHash: string;\n /** Whether to require user verification */\n requireUV: boolean;\n}\n\n// ============================================================================\n// Backup Passkey / Multi-Key Identity Types (Issue #22)\n// ============================================================================\n\n/**\n * Identity state for multi-key management\n * First passkey registered becomes the immutable identity root\n */\nexport interface IdentityState {\n /** Identity key hash (first passkey's keyHash) */\n identity: string;\n /** Number of authorized keys */\n keyCount: number;\n /** Maximum allowed keys per identity */\n maxKeys: number;\n /** Whether the specified key is the root identity */\n isRoot: boolean;\n}\n\n/**\n * Result from registering a backup passkey\n */\nexport interface AddBackupKeyResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the key was added to */\n identity: string;\n /** The new key hash that was added */\n newKeyHash: string;\n /** Total number of keys after addition */\n keyCount: number;\n}\n\n/**\n * Result from removing a passkey\n */\nexport interface RemoveKeyResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the key was removed from */\n identity: string;\n /** The key hash that was removed */\n removedKeyHash: string;\n /** Remaining number of keys after removal */\n keyCount: number;\n}\n\n/**\n * Authorized key information\n */\nexport interface AuthorizedKey {\n /** Key hash of the authorized passkey */\n keyHash: string;\n /** Whether this key is the root identity key */\n isRoot: boolean;\n}\n\n// =============================================================================\n// SOCIAL RECOVERY TYPES (Issue #23)\n// =============================================================================\n\n/**\n * Guardian configuration for an identity\n */\nexport interface GuardianConfig {\n /** Array of guardian key hashes */\n guardians: string[];\n /** Required approvals for recovery (M-of-N) */\n threshold: bigint;\n /** Whether guardians have been configured */\n isConfigured: boolean;\n}\n\n/**\n * Recovery status for an identity\n */\nexport interface RecoveryStatus {\n /** Whether a recovery is currently active */\n isActive: boolean;\n /** Proposed new owner key hash */\n newOwnerKeyHash: string;\n /** Timestamp when recovery was initiated */\n initiatedAt: bigint;\n /** Current number of guardian approvals */\n approvalCount: bigint;\n /** Required approvals for recovery */\n threshold: bigint;\n /** Timestamp when recovery can be executed (after timelock) */\n canExecuteAt: bigint;\n /** Timestamp when recovery expires */\n expiresAt: bigint;\n}\n\n/**\n * Result from setting up guardians\n */\nexport interface SetupGuardiansResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity guardians were set up for */\n identity: string;\n /** Array of guardian key hashes */\n guardians: string[];\n /** Required approvals for recovery */\n threshold: bigint;\n}\n\n/**\n * Result from adding a guardian\n */\nexport interface AddGuardianResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the guardian was added to */\n identity: string;\n /** The guardian key hash that was added */\n guardianKeyHash: string;\n}\n\n/**\n * Result from removing a guardian\n */\nexport interface RemoveGuardianResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the guardian was removed from */\n identity: string;\n /** The guardian key hash that was removed */\n guardianKeyHash: string;\n}\n\n/**\n * Result from initiating recovery\n */\nexport interface InitiateRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity being recovered */\n identity: string;\n /** Proposed new owner key hash */\n newOwnerKeyHash: string;\n /** Timestamp when recovery can be executed */\n canExecuteAt: bigint;\n}\n\n/**\n * Result from approving recovery\n */\nexport interface ApproveRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity being recovered */\n identity: string;\n /** The guardian who approved */\n guardianKeyHash: string;\n /** Current approval count */\n approvalCount: bigint;\n /** Required approvals */\n threshold: bigint;\n}\n\n/**\n * Result from executing recovery\n */\nexport interface ExecuteRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity that was recovered */\n identity: string;\n /** The new owner key hash */\n newOwnerKeyHash: string;\n}\n\n/**\n * Result from cancelling recovery\n */\nexport interface CancelRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity whose recovery was cancelled */\n identity: string;\n}\n\nexport interface ExecuteAction {\n type: 'execute';\n target: string;\n value: bigint;\n data: string;\n}\n\nexport interface ConfigAction {\n type: 'config';\n configType: number;\n configData: string;\n}\n\nexport type ActionPayload = TransferAction | BridgeAction | ExecuteAction | ConfigAction | { type: string; raw: string };\n\n// ============================================================================\n// VAA Types\n// ============================================================================\n\nexport interface VAA {\n version: number;\n guardianSetIndex: number;\n signatures: VAASignature[];\n timestamp: number;\n nonce: number;\n emitterChain: number;\n emitterAddress: string;\n sequence: bigint;\n consistencyLevel: number;\n payload: string;\n hash: string; // keccak256 of the body (for verification)\n}\n\nexport interface VAASignature {\n guardianIndex: number;\n signature: string;\n}\n\nexport interface VeridexPayload {\n version: number;\n userKeyHash: string;\n targetChain: number;\n nonce: bigint;\n publicKeyX: bigint;\n publicKeyY: bigint;\n actionPayload: string;\n}\n\n// ============================================================================\n// Vault Types\n// ============================================================================\n\nexport interface VaultInfo {\n address: string;\n ownerKeyHash: string;\n chain: string;\n wormholeChainId: number;\n}\n\n// ============================================================================\n// Test Result Types\n// ============================================================================\n\nexport interface TestResult {\n success: boolean;\n sourceChain: string;\n targetChain: string;\n txHash?: string;\n vaaSequence?: bigint;\n error?: string;\n duration?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["/**\n * Veridex Protocol SDK - Type Definitions\n */\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\nexport interface VeridexConfig {\n hubChainId: number;\n hubRpcUrl: string;\n hubContractAddress: string;\n relayerUrl?: string;\n}\n\nexport interface ChainConfig {\n name: string;\n chainId: number;\n wormholeChainId: number;\n hubChainId?: number; // Wormhole chain ID of the Hub (for cross-chain auth)\n rpcUrl: string;\n explorerUrl: string;\n isEvm: boolean;\n contracts: {\n hub?: string;\n vaultFactory?: string;\n vaultImplementation?: string;\n wormholeCoreBridge: string;\n tokenBridge?: string;\n /** Wormhole guardian signature verifier (Stacks Phase 2) */\n wormholeVerifier?: string;\n /** VAA-authorized vault for cross-chain transfers (Stacks Phase 2) */\n vaultVaa?: string;\n /** Agent marketplace contract (Monad Agent Gateway) */\n serviceDirectory?: string;\n /** ACP-204 P-256 verifier wrapper (Avalanche) */\n p256Verifier?: string;\n /** ICM Spoke for cross-L1 session bridging (Avalanche Teleporter) */\n icmSpoke?: string;\n /** Chainlink AVAX/USD price feed (Avalanche) */\n chainlinkAvaxUsd?: string;\n /** Chainlink USDC/USD price feed (Avalanche) */\n chainlinkUsdcUsd?: string;\n /** Chainlink USDT/USD price feed (Avalanche) */\n chainlinkUsdtUsd?: string;\n };\n}\n\n// ============================================================================\n// Credential Types\n// ============================================================================\n\nexport interface PasskeyCredential {\n credentialId: string;\n publicKeyX: bigint;\n publicKeyY: bigint;\n keyHash: string;\n assurance?: any;\n}\n\nexport interface WebAuthnSignature {\n authenticatorData: string;\n clientDataJSON: string;\n challengeIndex: number;\n typeIndex: number;\n r: bigint;\n s: bigint;\n}\n\n// ============================================================================\n// Action Types\n// ============================================================================\n\nexport interface TransferParams {\n targetChain: number;\n token: string; // address or \"native\"\n recipient: string;\n amount: bigint;\n}\n\nexport interface ExecuteParams {\n targetChain: number;\n target: string;\n value: bigint;\n data: string;\n}\n\nexport interface BridgeParams {\n sourceChain: number; // Chain where vault holds the tokens\n token: string; // Token address (or \"native\" for native token)\n amount: bigint;\n destinationChain: number; // Wormhole chain ID of destination\n recipient: string; // Recipient address on destination chain (hex string)\n}\n\nexport interface DispatchResult {\n transactionHash: string;\n sequence: bigint;\n userKeyHash: string;\n targetChain: number;\n}\n\n// ============================================================================\n// Action Payload Types\n// ============================================================================\n\nexport interface TransferAction {\n type: 'transfer';\n token: string;\n recipient: string;\n amount: bigint;\n}\n\nexport interface BridgeAction {\n type: 'bridge';\n token: string;\n amount: bigint;\n targetChain: number;\n recipient: string;\n}\n\n// ============================================================================\n// Query Types (Issue #9/#10/#11/#12)\n// ============================================================================\n\n/**\n * Wormhole Query proof for optimistic execution\n * Allows ~5-7 second latency vs ~120+ seconds for VAA\n */\nexport interface QueryProof {\n /** Raw query response bytes from Wormhole Guardians */\n queryResponse: string; // hex\n /** Guardian signatures (13/19 quorum) */\n signatures: string; // hex\n}\n\n/**\n * User preference for execution path\n */\nexport type ExecutionPath = 'query' | 'vaa' | 'auto';\n\n/**\n * Result from query-based submission\n */\nexport interface QuerySubmissionResult {\n /** Whether submission succeeded */\n success: boolean;\n /** Transaction hash on spoke chain */\n txHash?: string;\n /** Execution path used ('query' or 'vaa') */\n path: ExecutionPath;\n /** Latency in milliseconds */\n latencyMs?: number;\n /** Error message if failed */\n error?: string;\n /** Whether fallback to VAA was triggered */\n fellBack?: boolean;\n}\n\n// ============================================================================\n// Session Key Types (Issue #13)\n// ============================================================================\n\n/**\n * Session key structure for temporary authentication\n * Enables native L1 speed for repeat transactions without biometric auth\n */\nexport interface SessionKey {\n /** Hash of the temporary session public key */\n sessionKeyHash: string;\n /** Unix timestamp when session expires */\n expiry: number;\n /** Maximum transaction value for this session (0 = unlimited) */\n maxValue: bigint;\n /** Whether session was manually revoked */\n revoked: boolean;\n}\n\n/**\n * Result from session validation query\n */\nexport interface SessionValidationResult {\n /** Whether session is currently active */\n active: boolean;\n /** Session expiry timestamp (0 if inactive) */\n expiry: number;\n /** Maximum transaction value (0 if inactive) */\n maxValue: bigint;\n /** Index in sessions array */\n sessionIndex: number;\n}\n\n/**\n * Parameters for registering a new session\n */\nexport interface RegisterSessionParams {\n /** Signature for Passkey authentication */\n signature: WebAuthnSignature;\n /** User's Passkey public key X coordinate */\n publicKeyX: bigint;\n /** User's Passkey public key Y coordinate */\n publicKeyY: bigint;\n /** Hash of the temporary session public key */\n sessionKeyHash: string;\n /** Session duration in seconds (max 24 hours) */\n duration: number;\n /** Maximum transaction value (0 = unlimited) */\n maxValue: bigint;\n /** Whether to require user verification */\n requireUV: boolean;\n}\n\n/**\n * Parameters for revoking a session\n */\nexport interface RevokeSessionParams {\n /** Signature for Passkey authentication */\n signature: WebAuthnSignature;\n /** User's Passkey public key X coordinate */\n publicKeyX: bigint;\n /** User's Passkey public key Y coordinate */\n publicKeyY: bigint;\n /** Hash of the session key to revoke */\n sessionKeyHash: string;\n /** Whether to require user verification */\n requireUV: boolean;\n}\n\n// ============================================================================\n// Backup Passkey / Multi-Key Identity Types (Issue #22)\n// ============================================================================\n\n/**\n * Identity state for multi-key management\n * First passkey registered becomes the immutable identity root\n */\nexport interface IdentityState {\n /** Identity key hash (first passkey's keyHash) */\n identity: string;\n /** Number of authorized keys */\n keyCount: number;\n /** Maximum allowed keys per identity */\n maxKeys: number;\n /** Whether the specified key is the root identity */\n isRoot: boolean;\n}\n\n/**\n * Result from registering a backup passkey\n */\nexport interface AddBackupKeyResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the key was added to */\n identity: string;\n /** The new key hash that was added */\n newKeyHash: string;\n /** Total number of keys after addition */\n keyCount: number;\n}\n\n/**\n * Result from removing a passkey\n */\nexport interface RemoveKeyResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the key was removed from */\n identity: string;\n /** The key hash that was removed */\n removedKeyHash: string;\n /** Remaining number of keys after removal */\n keyCount: number;\n}\n\n/**\n * Authorized key information\n */\nexport interface AuthorizedKey {\n /** Key hash of the authorized passkey */\n keyHash: string;\n /** Whether this key is the root identity key */\n isRoot: boolean;\n}\n\n// =============================================================================\n// SOCIAL RECOVERY TYPES (Issue #23)\n// =============================================================================\n\n/**\n * Guardian configuration for an identity\n */\nexport interface GuardianConfig {\n /** Array of guardian key hashes */\n guardians: string[];\n /** Required approvals for recovery (M-of-N) */\n threshold: bigint;\n /** Whether guardians have been configured */\n isConfigured: boolean;\n}\n\n/**\n * Recovery status for an identity\n */\nexport interface RecoveryStatus {\n /** Whether a recovery is currently active */\n isActive: boolean;\n /** Proposed new owner key hash */\n newOwnerKeyHash: string;\n /** Timestamp when recovery was initiated */\n initiatedAt: bigint;\n /** Current number of guardian approvals */\n approvalCount: bigint;\n /** Required approvals for recovery */\n threshold: bigint;\n /** Timestamp when recovery can be executed (after timelock) */\n canExecuteAt: bigint;\n /** Timestamp when recovery expires */\n expiresAt: bigint;\n}\n\n/**\n * Result from setting up guardians\n */\nexport interface SetupGuardiansResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity guardians were set up for */\n identity: string;\n /** Array of guardian key hashes */\n guardians: string[];\n /** Required approvals for recovery */\n threshold: bigint;\n}\n\n/**\n * Result from adding a guardian\n */\nexport interface AddGuardianResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the guardian was added to */\n identity: string;\n /** The guardian key hash that was added */\n guardianKeyHash: string;\n}\n\n/**\n * Result from removing a guardian\n */\nexport interface RemoveGuardianResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity the guardian was removed from */\n identity: string;\n /** The guardian key hash that was removed */\n guardianKeyHash: string;\n}\n\n/**\n * Result from initiating recovery\n */\nexport interface InitiateRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity being recovered */\n identity: string;\n /** Proposed new owner key hash */\n newOwnerKeyHash: string;\n /** Timestamp when recovery can be executed */\n canExecuteAt: bigint;\n}\n\n/**\n * Result from approving recovery\n */\nexport interface ApproveRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity being recovered */\n identity: string;\n /** The guardian who approved */\n guardianKeyHash: string;\n /** Current approval count */\n approvalCount: bigint;\n /** Required approvals */\n threshold: bigint;\n}\n\n/**\n * Result from executing recovery\n */\nexport interface ExecuteRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity that was recovered */\n identity: string;\n /** The new owner key hash */\n newOwnerKeyHash: string;\n}\n\n/**\n * Result from cancelling recovery\n */\nexport interface CancelRecoveryResult {\n /** Transaction hash on Hub chain */\n transactionHash: string;\n /** Wormhole sequence number for cross-chain sync */\n sequence: bigint;\n /** The identity whose recovery was cancelled */\n identity: string;\n}\n\nexport interface ExecuteAction {\n type: 'execute';\n target: string;\n value: bigint;\n data: string;\n}\n\nexport interface ConfigAction {\n type: 'config';\n configType: number;\n configData: string;\n}\n\nexport type ActionPayload = TransferAction | BridgeAction | ExecuteAction | ConfigAction | { type: string; raw: string };\n\n// ============================================================================\n// VAA Types\n// ============================================================================\n\nexport interface VAA {\n version: number;\n guardianSetIndex: number;\n signatures: VAASignature[];\n timestamp: number;\n nonce: number;\n emitterChain: number;\n emitterAddress: string;\n sequence: bigint;\n consistencyLevel: number;\n payload: string;\n hash: string; // keccak256 of the body (for verification)\n}\n\nexport interface VAASignature {\n guardianIndex: number;\n signature: string;\n}\n\nexport interface VeridexPayload {\n version: number;\n userKeyHash: string;\n targetChain: number;\n nonce: bigint;\n publicKeyX: bigint;\n publicKeyY: bigint;\n actionPayload: string;\n}\n\n// ============================================================================\n// Vault Types\n// ============================================================================\n\nexport interface VaultInfo {\n address: string;\n ownerKeyHash: string;\n chain: string;\n wormholeChainId: number;\n}\n\n// ============================================================================\n// Test Result Types\n// ============================================================================\n\nexport interface TestResult {\n success: boolean;\n sourceChain: string;\n targetChain: string;\n txHash?: string;\n vaaSequence?: bigint;\n error?: string;\n duration?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@veridex/sdk",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.7",
|
|
4
4
|
"description": "Veridex Protocol SDK - Client library for Passkey-based cross-chain authentication",
|
|
5
5
|
"author": "Veridex Protocol <team@veridex.network>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -108,6 +108,11 @@
|
|
|
108
108
|
"types": "./dist/auth/prepareAuth.d.ts",
|
|
109
109
|
"import": "./dist/auth/prepareAuth.mjs",
|
|
110
110
|
"require": "./dist/auth/prepareAuth.js"
|
|
111
|
+
},
|
|
112
|
+
"./platform": {
|
|
113
|
+
"types": "./dist/platform/index.d.ts",
|
|
114
|
+
"import": "./dist/platform/index.mjs",
|
|
115
|
+
"require": "./dist/platform/index.js"
|
|
111
116
|
}
|
|
112
117
|
},
|
|
113
118
|
"scripts": {
|
|
@@ -133,6 +138,7 @@
|
|
|
133
138
|
"@solana/web3.js": "^1.95.4",
|
|
134
139
|
"@wormhole-foundation/sdk": "^0.10.0",
|
|
135
140
|
"@wormhole-foundation/wormhole-query-sdk": "^0.0.14",
|
|
141
|
+
"@veridex/platform-events": "0.1.0",
|
|
136
142
|
"axios": "^1.7.9",
|
|
137
143
|
"ethers": "^6.11.1",
|
|
138
144
|
"js-sha3": "^0.9.3",
|
package/dist/chunk-72ZA3OYQ.mjs
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
// src/queries/constants.ts
|
|
2
|
-
var WORMHOLE_QUERY_PROXY_URLS = {
|
|
3
|
-
mainnet: "https://query.wormhole.com/v1/query",
|
|
4
|
-
testnet: "https://testnet.query.wormhole.com/v1/query"
|
|
5
|
-
};
|
|
6
|
-
var WORMHOLE_QUERY_RATE_LIMIT_PER_SECOND = 6;
|
|
7
|
-
var WORMHOLE_QUERY_CHAIN_IDS = {
|
|
8
|
-
ETHEREUM: 2,
|
|
9
|
-
POLYGON: 5,
|
|
10
|
-
ARBITRUM: 23,
|
|
11
|
-
OPTIMISM: 24,
|
|
12
|
-
BASE: 30
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
export {
|
|
16
|
-
WORMHOLE_QUERY_PROXY_URLS,
|
|
17
|
-
WORMHOLE_QUERY_RATE_LIMIT_PER_SECOND,
|
|
18
|
-
WORMHOLE_QUERY_CHAIN_IDS
|
|
19
|
-
};
|
|
20
|
-
//# sourceMappingURL=chunk-72ZA3OYQ.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/queries/constants.ts"],"sourcesContent":["export const WORMHOLE_QUERY_PROXY_URLS = {\n mainnet: 'https://query.wormhole.com/v1/query',\n testnet: 'https://testnet.query.wormhole.com/v1/query',\n} as const;\n\n/**\n * Wormhole Query Proxy rate limit: 6 queries per second.\n * SDK callers should throttle requests accordingly.\n */\nexport const WORMHOLE_QUERY_RATE_LIMIT_PER_SECOND = 6;\n\n/**\n * Convenience set of Wormhole chain IDs commonly supported by Queries.\n * This is not an exhaustive list of all Wormhole chains.\n */\nexport const WORMHOLE_QUERY_CHAIN_IDS = {\n ETHEREUM: 2,\n POLYGON: 5,\n ARBITRUM: 23,\n OPTIMISM: 24,\n BASE: 30,\n} as const;\n"],"mappings":";AAAO,IAAM,4BAA4B;AAAA,EACvC,SAAS;AAAA,EACT,SAAS;AACX;AAMO,IAAM,uCAAuC;AAM7C,IAAM,2BAA2B;AAAA,EACtC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AAAA,EACV,MAAM;AACR;","names":[]}
|