@adland/react 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @adland/react
2
2
 
3
+ ## 0.13.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c051bc3: repo migration
8
+
9
+ ### Patch Changes
10
+
11
+ - 0d3484f: centralized packages
12
+ - Updated dependencies [c051bc3]
13
+ - Updated dependencies [0d3484f]
14
+ - @adland/data@0.14.0
15
+
16
+ ## 0.12.1
17
+
18
+ ### Patch Changes
19
+
20
+ - c56a65d: change of profile ad display name
21
+
3
22
  ## 0.12.0
4
23
 
5
24
  ### Minor Changes
@@ -115,7 +134,6 @@
115
134
  ### Minor Changes
116
135
 
117
136
  - c2df20a: Add `useFetch` hook with global in-memory cache and improve Ad component:
118
-
119
137
  - Add `useFetch` hook with React Query-like global cache that persists across component lifecycles
120
138
  - Add `fetchCache` utility for global cache management
121
139
  - Improve Ad component to use relative URLs for local development
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adland/react",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -33,7 +33,7 @@
33
33
  "@types/react-dom": "^18.3.1",
34
34
  "lucide-react": "0.561.0",
35
35
  "tsup": "^8.0.1",
36
- "@adland/data": "0.13.0"
36
+ "@adland/data": "0.14.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@typescript-eslint/eslint-plugin": "^7.13.1",
@@ -12,40 +12,44 @@ import TokenAdContent from "./content/TokenAdContent";
12
12
  import FarcasterProfileAdContent from "./content/FarcasterProfileAdContent";
13
13
  import { AdDataQueryError, AdProps } from "../types";
14
14
  import { getBaseUrl } from "../utils";
15
- import { adlandApiUrl } from "../utils/constants";
16
- import { fetchAd } from "../fetch";
15
+ import { fetchAdFromURI, fetchMetadataURI } from "../fetch";
16
+
17
+ const DEFAULT_RPC = "https://sepolia.base.org";
18
+ const DEFAULT_METADATA_MODULE = "0x6c5A8A7f061bEd94b1b88CFAd4e1a1a8C5c4e527";
17
19
 
18
20
  /**
19
- * Simple Ad component with built-in view and click tracking
20
- * Uses Farcaster MiniApp SDK for authenticated tracking requests
21
+ * Ad component powered by 0xSlots v3 MetadataModule.
22
+ * Fetches ad content URI from on-chain, then fetches content from IPFS/HTTP.
21
23
  *
22
24
  * @example
23
25
  * ```tsx
24
- * <Ad owner="0x123..." adId="ad-1" network="testnet">
25
- * <img src="ad-image.jpg" alt="Advertisement" />
26
- * </Ad>
26
+ * <Ad slot="0xabc...123" />
27
27
  * ```
28
28
  */
29
29
  export function Ad({
30
- owner,
31
- slotId,
30
+ slot,
31
+ metadataModule = DEFAULT_METADATA_MODULE,
32
32
  network = "testnet",
33
33
  baseUrl,
34
+ rpcUrl = DEFAULT_RPC,
34
35
  ...props
35
36
  }: AdProps) {
36
37
  const ref = useRef<HTMLDivElement>(null);
38
+ const networkBaseUrl = baseUrl ?? getBaseUrl(network);
39
+
37
40
  const {
38
41
  data: adData,
39
42
  isLoading,
40
43
  error,
41
44
  } = useFetch<AdData>(
42
- `ad-data-${owner}-${slotId}`,
43
- () => fetchAd(owner, slotId),
44
- {
45
- enabled: !!owner && !!slotId,
45
+ `ad-data-${slot}`,
46
+ async () => {
47
+ const uri = await fetchMetadataURI(rpcUrl, metadataModule, slot);
48
+ if (!uri) throw new Error(AdDataQueryError.NO_AD);
49
+ return fetchAdFromURI(uri);
46
50
  },
51
+ { enabled: !!slot },
47
52
  );
48
- const networkBaseUrl = baseUrl ?? getBaseUrl(network);
49
53
 
50
54
  const send = useCallback(
51
55
  (type: "view" | "click") => {
@@ -53,20 +57,19 @@ export function Ad({
53
57
 
54
58
  sendTrackRequest(trackEndpoint, {
55
59
  type,
56
- adId: slotId,
57
- adOwner: owner,
60
+ slot,
58
61
  }).catch((error: unknown) => {
59
62
  console.error(`[@adland/react] Failed to track ${type}:`, error);
60
63
  });
61
64
  },
62
- [slotId, owner, networkBaseUrl],
65
+ [slot, networkBaseUrl],
63
66
  );
64
67
 
65
68
  useEffect(() => {
66
69
  const el = ref.current;
67
70
  if (!el) return;
68
71
 
69
- const key = `ad_view_${slotId}`;
72
+ const key = `ad_view_${slot}`;
70
73
 
71
74
  const obs = new IntersectionObserver(
72
75
  (entries) => {
@@ -83,20 +86,15 @@ export function Ad({
83
86
  send("view");
84
87
  obs.unobserve(el);
85
88
  },
86
- {
87
- threshold: 0.15, // more forgiving
88
- },
89
+ { threshold: 0.15 },
89
90
  );
90
91
 
91
92
  obs.observe(el);
92
93
  return () => obs.disconnect();
93
- }, [slotId, send]);
94
+ }, [slot, send]);
94
95
 
95
- // CLICK tracking
96
- // Only track clicks that aren't on links or buttons (let those handle their own navigation)
97
96
  const onClick = useCallback(
98
97
  (e: React.MouseEvent<HTMLDivElement>) => {
99
- // Don't track if clicking on a link, button, or other interactive element
100
98
  const target = e.target as HTMLElement;
101
99
  const isInteractiveElement =
102
100
  target.tagName === "A" ||
@@ -114,21 +112,11 @@ export function Ad({
114
112
  return (
115
113
  <div ref={ref} onClick={onClick} {...props}>
116
114
  {(() => {
117
- if (isLoading) {
118
- return <LoadingAdContent />;
119
- }
115
+ if (isLoading) return <LoadingAdContent />;
120
116
  if (error) {
121
- // @ts-ignore
122
117
  if (error instanceof Error) {
123
118
  if (error.message === AdDataQueryError.NO_AD) {
124
- return (
125
- <EmtpyAdContent
126
- data={{ url: networkBaseUrl + `${owner}/${slotId}` }}
127
- />
128
- );
129
- }
130
- if (error.message === AdDataQueryError.ERROR) {
131
- return <ErrorAdContent error={error} />;
119
+ return <EmtpyAdContent slot={slot} baseUrl={networkBaseUrl} />;
132
120
  }
133
121
  }
134
122
  return <ErrorAdContent error={error} />;
@@ -137,25 +125,16 @@ export function Ad({
137
125
  return (
138
126
  <>
139
127
  {adData.type === "link" && <LinkAdContent data={adData} />}
140
-
141
128
  {adData.type === "cast" && <CastAdContent data={adData} />}
142
-
143
129
  {adData.type === "miniapp" && <MiniappAdContent data={adData} />}
144
-
145
130
  {adData.type === "token" && <TokenAdContent data={adData} />}
146
-
147
131
  {adData.type === "farcasterProfile" && (
148
132
  <FarcasterProfileAdContent data={adData} />
149
133
  )}
150
134
  </>
151
135
  );
152
- } else {
153
- return (
154
- <EmtpyAdContent
155
- data={{ url: networkBaseUrl + `${owner}/${slotId}` }}
156
- />
157
- );
158
136
  }
137
+ return <EmtpyAdContent slot={slot} baseUrl={networkBaseUrl} />;
159
138
  })()}
160
139
  </div>
161
140
  );
@@ -183,12 +162,12 @@ function LoadingAdContent() {
183
162
  );
184
163
  }
185
164
 
186
- function EmtpyAdContent({ data }: { data: { url: string } }) {
165
+ function EmtpyAdContent({ slot, baseUrl }: { slot: string; baseUrl: string }) {
187
166
  return (
188
167
  <BasicAdBody
189
168
  onClick={() => {
190
169
  sdk.actions.openMiniApp({
191
- url: data.url,
170
+ url: `${baseUrl}/slots/${slot}`,
192
171
  });
193
172
  }}
194
173
  >
@@ -34,24 +34,18 @@ const FarcasterProfileAdContent = ({ data }: { data: FarcasterProfileAd }) => {
34
34
  </div>
35
35
  )}
36
36
  <div className="flex flex-row items-center gap-1">
37
- {profileMetadata?.displayName || profileMetadata?.username ? (
38
- <p className="text-sm font-bold text-primary truncate">
39
- {profileMetadata.displayName || `@${profileMetadata.username}`}
40
- </p>
41
- ) : (
42
- <p className="text-sm font-bold text-primary">FID: {fid}</p>
43
- )}
37
+ <p className="text-sm text-primary truncate">
38
+ <span className="font-bold">{profileMetadata?.displayName} </span>
39
+ <span className="text-xs font-light text-muted-foreground/80">
40
+ @{profileMetadata?.username}
41
+ </span>
42
+ </p>
44
43
  {profileMetadata?.pro && (
45
44
  <span className="text-xs bg-primary text-primary-foreground px-1 rounded">
46
45
  PRO
47
46
  </span>
48
47
  )}
49
48
  </div>
50
- {profileMetadata?.displayName && profileMetadata?.username && (
51
- <p className="text-xs text-muted-foreground/80 truncate">
52
- @{profileMetadata.username}
53
- </p>
54
- )}
55
49
  {profileMetadata?.bio ? (
56
50
  <p className="text-xs text-muted-foreground/80 line-clamp-1">
57
51
  {profileMetadata.bio}
package/src/fetch.ts CHANGED
@@ -1,28 +1,80 @@
1
1
  import { AdDataQueryError } from "./types";
2
- import { adlandApiUrl } from "./utils/constants";
3
2
 
4
- export const fetchAd = async (owner: string, slotId: string) => {
5
- const url = `${adlandApiUrl}/ad/owner/${owner.toLowerCase()}/slot/${slotId}`;
3
+ const IPFS_GATEWAY = "https://gateway.pinata.cloud/ipfs/";
4
+
5
+ /**
6
+ * Fetch ad content from a metadata URI (IPFS or HTTP)
7
+ */
8
+ export const fetchAdFromURI = async (uri: string) => {
9
+ if (!uri) throw new Error(AdDataQueryError.NO_AD);
10
+
11
+ const url = uri.startsWith("ipfs://")
12
+ ? `${IPFS_GATEWAY}${uri.slice(7)}`
13
+ : uri;
6
14
 
7
15
  const res = await fetch(url, {
8
16
  method: "GET",
9
- headers: {
10
- "Content-Type": "application/json",
11
- },
17
+ headers: { Accept: "application/json" },
12
18
  });
13
19
 
14
20
  if (!res.ok) {
15
- if (res.status === 404) {
16
- throw new Error(AdDataQueryError.NO_AD);
17
- }
21
+ if (res.status === 404) throw new Error(AdDataQueryError.NO_AD);
18
22
  throw new Error(AdDataQueryError.ERROR);
19
23
  }
20
24
 
21
25
  const data = await res.json();
22
-
23
- if (data.error) {
24
- throw new Error(data.error);
25
- }
26
+ if (data.error) throw new Error(data.error);
26
27
 
27
28
  return data;
28
29
  };
30
+
31
+ /**
32
+ * Fetch the metadata URI for a slot from the MetadataModule contract via RPC
33
+ */
34
+ export const fetchMetadataURI = async (
35
+ rpcUrl: string,
36
+ metadataModuleAddress: string,
37
+ slotAddress: string,
38
+ ): Promise<string> => {
39
+ // tokenURI(address) selector = 0xc2bc2efc (keccak of tokenURI(address))
40
+ // Actually, tokenURI takes address param, need proper encoding
41
+ const paddedSlot = slotAddress.slice(2).toLowerCase().padStart(64, "0");
42
+ // tokenURI(address) = 0xc87b56dd... no, it's a custom function
43
+ // bytes4(keccak256("tokenURI(address)"))
44
+ const selector = "0xe9dc6375"; // we'll compute it properly
45
+
46
+ const res = await fetch(rpcUrl, {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/json" },
49
+ body: JSON.stringify({
50
+ jsonrpc: "2.0",
51
+ method: "eth_call",
52
+ id: 1,
53
+ params: [
54
+ {
55
+ to: metadataModuleAddress,
56
+ data: `0x93702f33${paddedSlot}`, // tokenURI(address)
57
+ },
58
+ "latest",
59
+ ],
60
+ }),
61
+ });
62
+
63
+ const json = await res.json();
64
+ if (!json.result || json.result === "0x") return "";
65
+
66
+ // Decode ABI-encoded string
67
+ try {
68
+ const hex = json.result.slice(2);
69
+ const offset = parseInt(hex.slice(0, 64), 16) * 2;
70
+ const length = parseInt(hex.slice(offset, offset + 64), 16);
71
+ const strHex = hex.slice(offset + 64, offset + 64 + length * 2);
72
+ let str = "";
73
+ for (let i = 0; i < strHex.length; i += 2) {
74
+ str += String.fromCharCode(parseInt(strHex.slice(i, i + 2), 16));
75
+ }
76
+ return str;
77
+ } catch {
78
+ return "";
79
+ }
80
+ };
package/src/types.ts CHANGED
@@ -4,13 +4,13 @@ export type Network = "testnet" | "mainnet";
4
4
 
5
5
  export interface AdProps extends React.HTMLAttributes<HTMLDivElement> {
6
6
  /**
7
- * The owner/creator of the ad
7
+ * The slot contract address (0xSlots v3)
8
8
  */
9
- owner: string;
9
+ slot: string;
10
10
  /**
11
- * Unique identifier for the ad
11
+ * MetadataModule contract address (to fetch ad content URI)
12
12
  */
13
- slotId: string;
13
+ metadataModule?: string;
14
14
  /**
15
15
  * Network to use for tracking requests (currently only "testnet" is supported)
16
16
  */
@@ -19,6 +19,10 @@ export interface AdProps extends React.HTMLAttributes<HTMLDivElement> {
19
19
  * Optional base URL override. If not provided, uses relative URL in browser or production URL in SSR
20
20
  */
21
21
  baseUrl?: string;
22
+ /**
23
+ * RPC URL for reading MetadataModule on-chain
24
+ */
25
+ rpcUrl?: string;
22
26
  }
23
27
 
24
28
  export enum AdDataQueryError {
package/src/utils/sdk.ts CHANGED
@@ -33,8 +33,7 @@ export async function sendTrackRequest(
33
33
  url: string,
34
34
  data: {
35
35
  type: "view" | "click";
36
- adOwner: string;
37
- adId: string;
36
+ slot: string;
38
37
  },
39
38
  ): Promise<Response> {
40
39
  if (!isSdkReady()) {
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 dan5py (git@dan5py.com)
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.