@flapsdk/vault-runtime 0.1.33-next.1 → 0.1.34
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/README.md +2 -2
- package/chunk-22KTLOYH.js +73 -0
- package/chunk-22KTLOYH.js.map +1 -0
- package/chunk-AGLB72HK.js +61 -0
- package/chunk-AGLB72HK.js.map +1 -0
- package/{chunk-SVYURGMV.js → chunk-CXCG5MGE.js} +506 -52
- package/chunk-CXCG5MGE.js.map +1 -0
- package/chunk-JVZ4TFPY.js +945 -0
- package/chunk-JVZ4TFPY.js.map +1 -0
- package/host-client.d.mts +23 -0
- package/host-client.js +12 -0
- package/host-client.js.map +1 -0
- package/host.d.mts +6 -4
- package/host.js +5 -3
- package/host.js.map +1 -1
- package/{hostRuntimeConfig-Yc9-iwI8.d.mts → hostRuntimeConfig-Dl9t_R9u.d.mts} +1 -1
- package/{mpegts-J2J6JTD7.js → mpegts-6MFVUHRP.js} +6 -6
- package/{mpegts-J2J6JTD7.js.map → mpegts-6MFVUHRP.js.map} +1 -1
- package/package.json +3 -4
- package/runtime-contract.json +7 -1
- package/sdk.d.mts +9 -47
- package/sdk.js +10 -489
- package/sdk.js.map +1 -1
- package/server.d.mts +3 -3
- package/server.js +1 -1
- package/{txError-DIU819Wi.d.mts → txError-uPZICnzz.d.mts} +2 -15
- package/{types-BXHQvaxV.d.mts → types-_ifYbddY.d.mts} +98 -7
- package/ui.d.mts +1 -1
- package/ui.js +1 -1
- package/chunk-2YQUR2S6.js +0 -141
- package/chunk-2YQUR2S6.js.map +0 -1
- package/chunk-SVYURGMV.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flapsdk/vault-runtime",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "0.1.34",
|
|
4
|
+
"gitHead": "9d5b32e86c11f4d4535d32f2c0c688428306792e",
|
|
5
5
|
"description": "Shared runtime surface for Flap Vault UI hosts, Workbench preview, and custom Vault components.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": false,
|
|
@@ -45,7 +45,6 @@
|
|
|
45
45
|
"@rainbow-me/rainbowkit": "^2.1.7"
|
|
46
46
|
},
|
|
47
47
|
"publishConfig": {
|
|
48
|
-
"access": "public"
|
|
49
|
-
"tag": "next"
|
|
48
|
+
"access": "public"
|
|
50
49
|
}
|
|
51
50
|
}
|
package/runtime-contract.json
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"runtimeContractVersion": 1,
|
|
3
|
+
"sdkFeatures": {
|
|
4
|
+
"nftAccountWithdrawal": 1,
|
|
5
|
+
"resolvedContracts": 1,
|
|
6
|
+
"strictContractTargets": 1,
|
|
7
|
+
"hostOnlyProvider": 1
|
|
8
|
+
},
|
|
3
9
|
"packageName": "@flapsdk/vault-runtime",
|
|
4
|
-
"packageVersion": "0.1.
|
|
10
|
+
"packageVersion": "0.1.34",
|
|
5
11
|
"stableAuthoringAliases": [
|
|
6
12
|
"@/src/sdk",
|
|
7
13
|
"@/src/ui"
|
package/sdk.d.mts
CHANGED
|
@@ -1,38 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { A as ActionAvailabilityStage, C as ContractEventRequest, b as ContractReadRequest, c as ContractWriteRequest, F as FeeMode, e as FlapFeeVaultInfo, h as FlapTaxInfo, i as FlapTokenInfo, j as FlapVaultPortalInfo, M as ManifestBindingEntry, y as MediaUploadOptions,
|
|
3
|
-
export {
|
|
4
|
-
import * as React from 'react';
|
|
5
|
-
import { ReactNode } from 'react';
|
|
1
|
+
import { ae as VaultLaunchSchema, ab as VaultLaunchConfigResult, I as IpfsUploadResult, G as MediaUploader, D as MediaUploadRequest, P as NftMetadataReader, L as NftMetadataAttribute, k as FlapVaultSdk, a as Address, am as VaultRuntimeContext, f as FlapI18n, g as FlapNotify, l as FlapWallet } from './types-_ifYbddY.mjs';
|
|
2
|
+
export { A as ActionAvailabilityStage, C as ContractEventRequest, b as ContractReadRequest, c as ContractWriteRequest, F as FeeMode, e as FlapFeeVaultInfo, h as FlapTaxInfo, i as FlapTokenInfo, j as FlapVaultPortalInfo, M as ManifestBindingEntry, y as ManifestNftAccountWithdrawal, z as ManifestResolvedContract, B as MediaUploadOptions, N as NftAccountWithdrawalPolicy, J as NftAccountWithdrawalReceipt, K as NftAccountWithdrawalRequest, O as NftMetadataReadRequest, Q as NftMetadataReaderRequest, R as NftMetadataSnapshot, S as NftMetadataSource, T as OracleProvision, U as OracleReadRequest, V as OracleReader, X as PaymentToken, Y as ResolvedContractCheck, Z as ResolvedContractHandle, _ as ReviewedBeaconPin, $ as ReviewedContractPin, a0 as RuntimeOracleRegistry, a1 as SimulateResult, a2 as TokenMarketPhase, a5 as TxReceipt, a6 as VaultArtifactSurface, a7 as VaultComponentProps, a8 as VaultHostContext, a9 as VaultLaunchConfigComponentProps, aa as VaultLaunchConfigContext, ac as VaultLaunchConfigSummaryItem, ad as VaultLaunchConfigValues, af as VaultLaunchSchemaField, ag as VaultManifest, al as VaultRenderSurface, an as VaultRuntimeContextOverrides, ao as VaultRuntimeExtraConfig } from './types-_ifYbddY.mjs';
|
|
3
|
+
export { O as OracleReadError, Z as ZERO_ADDRESS, c as buildLocalOracleUrl, d as createLocalOracleReader, f as fetchOracleJson, g as fetchProvisionedOracle, h as formatCountdown, i as formatPercentBps, j as formatTokenAmount, l as getTxErrorKind, m as handleTxError, n as isActionAvailableForPhase, o as isCustomVaultTaxToken, r as isValidAddress, y as parseTokenAmount, A as readTaxVaultHostContext, F as resolveTokenMarketPhase, H as shortenAddress, I as standardErc20Abi } from './txError-uPZICnzz.mjs';
|
|
6
4
|
export { erc20Abi } from 'viem';
|
|
7
5
|
|
|
8
|
-
interface MiniAppSession {
|
|
9
|
-
address?: Address;
|
|
10
|
-
isConnected: boolean;
|
|
11
|
-
isAuthenticated: boolean;
|
|
12
|
-
isLoading: boolean;
|
|
13
|
-
connect(): void;
|
|
14
|
-
/** Uses the host's existing session; only prompts for a signature when needed. */
|
|
15
|
-
signIn(): Promise<void>;
|
|
16
|
-
}
|
|
17
|
-
interface MiniAppSdk {
|
|
18
|
-
context: {
|
|
19
|
-
appId: string;
|
|
20
|
-
slug: string;
|
|
21
|
-
manifest: VaultManifest;
|
|
22
|
-
};
|
|
23
|
-
session: MiniAppSession;
|
|
24
|
-
i18n: FlapI18n;
|
|
25
|
-
notify: FlapNotify;
|
|
26
|
-
}
|
|
27
|
-
declare function MiniAppRuntimeProvider({ manifest, session, i18n, notify, children }: {
|
|
28
|
-
manifest: VaultManifest;
|
|
29
|
-
session: MiniAppSession;
|
|
30
|
-
i18n: FlapI18n;
|
|
31
|
-
notify: FlapNotify;
|
|
32
|
-
children: ReactNode;
|
|
33
|
-
}): React.JSX.Element;
|
|
34
|
-
declare function useMiniAppSdk(): MiniAppSdk;
|
|
35
|
-
|
|
36
6
|
declare function isIpfsImageCid(value: string): boolean;
|
|
37
7
|
declare function normalizeIpfsImagePath(value: string | undefined): string | undefined;
|
|
38
8
|
declare function resolveIpfsImageUrl(cid: string, chainId?: number, path?: string): string | undefined;
|
|
@@ -175,19 +145,11 @@ declare function useVaultContext(): VaultRuntimeContext;
|
|
|
175
145
|
declare function useFlapI18n(): FlapI18n;
|
|
176
146
|
declare function useFlapNotify(): FlapNotify;
|
|
177
147
|
|
|
178
|
-
interface RuntimeProviderProps {
|
|
179
|
-
children: ReactNode;
|
|
180
|
-
manifest: VaultManifest;
|
|
181
|
-
i18n: Record<string, Record<string, string>>;
|
|
182
|
-
runtimeContext?: VaultRuntimeContextOverrides;
|
|
183
|
-
hostRuntimeResult?: HostRuntimeResult | null;
|
|
184
|
-
locale?: string;
|
|
185
|
-
oracleReader?: OracleReader;
|
|
186
|
-
nftMetadataReader?: NftMetadataReader;
|
|
187
|
-
mediaUploader?: MediaUploader;
|
|
188
|
-
}
|
|
189
|
-
declare function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtimeOverrides, hostRuntimeResult, locale, oracleReader, nftMetadataReader, mediaUploader }: RuntimeProviderProps): React.JSX.Element;
|
|
190
|
-
|
|
191
148
|
declare function useFlapWallet(): FlapWallet;
|
|
192
149
|
|
|
193
|
-
|
|
150
|
+
/** Host feature check; declarations must fail closed on older runtimes. */
|
|
151
|
+
declare const NFT_ACCOUNT_WITHDRAWAL_VERSION = 1;
|
|
152
|
+
|
|
153
|
+
declare const RESOLVED_CONTRACTS_VERSION = 1;
|
|
154
|
+
|
|
155
|
+
export { Address, type ConsumerVideoClip, type ConsumerVideoSessionReader, FlapI18n, FlapNotify, FlapVaultSdk, FlapWallet, IMAGE_UPLOAD_MEDIA_TYPES, IpfsUploadResult, type LocalNftMetadataReaderOptions, MAX_IMAGE_UPLOAD_BYTES, MAX_TEXT_UPLOAD_BYTES, MediaUploadError, MediaUploadRequest, MediaUploader, type MiniApp3DDecoderUrls, NFT_ACCOUNT_WITHDRAWAL_VERSION, NftMetadataAttribute, NftMetadataReader, RESOLVED_CONTRACTS_VERSION, RUNTIME_UPLOAD_ENDPOINT, VAULT_LAUNCH_SCHEMA_ABI, VaultLaunchConfigResult, VaultLaunchSchema, VaultRuntimeContext, VideoSessionReadError, createConsumerVideoSessionReader, createIpfsUploadResult, createLocalMediaUploader, createLocalNftMetadataReader, isIpfsImageCid, isVaultLaunchConfigResultForSchema, nftTokenUriAbi, normalizeInlineNftImage, normalizeIpfsImagePath, parseInlineNftMetadata, parseVaultLaunchSchema, readVideoSessionLength, readVideoSessionSlice, resolveIpfsImageUrl, resolveIpfsImageUrls, resolveMiniApp3DAssetUrl, resolveMiniApp3DDecoderUrls, sanitizeNftMetadataRecord, useVaultContext as useFlapChain, useFlapI18n, useFlapNotify, useFlapSdk, useFlapWallet, useVaultContext, validateMediaUpload, vaultV2NftAbi };
|
package/sdk.js
CHANGED
|
@@ -1,31 +1,15 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import
|
|
2
|
+
export { erc20Abi, getTxErrorKind, handleTxError, standardErc20Abi } from './chunk-22KTLOYH.js';
|
|
3
|
+
import './chunk-JVZ4TFPY.js';
|
|
4
|
+
import './chunk-AGLB72HK.js';
|
|
5
5
|
export { IMAGE_UPLOAD_MEDIA_TYPES, MAX_IMAGE_UPLOAD_BYTES, MAX_TEXT_UPLOAD_BYTES, MediaUploadError, RUNTIME_UPLOAD_ENDPOINT, createIpfsUploadResult, createLocalMediaUploader, createLocalNftMetadataReader, nftTokenUriAbi, normalizeInlineNftImage, parseInlineNftMetadata, sanitizeNftMetadataRecord, validateMediaUpload, vaultV2NftAbi } from './chunk-PU7VEZWA.js';
|
|
6
|
-
import { fetchOracleJson } from './chunk-JLI25XFB.js';
|
|
7
6
|
export { OracleReadError, buildLocalOracleUrl, createLocalOracleReader, fetchOracleJson, fetchProvisionedOracle } from './chunk-JLI25XFB.js';
|
|
8
|
-
import {
|
|
9
|
-
export { VideoSessionReadError, createConsumerVideoSessionReader, readVideoSessionLength, readVideoSessionSlice, useVaultContext as useFlapChain, useFlapI18n, useFlapNotify, useFlapSdk, useVaultContext } from './chunk-
|
|
10
|
-
import { isValidAddress, ZERO_ADDRESS } from './chunk-B4WKI3EW.js';
|
|
7
|
+
import { useFlapSdk } from './chunk-CXCG5MGE.js';
|
|
8
|
+
export { VideoSessionReadError, createConsumerVideoSessionReader, readVideoSessionLength, readVideoSessionSlice, useVaultContext as useFlapChain, useFlapI18n, useFlapNotify, useFlapSdk, useVaultContext } from './chunk-CXCG5MGE.js';
|
|
11
9
|
export { ZERO_ADDRESS, formatCountdown, formatPercentBps, formatTokenAmount, isActionAvailableForPhase, isCustomVaultTaxToken, isValidAddress, parseTokenAmount, readTaxVaultHostContext, resolveTokenMarketPhase, shortenAddress } from './chunk-B4WKI3EW.js';
|
|
12
10
|
export { isIpfsImageCid, normalizeIpfsImagePath, resolveIpfsImageUrl, resolveIpfsImageUrls } from './chunk-SAG36LUR.js';
|
|
13
11
|
import './chunk-FUOBTZMQ.js';
|
|
14
12
|
import './chunk-BUSYA2B4.js';
|
|
15
|
-
import { createContext, useContext, useState, useRef, useCallback, useEffect, useMemo } from 'react';
|
|
16
|
-
import { useAccount, useChainId, useConnect, useDisconnect, useSwitchChain, usePublicClient, useWalletClient, useBalance } from 'wagmi';
|
|
17
|
-
import { formatUnits, encodeFunctionData, decodeFunctionResult } from 'viem';
|
|
18
|
-
|
|
19
|
-
var MiniAppContext = createContext(null);
|
|
20
|
-
function MiniAppRuntimeProvider({ manifest, session, i18n, notify, children }) {
|
|
21
|
-
if (!isStandaloneMiniApp(manifest)) throw new Error("A standalone Mini App v2 manifest is required.");
|
|
22
|
-
return /* @__PURE__ */ React.createElement(MiniAppContext.Provider, { value: { context: { appId: manifest.artifactId, slug: manifest.slug, manifest }, session, i18n, notify } }, children);
|
|
23
|
-
}
|
|
24
|
-
function useMiniAppSdk() {
|
|
25
|
-
const sdk = useContext(MiniAppContext);
|
|
26
|
-
if (!sdk) throw new Error("useMiniAppSdk requires MiniAppRuntimeProvider.");
|
|
27
|
-
return sdk;
|
|
28
|
-
}
|
|
29
13
|
|
|
30
14
|
// src/sdk/launchConfig.ts
|
|
31
15
|
var VAULT_LAUNCH_SCHEMA_ABI = [{
|
|
@@ -97,478 +81,15 @@ function resolveMiniApp3DDecoderUrls(urls, moduleUrl) {
|
|
|
97
81
|
};
|
|
98
82
|
}
|
|
99
83
|
|
|
100
|
-
// src/sdk/contractWriteFees.ts
|
|
101
|
-
var MAX_CONTRACT_WRITE_GAS = 5000000n;
|
|
102
|
-
var MAX_GAS_PRICE_MULTIPLIER = 2n;
|
|
103
|
-
async function resolveSafeContractWriteFeeOverrides(request, getNetworkGasPrice) {
|
|
104
|
-
if (request.gas !== void 0) {
|
|
105
|
-
if (request.gas <= 0n) throw new Error("Contract write gas must be greater than zero.");
|
|
106
|
-
if (request.gas > MAX_CONTRACT_WRITE_GAS) {
|
|
107
|
-
throw new Error(`Contract write gas must not exceed ${MAX_CONTRACT_WRITE_GAS.toString()}.`);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
if (request.gasPrice !== void 0) {
|
|
111
|
-
if (request.gasPrice <= 0n) throw new Error("Contract write gasPrice must be greater than zero.");
|
|
112
|
-
const networkGasPrice = await getNetworkGasPrice();
|
|
113
|
-
if (networkGasPrice <= 0n) throw new Error("The runtime returned an invalid network gas price.");
|
|
114
|
-
const maximumGasPrice = networkGasPrice * MAX_GAS_PRICE_MULTIPLIER;
|
|
115
|
-
if (request.gasPrice > maximumGasPrice) {
|
|
116
|
-
throw new Error(
|
|
117
|
-
`Contract write gasPrice ${request.gasPrice.toString()} exceeds the runtime safety limit ${maximumGasPrice.toString()}.`
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
return {
|
|
122
|
-
...request.gas === void 0 ? {} : { gas: request.gas },
|
|
123
|
-
...request.gasPrice === void 0 ? {} : { gasPrice: request.gasPrice }
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// src/sdk/contractEvents.ts
|
|
128
|
-
var MAX_CONTRACT_EVENT_BLOCK_SPAN = 1000n;
|
|
129
|
-
var MAX_CONTRACT_EVENT_BLOCK_LOOKBACK = 20000n;
|
|
130
|
-
var CONTRACT_EVENT_QUERY_CONCURRENCY = 4;
|
|
131
|
-
function splitContractEventBlockRanges(fromBlock, toBlock, maxBlockSpan = MAX_CONTRACT_EVENT_BLOCK_SPAN, maxLookback = MAX_CONTRACT_EVENT_BLOCK_LOOKBACK) {
|
|
132
|
-
if (fromBlock < 0n || toBlock < 0n) {
|
|
133
|
-
throw new RangeError("Contract event block numbers must not be negative.");
|
|
134
|
-
}
|
|
135
|
-
if (maxBlockSpan <= 0n) {
|
|
136
|
-
throw new RangeError("Contract event block span must be greater than zero.");
|
|
137
|
-
}
|
|
138
|
-
if (maxLookback < 0n) {
|
|
139
|
-
throw new RangeError("Contract event block lookback must not be negative.");
|
|
140
|
-
}
|
|
141
|
-
if (toBlock < fromBlock) return [];
|
|
142
|
-
if (toBlock - fromBlock > maxLookback) {
|
|
143
|
-
throw new RangeError(`Contract event block range must not exceed ${maxLookback.toString()} blocks.`);
|
|
144
|
-
}
|
|
145
|
-
const ranges = [];
|
|
146
|
-
let cursor = fromBlock;
|
|
147
|
-
while (cursor <= toBlock) {
|
|
148
|
-
const candidateEnd = cursor + maxBlockSpan;
|
|
149
|
-
const chunkEnd = candidateEnd < toBlock ? candidateEnd : toBlock;
|
|
150
|
-
ranges.push({ fromBlock: cursor, toBlock: chunkEnd });
|
|
151
|
-
cursor = chunkEnd + 1n;
|
|
152
|
-
}
|
|
153
|
-
return ranges;
|
|
154
|
-
}
|
|
155
|
-
async function readContractEventsInBlockRanges(input) {
|
|
156
|
-
const concurrency = input.concurrency ?? CONTRACT_EVENT_QUERY_CONCURRENCY;
|
|
157
|
-
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > CONTRACT_EVENT_QUERY_CONCURRENCY) {
|
|
158
|
-
throw new RangeError(`Contract event query concurrency must be between 1 and ${CONTRACT_EVENT_QUERY_CONCURRENCY}.`);
|
|
159
|
-
}
|
|
160
|
-
const ranges = splitContractEventBlockRanges(input.fromBlock, input.toBlock);
|
|
161
|
-
const events = [];
|
|
162
|
-
for (let index = 0; index < ranges.length; index += concurrency) {
|
|
163
|
-
const batch = ranges.slice(index, index + concurrency);
|
|
164
|
-
const batchEvents = await Promise.all(batch.map((range) => input.readRange(range)));
|
|
165
|
-
for (const items of batchEvents) events.push(...items);
|
|
166
|
-
}
|
|
167
|
-
return events;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// src/sdk/runtime.tsx
|
|
171
|
-
var defaultNftMetadataReader = createLocalNftMetadataReader();
|
|
172
|
-
var defaultMediaUploader = createLocalMediaUploader();
|
|
173
|
-
var NFT_METADATA_MAX_CONCURRENCY = 6;
|
|
174
|
-
var activeNftMetadataReads = 0;
|
|
175
|
-
var pendingNftMetadataReads = [];
|
|
176
|
-
async function limitNftMetadataRead(task) {
|
|
177
|
-
if (activeNftMetadataReads >= NFT_METADATA_MAX_CONCURRENCY) {
|
|
178
|
-
await new Promise((resolve) => pendingNftMetadataReads.push(resolve));
|
|
179
|
-
}
|
|
180
|
-
activeNftMetadataReads += 1;
|
|
181
|
-
try {
|
|
182
|
-
return await task();
|
|
183
|
-
} finally {
|
|
184
|
-
activeNftMetadataReads -= 1;
|
|
185
|
-
pendingNftMetadataReads.shift()?.();
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
function applyParams(value, params) {
|
|
189
|
-
if (!params) return value;
|
|
190
|
-
return Object.entries(params).reduce((acc, [key, item]) => acc.replaceAll(`{${key}}`, String(item)), value);
|
|
191
|
-
}
|
|
192
|
-
function getPreviewOracleEndpoint(extraConfig, oracleId) {
|
|
193
|
-
const oracleEndpoints = extraConfig?.oracleEndpoints;
|
|
194
|
-
if (!oracleEndpoints || typeof oracleEndpoints !== "object" || Array.isArray(oracleEndpoints)) return void 0;
|
|
195
|
-
const endpoint = oracleEndpoints[oracleId];
|
|
196
|
-
return typeof endpoint === "string" ? endpoint : void 0;
|
|
197
|
-
}
|
|
198
|
-
function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtimeOverrides, hostRuntimeResult, locale = "en", oracleReader, nftMetadataReader, mediaUploader }) {
|
|
199
|
-
const [version, setVersion] = useState(0);
|
|
200
|
-
const [messages, setMessages] = useState([]);
|
|
201
|
-
const toastTimersRef = useRef(/* @__PURE__ */ new Map());
|
|
202
|
-
const nftMetadataCacheRef = useRef(/* @__PURE__ */ new Map());
|
|
203
|
-
const vaultNftAddressCacheRef = useRef(/* @__PURE__ */ new Map());
|
|
204
|
-
const { address: accountAddress, isConnected } = useAccount();
|
|
205
|
-
const connectedChainId = useChainId();
|
|
206
|
-
const { connect, connectors } = useConnect();
|
|
207
|
-
const { disconnect } = useDisconnect();
|
|
208
|
-
const { switchChainAsync, isPending: isSwitchingChain } = useSwitchChain();
|
|
209
|
-
const effectiveChainId = runtimeOverrides?.chainId ?? hostRuntimeResult?.addresses.chainId ?? connectedChainId ?? manifest.match.bindings[0]?.chainId ?? 56;
|
|
210
|
-
const publicClient = usePublicClient({ chainId: effectiveChainId });
|
|
211
|
-
const { data: walletClient } = useWalletClient();
|
|
212
|
-
const { data: nativeBalance } = useBalance({ address: accountAddress, chainId: isConnected ? connectedChainId : void 0 });
|
|
213
|
-
const dismissMessage = useCallback((id) => {
|
|
214
|
-
const timerId = toastTimersRef.current.get(id);
|
|
215
|
-
if (timerId) {
|
|
216
|
-
window.clearTimeout(timerId);
|
|
217
|
-
toastTimersRef.current.delete(id);
|
|
218
|
-
}
|
|
219
|
-
setMessages((items) => items.filter((item) => item.id !== id));
|
|
220
|
-
}, []);
|
|
221
|
-
useEffect(() => {
|
|
222
|
-
const timers = toastTimersRef.current;
|
|
223
|
-
return () => {
|
|
224
|
-
for (const timerId of timers.values()) {
|
|
225
|
-
window.clearTimeout(timerId);
|
|
226
|
-
}
|
|
227
|
-
timers.clear();
|
|
228
|
-
};
|
|
229
|
-
}, []);
|
|
230
|
-
const runtimeContext = useMemo(() => {
|
|
231
|
-
return createVaultRuntimeContext({
|
|
232
|
-
manifest,
|
|
233
|
-
connectedChainId,
|
|
234
|
-
hostRuntimeResult,
|
|
235
|
-
runtimeOverrides: {
|
|
236
|
-
...runtimeOverrides,
|
|
237
|
-
userAddress: runtimeOverrides?.userAddress ?? accountAddress
|
|
238
|
-
}
|
|
239
|
-
});
|
|
240
|
-
}, [accountAddress, connectedChainId, hostRuntimeResult, manifest, runtimeOverrides]);
|
|
241
|
-
const i18nApi = useMemo(
|
|
242
|
-
() => ({
|
|
243
|
-
locale,
|
|
244
|
-
t(key, fallback, params) {
|
|
245
|
-
const defaultLocale = manifest.i18n[0];
|
|
246
|
-
const resolved = i18n[locale]?.[key] ?? i18n[defaultLocale]?.[key] ?? i18n.en?.[key] ?? fallback ?? key;
|
|
247
|
-
return applyParams(resolved, params);
|
|
248
|
-
}
|
|
249
|
-
}),
|
|
250
|
-
[i18n, locale, manifest.i18n]
|
|
251
|
-
);
|
|
252
|
-
const push = useCallback(
|
|
253
|
-
(level, message) => {
|
|
254
|
-
const id = Date.now() + Math.floor(Math.random() * 1e3);
|
|
255
|
-
setMessages((items) => [{ id, level, message }, ...items].slice(0, 4));
|
|
256
|
-
const timerId = window.setTimeout(() => {
|
|
257
|
-
dismissMessage(id);
|
|
258
|
-
}, 4200);
|
|
259
|
-
toastTimersRef.current.set(id, timerId);
|
|
260
|
-
},
|
|
261
|
-
[dismissMessage]
|
|
262
|
-
);
|
|
263
|
-
const notify = useMemo(
|
|
264
|
-
() => ({
|
|
265
|
-
info: (message) => push("info", message),
|
|
266
|
-
success: (message) => push("success", message),
|
|
267
|
-
warning: (message) => push("warning", message),
|
|
268
|
-
error: (message) => push("error", message)
|
|
269
|
-
}),
|
|
270
|
-
[push]
|
|
271
|
-
);
|
|
272
|
-
const wallet = useMemo(
|
|
273
|
-
() => {
|
|
274
|
-
const previewWallet = runtimeOverrides?.previewWallet;
|
|
275
|
-
const walletAddress = previewWallet?.address ?? accountAddress;
|
|
276
|
-
const walletConnected = previewWallet?.isConnected ?? isConnected;
|
|
277
|
-
const walletChainId = previewWallet?.chainId ?? connectedChainId;
|
|
278
|
-
return {
|
|
279
|
-
address: walletAddress,
|
|
280
|
-
chainId: walletConnected ? walletChainId : void 0,
|
|
281
|
-
chainLabel: walletConnected && walletChainId ? chainLabelForChain(walletChainId) : void 0,
|
|
282
|
-
requiredChainId: runtimeContext.chainId,
|
|
283
|
-
requiredChainLabel: chainLabelForChain(runtimeContext.chainId),
|
|
284
|
-
isConnected: walletConnected,
|
|
285
|
-
isWrongNetwork: Boolean(walletConnected && walletChainId && walletChainId !== runtimeContext.chainId),
|
|
286
|
-
canSwitchChain: previewWallet?.canSwitchChain ?? Boolean(switchChainAsync),
|
|
287
|
-
isSwitchingChain,
|
|
288
|
-
// Real native-token balance from the connected wallet. "0" until a wallet is connected.
|
|
289
|
-
balance: previewWallet ? "0" : nativeBalance ? formatUnits(nativeBalance.value, nativeBalance.decimals) : "0",
|
|
290
|
-
// Wallet connection is host/shell-owned. In this preview the SDK forwards to the
|
|
291
|
-
// injected wagmi connector so the surface is functional rather than a no-op stub.
|
|
292
|
-
connect: () => {
|
|
293
|
-
const connector = connectors[0];
|
|
294
|
-
if (connector) connect({ connector });
|
|
295
|
-
},
|
|
296
|
-
disconnect: () => disconnect(),
|
|
297
|
-
switchChain: async () => {
|
|
298
|
-
if (previewWallet) {
|
|
299
|
-
throw new Error(`Switch wallet to ${chainLabelForChain(runtimeContext.chainId)} before continuing.`);
|
|
300
|
-
}
|
|
301
|
-
if (!switchChainAsync) {
|
|
302
|
-
throw new Error(`Switch wallet to ${chainLabelForChain(runtimeContext.chainId)} before continuing.`);
|
|
303
|
-
}
|
|
304
|
-
await switchChainAsync({ chainId: runtimeContext.chainId });
|
|
305
|
-
}
|
|
306
|
-
};
|
|
307
|
-
},
|
|
308
|
-
[accountAddress, connect, connectedChainId, connectors, disconnect, isConnected, isSwitchingChain, nativeBalance, runtimeContext.chainId, runtimeOverrides?.previewWallet, switchChainAsync]
|
|
309
|
-
);
|
|
310
|
-
const assertWalletWriteReady = useCallback(
|
|
311
|
-
(actionLabel) => {
|
|
312
|
-
if (!accountAddress) throw new Error("Wallet is not connected.");
|
|
313
|
-
if (isConnected && connectedChainId !== runtimeContext.chainId) {
|
|
314
|
-
throw new Error(`Wrong network. Switch wallet to ${chainLabelForChain(runtimeContext.chainId)} before ${actionLabel}.`);
|
|
315
|
-
}
|
|
316
|
-
},
|
|
317
|
-
[accountAddress, connectedChainId, isConnected, runtimeContext.chainId]
|
|
318
|
-
);
|
|
319
|
-
const readContract = useCallback(
|
|
320
|
-
async (request) => {
|
|
321
|
-
if (!publicClient || !request.abi || !request.address) {
|
|
322
|
-
throw new Error(`Contract read ${request.functionName} requires a public client, ABI, and address.`);
|
|
323
|
-
}
|
|
324
|
-
if (request.gasPrice !== void 0) {
|
|
325
|
-
if (request.gasPrice <= 0n) throw new Error("Contract read gasPrice must be greater than zero.");
|
|
326
|
-
const data = encodeFunctionData({
|
|
327
|
-
abi: request.abi,
|
|
328
|
-
functionName: request.functionName,
|
|
329
|
-
args: request.args
|
|
330
|
-
});
|
|
331
|
-
const response = await publicClient.call({
|
|
332
|
-
account: request.account,
|
|
333
|
-
to: request.address,
|
|
334
|
-
data,
|
|
335
|
-
gasPrice: request.gasPrice
|
|
336
|
-
});
|
|
337
|
-
if (!response.data) throw new Error(`Contract read ${request.functionName} returned no data.`);
|
|
338
|
-
return decodeFunctionResult({
|
|
339
|
-
abi: request.abi,
|
|
340
|
-
functionName: request.functionName,
|
|
341
|
-
args: request.args,
|
|
342
|
-
data: response.data
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
return await publicClient.readContract({
|
|
346
|
-
address: request.address,
|
|
347
|
-
abi: request.abi,
|
|
348
|
-
functionName: request.functionName,
|
|
349
|
-
args: request.args,
|
|
350
|
-
account: request.account
|
|
351
|
-
});
|
|
352
|
-
},
|
|
353
|
-
[publicClient]
|
|
354
|
-
);
|
|
355
|
-
const getGasPrice = useCallback(async () => {
|
|
356
|
-
if (!publicClient) throw new Error("Gas-price lookup requires a public client.");
|
|
357
|
-
const gasPrice = await publicClient.getGasPrice();
|
|
358
|
-
if (gasPrice <= 0n) throw new Error("The runtime returned an invalid network gas price.");
|
|
359
|
-
return gasPrice;
|
|
360
|
-
}, [publicClient]);
|
|
361
|
-
const getBlockNumber = useCallback(async () => {
|
|
362
|
-
if (!publicClient) throw new Error("Block-number lookup requires a public client.");
|
|
363
|
-
const blockNumber = await publicClient.getBlockNumber();
|
|
364
|
-
if (blockNumber < 0n) throw new Error("The runtime returned an invalid block number.");
|
|
365
|
-
return blockNumber;
|
|
366
|
-
}, [publicClient]);
|
|
367
|
-
const getContractEvents = useCallback(
|
|
368
|
-
async (request) => {
|
|
369
|
-
if (!publicClient || !request.abi || !request.address || !request.eventName.trim()) {
|
|
370
|
-
throw new Error("Contract event lookup requires a public client, ABI, address, and event name.");
|
|
371
|
-
}
|
|
372
|
-
const toBlock = typeof request.toBlock === "bigint" ? request.toBlock : await getBlockNumber();
|
|
373
|
-
return readContractEventsInBlockRanges({
|
|
374
|
-
fromBlock: request.fromBlock,
|
|
375
|
-
toBlock,
|
|
376
|
-
readRange: async ({ fromBlock, toBlock: chunkToBlock }) => {
|
|
377
|
-
const events = await publicClient.getContractEvents({
|
|
378
|
-
address: request.address,
|
|
379
|
-
abi: request.abi,
|
|
380
|
-
eventName: request.eventName,
|
|
381
|
-
args: request.args,
|
|
382
|
-
fromBlock,
|
|
383
|
-
toBlock: chunkToBlock,
|
|
384
|
-
strict: request.strict
|
|
385
|
-
});
|
|
386
|
-
return events;
|
|
387
|
-
}
|
|
388
|
-
});
|
|
389
|
-
},
|
|
390
|
-
[getBlockNumber, publicClient]
|
|
391
|
-
);
|
|
392
|
-
const simulateContract = useCallback(
|
|
393
|
-
async (request) => {
|
|
394
|
-
assertWalletWriteReady(`simulating ${request.functionName}`);
|
|
395
|
-
if (!publicClient || !request.abi || !request.address) {
|
|
396
|
-
throw new Error(`Contract simulation ${request.functionName} requires a public client, ABI, and address.`);
|
|
397
|
-
}
|
|
398
|
-
const feeOverrides = await resolveSafeContractWriteFeeOverrides(request, getGasPrice);
|
|
399
|
-
const simulation = await publicClient.simulateContract({
|
|
400
|
-
account: accountAddress,
|
|
401
|
-
address: request.address,
|
|
402
|
-
abi: request.abi,
|
|
403
|
-
functionName: request.functionName,
|
|
404
|
-
args: request.args,
|
|
405
|
-
value: request.value,
|
|
406
|
-
...feeOverrides
|
|
407
|
-
});
|
|
408
|
-
return { request, result: simulation.result };
|
|
409
|
-
},
|
|
410
|
-
[accountAddress, assertWalletWriteReady, getGasPrice, publicClient]
|
|
411
|
-
);
|
|
412
|
-
const writeContract = useCallback(
|
|
413
|
-
async (request) => {
|
|
414
|
-
assertWalletWriteReady(`writing ${request.functionName}`);
|
|
415
|
-
if (!walletClient || !request.abi || !request.address) {
|
|
416
|
-
throw new Error(`Contract write ${request.functionName} requires a wallet client, ABI, and address.`);
|
|
417
|
-
}
|
|
418
|
-
const feeOverrides = await resolveSafeContractWriteFeeOverrides(request, getGasPrice);
|
|
419
|
-
const hash = await walletClient.writeContract({
|
|
420
|
-
address: request.address,
|
|
421
|
-
abi: request.abi,
|
|
422
|
-
functionName: request.functionName,
|
|
423
|
-
args: request.args,
|
|
424
|
-
value: request.value,
|
|
425
|
-
...feeOverrides
|
|
426
|
-
});
|
|
427
|
-
return hash;
|
|
428
|
-
},
|
|
429
|
-
[assertWalletWriteReady, getGasPrice, walletClient]
|
|
430
|
-
);
|
|
431
|
-
const waitForTx = useCallback(
|
|
432
|
-
async (hash) => {
|
|
433
|
-
if (!publicClient) throw new Error("Transaction receipt requires a public client.");
|
|
434
|
-
const receipt = await publicClient.waitForTransactionReceipt({ hash });
|
|
435
|
-
return { hash, status: receipt.status === "success" ? "success" : "reverted" };
|
|
436
|
-
},
|
|
437
|
-
[publicClient]
|
|
438
|
-
);
|
|
439
|
-
const readOracle = useCallback(
|
|
440
|
-
async (oracleId, params) => {
|
|
441
|
-
if (oracleReader) {
|
|
442
|
-
return oracleReader({
|
|
443
|
-
oracleId,
|
|
444
|
-
params,
|
|
445
|
-
context: runtimeContext
|
|
446
|
-
});
|
|
447
|
-
}
|
|
448
|
-
const endpoint = getPreviewOracleEndpoint(runtimeContext.extraConfig, oracleId);
|
|
449
|
-
if (!endpoint) throw new Error(`Oracle ${oracleId} is not provisioned by the runtime.`);
|
|
450
|
-
return fetchOracleJson({
|
|
451
|
-
endpoint,
|
|
452
|
-
params
|
|
453
|
-
});
|
|
454
|
-
},
|
|
455
|
-
[oracleReader, runtimeContext]
|
|
456
|
-
);
|
|
457
|
-
const readNftMetadata = useCallback(
|
|
458
|
-
async (request) => {
|
|
459
|
-
if (request.tokenId < 0n) throw new Error("NFT tokenId must not be negative.");
|
|
460
|
-
const vaultAddress = runtimeContext.vaultAddress;
|
|
461
|
-
if (!isValidAddress(vaultAddress) || vaultAddress.toLowerCase() === ZERO_ADDRESS) {
|
|
462
|
-
throw new Error("Vault V2 NFT metadata requires a valid runtime Vault address.");
|
|
463
|
-
}
|
|
464
|
-
const cacheKey = `${runtimeContext.chainId}:${vaultAddress.toLowerCase()}:${request.tokenId.toString()}:${version}`;
|
|
465
|
-
const cached = nftMetadataCacheRef.current.get(cacheKey);
|
|
466
|
-
if (cached) return cached;
|
|
467
|
-
const pending = limitNftMetadataRead(async () => {
|
|
468
|
-
const nftAddressCacheKey = `${runtimeContext.chainId}:${vaultAddress.toLowerCase()}:${version}`;
|
|
469
|
-
let nftAddressPending = vaultNftAddressCacheRef.current.get(nftAddressCacheKey);
|
|
470
|
-
if (!nftAddressPending) {
|
|
471
|
-
nftAddressPending = readContract({
|
|
472
|
-
contract: "vault",
|
|
473
|
-
address: vaultAddress,
|
|
474
|
-
abi: vaultV2NftAbi,
|
|
475
|
-
functionName: "nft"
|
|
476
|
-
}).then((nftAddress2) => {
|
|
477
|
-
if (!isValidAddress(nftAddress2) || nftAddress2.toLowerCase() === ZERO_ADDRESS) {
|
|
478
|
-
throw new Error("Vault V2 nft() returned an invalid NFT address.");
|
|
479
|
-
}
|
|
480
|
-
return nftAddress2;
|
|
481
|
-
});
|
|
482
|
-
vaultNftAddressCacheRef.current.set(nftAddressCacheKey, nftAddressPending);
|
|
483
|
-
if (vaultNftAddressCacheRef.current.size > 32) {
|
|
484
|
-
const oldestNftAddressKey = vaultNftAddressCacheRef.current.keys().next().value;
|
|
485
|
-
if (oldestNftAddressKey) vaultNftAddressCacheRef.current.delete(oldestNftAddressKey);
|
|
486
|
-
}
|
|
487
|
-
nftAddressPending.catch(() => vaultNftAddressCacheRef.current.delete(nftAddressCacheKey));
|
|
488
|
-
}
|
|
489
|
-
const nftAddress = await nftAddressPending;
|
|
490
|
-
const tokenUri = await readContract({
|
|
491
|
-
contract: "nft",
|
|
492
|
-
address: nftAddress,
|
|
493
|
-
abi: nftTokenUriAbi,
|
|
494
|
-
functionName: "tokenURI",
|
|
495
|
-
args: [request.tokenId]
|
|
496
|
-
});
|
|
497
|
-
if (typeof tokenUri !== "string" || !tokenUri.trim()) throw new Error("NFT tokenURI returned an empty value.");
|
|
498
|
-
return (nftMetadataReader ?? defaultNftMetadataReader)({
|
|
499
|
-
...request,
|
|
500
|
-
chainId: runtimeContext.chainId,
|
|
501
|
-
nftAddress,
|
|
502
|
-
tokenUri: tokenUri.trim(),
|
|
503
|
-
context: runtimeContext
|
|
504
|
-
});
|
|
505
|
-
});
|
|
506
|
-
nftMetadataCacheRef.current.set(cacheKey, pending);
|
|
507
|
-
if (nftMetadataCacheRef.current.size > 128) {
|
|
508
|
-
const oldestKey = nftMetadataCacheRef.current.keys().next().value;
|
|
509
|
-
if (oldestKey) nftMetadataCacheRef.current.delete(oldestKey);
|
|
510
|
-
}
|
|
511
|
-
pending.catch(() => nftMetadataCacheRef.current.delete(cacheKey));
|
|
512
|
-
return pending;
|
|
513
|
-
},
|
|
514
|
-
[nftMetadataReader, readContract, runtimeContext, version]
|
|
515
|
-
);
|
|
516
|
-
const uploadImage = useCallback(
|
|
517
|
-
(file, options) => (mediaUploader ?? defaultMediaUploader)({ kind: "image", file, chainId: effectiveChainId, signal: options?.signal }),
|
|
518
|
-
[effectiveChainId, mediaUploader]
|
|
519
|
-
);
|
|
520
|
-
const uploadText = useCallback(
|
|
521
|
-
(text, options) => (mediaUploader ?? defaultMediaUploader)({ kind: "text", file: new Blob([text], { type: "text/plain;charset=utf-8" }), chainId: effectiveChainId, signal: options?.signal }),
|
|
522
|
-
[effectiveChainId, mediaUploader]
|
|
523
|
-
);
|
|
524
|
-
const refetch = useCallback(async () => {
|
|
525
|
-
setVersion((item) => item + 1);
|
|
526
|
-
}, []);
|
|
527
|
-
const openExplorerTx = useCallback(
|
|
528
|
-
(hash) => {
|
|
529
|
-
if (!runtimeContext.explorerBaseUrl) return;
|
|
530
|
-
window.open(`${runtimeContext.explorerBaseUrl.replace(/\/$/, "")}/tx/${hash}`, "_blank", "noreferrer");
|
|
531
|
-
},
|
|
532
|
-
[runtimeContext.explorerBaseUrl]
|
|
533
|
-
);
|
|
534
|
-
const sdk = useMemo(
|
|
535
|
-
() => ({
|
|
536
|
-
context: runtimeContext,
|
|
537
|
-
i18n: i18nApi,
|
|
538
|
-
notify,
|
|
539
|
-
wallet,
|
|
540
|
-
getGasPrice,
|
|
541
|
-
getBlockNumber,
|
|
542
|
-
getContractEvents,
|
|
543
|
-
readContract,
|
|
544
|
-
simulateContract,
|
|
545
|
-
writeContract,
|
|
546
|
-
waitForTx,
|
|
547
|
-
readOracle,
|
|
548
|
-
readNftMetadata,
|
|
549
|
-
uploadImage,
|
|
550
|
-
uploadText,
|
|
551
|
-
refetch,
|
|
552
|
-
refetchNonce: version,
|
|
553
|
-
openExplorerTx
|
|
554
|
-
}),
|
|
555
|
-
[getBlockNumber, getContractEvents, getGasPrice, i18nApi, notify, openExplorerTx, readContract, readNftMetadata, readOracle, refetch, runtimeContext, simulateContract, uploadImage, uploadText, version, waitForTx, wallet, writeContract]
|
|
556
|
-
);
|
|
557
|
-
return /* @__PURE__ */ React.createElement(RuntimeContext.Provider, { value: sdk }, children, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none fixed bottom-4 right-4 z-50 flex w-[min(360px,calc(100vw-2rem))] flex-col gap-2" }, messages.map((message) => /* @__PURE__ */ React.createElement("div", { key: message.id, className: "pointer-events-auto" }, /* @__PURE__ */ React.createElement(
|
|
558
|
-
Alert,
|
|
559
|
-
{
|
|
560
|
-
tone: message.level === "error" ? "danger" : message.level,
|
|
561
|
-
className: "cursor-pointer shadow-panel backdrop-blur-sm transition hover:translate-y-[-1px]"
|
|
562
|
-
},
|
|
563
|
-
/* @__PURE__ */ React.createElement("button", { type: "button", className: "w-full text-left", onClick: () => dismissMessage(message.id) }, message.message)
|
|
564
|
-
)))));
|
|
565
|
-
}
|
|
566
|
-
|
|
567
84
|
// src/sdk/useFlapWallet.ts
|
|
568
85
|
function useFlapWallet() {
|
|
569
86
|
return useFlapSdk().wallet;
|
|
570
87
|
}
|
|
571
88
|
|
|
572
|
-
|
|
89
|
+
// src/sdk/client.ts
|
|
90
|
+
var NFT_ACCOUNT_WITHDRAWAL_VERSION = 1;
|
|
91
|
+
var RESOLVED_CONTRACTS_VERSION = 1;
|
|
92
|
+
|
|
93
|
+
export { NFT_ACCOUNT_WITHDRAWAL_VERSION, RESOLVED_CONTRACTS_VERSION, VAULT_LAUNCH_SCHEMA_ABI, isVaultLaunchConfigResultForSchema, parseVaultLaunchSchema, resolveMiniApp3DAssetUrl, resolveMiniApp3DDecoderUrls, useFlapWallet };
|
|
573
94
|
//# sourceMappingURL=sdk.js.map
|
|
574
95
|
//# sourceMappingURL=sdk.js.map
|