Repository: Zizzamia/a-frame-in-100-lines
Branch: main
Commit: 525089eaff58
Files: 14
Total size: 16.4 KB
Directory structure:
gitextract_f7tggf9_/
├── .gitignore
├── LICENSE
├── README.md
├── app/
│ ├── _contracts/
│ │ └── BuyMeACoffeeABI.ts
│ ├── api/
│ │ ├── frame/
│ │ │ └── route.ts
│ │ ├── tx/
│ │ │ └── route.ts
│ │ └── tx-success/
│ │ └── route.ts
│ ├── config.ts
│ ├── layout.tsx
│ └── page.tsx
├── next-env.d.ts
├── package.json
├── prettier.config.js
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
node_modules
.DS_STORE
.next/
yarn.lock
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2024 Leonardo Zizzamia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# A Frame in 100 lines (or less)
Farcaster Frames in less than 100 lines, and ready to be deployed to Vercel.
To test a **deployed** Frame, use: https://warpcast.com/~/developers/frames.
To test a **localhost** Frame, use: [Framegear](https://onchainkit.xyz/frame/framegear).
A simple tool that allows you to run and test your frames locally:
- without publishing
- without casting
- without spending warps
And let us know what you build by either mentioning @zizzamia on [Warpcast](https://warpcast.com/zizzamia) or [X](https://twitter.com/Zizzamia).
Have fun! ⛵️
## App Routing files
- app/
- [config.ts](https://github.com/Zizzamia/a-frame-in-100-lines?tab=readme-ov-file#appconfigts)
- [layout.tsx](https://github.com/Zizzamia/a-frame-in-100-lines?tab=readme-ov-file#applayouttsx)
- [page.tsx](https://github.com/Zizzamia/a-frame-in-100-lines?tab=readme-ov-file#apppagetsx)
- api/
- frame/
- [route.ts](https://github.com/Zizzamia/a-frame-in-100-lines?tab=readme-ov-file#appapiframeroutets)
### `app/page.tsx`
```tsx
import { getFrameMetadata } from '@coinbase/onchainkit/frame';
import type { Metadata } from 'next';
import { NEXT_PUBLIC_URL } from './config';
const frameMetadata = getFrameMetadata({
buttons: [
{
label: 'Story time!',
},
{
action: 'link',
label: 'Link to Google',
target: 'https://www.google.com',
},
{
label: 'Redirect to pictures',
action: 'post_redirect',
},
],
image: {
src: `${NEXT_PUBLIC_URL}/park-3.png`,
aspectRatio: '1:1',
},
input: {
text: 'Tell me a boat story',
},
postUrl: `${NEXT_PUBLIC_URL}/api/frame`,
});
export const metadata: Metadata = {
title: 'zizzamia.xyz',
description: 'LFG',
openGraph: {
title: 'zizzamia.xyz',
description: 'LFG',
images: [`${NEXT_PUBLIC_URL}/park-1.png`],
},
other: {
...frameMetadata,
},
};
export default function Page() {
return (
<>
zizzamia.xyz
>
);
}
```
### `app/layout.tsx`
```tsx
export const viewport = {
width: 'device-width',
initialScale: 1.0,
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
### `app/config.ts`
```ts
export const NEXT_PUBLIC_URL = 'https://zizzamia.xyz';
```
### `app/api/frame/route.ts`
```ts
import { FrameRequest, getFrameMessage, getFrameHtmlResponse } from '@coinbase/onchainkit/frame';
import { NextRequest, NextResponse } from 'next/server';
import { NEXT_PUBLIC_URL } from '../../config';
async function getResponse(req: NextRequest): Promise {
let accountAddress: string | undefined = '';
let text: string | undefined = '';
const body: FrameRequest = await req.json();
const { isValid, message } = await getFrameMessage(body, { neynarApiKey: 'NEYNAR_ONCHAIN_KIT' });
if (isValid) {
accountAddress = message.interactor.verified_accounts[0];
}
if (message?.input) {
text = message.input;
}
if (message?.button === 3) {
return NextResponse.redirect(
'https://www.google.com/search?q=cute+dog+pictures&tbm=isch&source=lnms',
{ status: 302 },
);
}
return new NextResponse(
getFrameHtmlResponse({
buttons: [
{
label: `🌲 ${text} 🌲`,
},
],
image: {
src: `${NEXT_PUBLIC_URL}/park-1.png`,
},
postUrl: `${NEXT_PUBLIC_URL}/api/frame`,
}),
);
}
export async function POST(req: NextRequest): Promise {
return getResponse(req);
}
export const dynamic = 'force-dynamic';
```
## Resources
- [Official Farcaster Frames documentation](https://docs.farcaster.xyz/learn/what-is-farcaster/frames)
- [Official Farcaster Frame specification](https://docs.farcaster.xyz/reference/frames/spec)
- [OnchainKit documentation](https://onchainkit.xyz)
## Community ☁️ 🌁 ☁️
Check out the following places for more OnchainKit-related content:
- Follow @zizzamia ([X](https://twitter.com/zizzamia), [Farcaster](https://warpcast.com/zizzamia)) for project updates
- Join the discussions on our [OnchainKit warpcast channel](https://warpcast.com/~/channel/onchainkit)
## Authors
- [@zizzamia](https://github.com/zizzamia.png) ([X](https://twitter.com/Zizzamia))
- [@cnasc](https://github.com/cnasc.png) ([warpcast](https://warpcast.com/cnasc))
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
================================================
FILE: app/_contracts/BuyMeACoffeeABI.ts
================================================
/**
* This ABI is trimmed down to just the functions we expect to call for the
* sake of minimizing bytes downloaded.
*/
const abi = [
{ type: 'constructor', inputs: [], stateMutability: 'nonpayable' },
{ type: 'receive', stateMutability: 'payable' },
{
type: 'function',
name: 'buyCoffee',
inputs: [
{ name: 'numCoffees', type: 'uint256', internalType: 'uint256' },
{ name: 'message', type: 'string', internalType: 'string' },
],
outputs: [],
stateMutability: 'payable',
},
{
type: 'function',
name: 'getMemos',
inputs: [
{ name: 'index', type: 'uint256', internalType: 'uint256' },
{ name: 'size', type: 'uint256', internalType: 'uint256' },
],
outputs: [
{
name: '',
type: 'tuple[]',
internalType: 'struct Memo[]',
components: [
{ name: 'numCoffees', type: 'uint256', internalType: 'uint256' },
{ name: 'message', type: 'string', internalType: 'string' },
{ name: 'time', type: 'uint256', internalType: 'uint256' },
{ name: 'userAddress', type: 'address', internalType: 'address' },
],
},
],
stateMutability: 'view',
},
{
type: 'function',
name: 'memos',
inputs: [{ name: '', type: 'uint256', internalType: 'uint256' }],
outputs: [
{ name: 'numCoffees', type: 'uint256', internalType: 'uint256' },
{ name: 'message', type: 'string', internalType: 'string' },
{ name: 'time', type: 'uint256', internalType: 'uint256' },
{ name: 'userAddress', type: 'address', internalType: 'address' },
],
stateMutability: 'view',
},
{
type: 'function',
name: 'modifyMemoMessage',
inputs: [
{ name: 'index', type: 'uint256', internalType: 'uint256' },
{ name: 'message', type: 'string', internalType: 'string' },
],
outputs: [],
stateMutability: 'nonpayable',
},
{
type: 'function',
name: 'owner',
inputs: [],
outputs: [{ name: '', type: 'address', internalType: 'address payable' }],
stateMutability: 'view',
},
{
type: 'function',
name: 'price',
inputs: [],
outputs: [{ name: '', type: 'uint256', internalType: 'uint256' }],
stateMutability: 'view',
},
{
type: 'function',
name: 'removeMemo',
inputs: [{ name: 'index', type: 'uint256', internalType: 'uint256' }],
outputs: [],
stateMutability: 'nonpayable',
},
{
type: 'function',
name: 'setPriceForCoffee',
inputs: [{ name: '_price', type: 'uint256', internalType: 'uint256' }],
outputs: [],
stateMutability: 'nonpayable',
},
{
type: 'function',
name: 'withdrawTips',
inputs: [],
outputs: [],
stateMutability: 'nonpayable',
},
{
type: 'event',
name: 'BuyMeACoffeeEvent',
inputs: [
{ name: 'buyer', type: 'address', indexed: true, internalType: 'address' },
{ name: 'price', type: 'uint256', indexed: false, internalType: 'uint256' },
],
anonymous: false,
},
{
type: 'event',
name: 'NewMemo',
inputs: [
{ name: 'userAddress', type: 'address', indexed: true, internalType: 'address' },
{ name: 'time', type: 'uint256', indexed: false, internalType: 'uint256' },
{ name: 'numCoffees', type: 'uint256', indexed: false, internalType: 'uint256' },
{ name: 'message', type: 'string', indexed: false, internalType: 'string' },
],
anonymous: false,
},
{ type: 'error', name: 'InsufficientFunds', inputs: [] },
{
type: 'error',
name: 'InvalidArguments',
inputs: [{ name: 'message', type: 'string', internalType: 'string' }],
},
{ type: 'error', name: 'OnlyOwner', inputs: [] },
] as const;
export default abi;
================================================
FILE: app/api/frame/route.ts
================================================
import { FrameRequest, getFrameMessage, getFrameHtmlResponse } from '@coinbase/onchainkit/frame';
import { NextRequest, NextResponse } from 'next/server';
import { NEXT_PUBLIC_URL } from '../../config';
async function getResponse(req: NextRequest): Promise {
const body: FrameRequest = await req.json();
const { isValid, message } = await getFrameMessage(body, { neynarApiKey: 'NEYNAR_ONCHAIN_KIT' });
if (!isValid) {
return new NextResponse('Message not valid', { status: 500 });
}
const text = message.input || '';
let state = {
page: 0,
};
try {
state = JSON.parse(decodeURIComponent(message.state?.serialized));
} catch (e) {
console.error(e);
}
/**
* Use this code to redirect to a different page
*/
if (message?.button === 3) {
return NextResponse.redirect(
'https://www.google.com/search?q=cute+dog+pictures&tbm=isch&source=lnms',
{ status: 302 },
);
}
return new NextResponse(
getFrameHtmlResponse({
buttons: [
{
label: `State: ${state?.page || 0}`,
},
{
action: 'link',
label: 'OnchainKit',
target: 'https://onchainkit.xyz',
},
{
action: 'post_redirect',
label: 'Dog pictures',
},
],
image: {
src: `${NEXT_PUBLIC_URL}/park-1.png`,
},
postUrl: `${NEXT_PUBLIC_URL}/api/frame`,
state: {
page: state?.page + 1,
time: new Date().toISOString(),
},
}),
);
}
export async function POST(req: NextRequest): Promise {
return getResponse(req);
}
export const dynamic = 'force-dynamic';
================================================
FILE: app/api/tx/route.ts
================================================
import { FrameRequest, getFrameMessage } from '@coinbase/onchainkit/frame';
import { NextRequest, NextResponse } from 'next/server';
import { encodeFunctionData, parseEther } from 'viem';
import { baseSepolia } from 'viem/chains';
import BuyMeACoffeeABI from '../../_contracts/BuyMeACoffeeABI';
import { BUY_MY_COFFEE_CONTRACT_ADDR } from '../../config';
import type { FrameTransactionResponse } from '@coinbase/onchainkit/frame';
async function getResponse(req: NextRequest): Promise {
const body: FrameRequest = await req.json();
// Remember to replace 'NEYNAR_ONCHAIN_KIT' with your own Neynar API key
const { isValid } = await getFrameMessage(body, { neynarApiKey: 'NEYNAR_ONCHAIN_KIT' });
if (!isValid) {
return new NextResponse('Message not valid', { status: 500 });
}
const data = encodeFunctionData({
abi: BuyMeACoffeeABI,
functionName: 'buyCoffee',
args: [parseEther('1'), 'Coffee all day!'],
});
const txData: FrameTransactionResponse = {
chainId: `eip155:${baseSepolia.id}`,
method: 'eth_sendTransaction',
params: {
abi: [],
data,
to: BUY_MY_COFFEE_CONTRACT_ADDR,
value: parseEther('0.00004').toString(), // 0.00004 ETH
},
};
return NextResponse.json(txData);
}
export async function POST(req: NextRequest): Promise {
return getResponse(req);
}
export const dynamic = 'force-dynamic';
================================================
FILE: app/api/tx-success/route.ts
================================================
import { FrameRequest, getFrameMessage, getFrameHtmlResponse } from '@coinbase/onchainkit/frame';
import { NextRequest, NextResponse } from 'next/server';
import { NEXT_PUBLIC_URL } from '../../config';
async function getResponse(req: NextRequest): Promise {
const body: FrameRequest = await req.json();
const { isValid } = await getFrameMessage(body);
if (!isValid) {
return new NextResponse('Message not valid', { status: 500 });
}
return new NextResponse(
getFrameHtmlResponse({
buttons: [
{
label: `Tx: ${body?.untrustedData?.transactionId || '--'}`,
},
],
image: {
src: `${NEXT_PUBLIC_URL}/park-4.png`,
},
}),
);
}
export async function POST(req: NextRequest): Promise {
return getResponse(req);
}
export const dynamic = 'force-dynamic';
================================================
FILE: app/config.ts
================================================
// use NODE_ENV to not have to change config based on where it's deployed
export const NEXT_PUBLIC_URL =
process.env.NODE_ENV == 'development' ? 'http://localhost:3000' : 'https://zizzamia.xyz';
export const BUY_MY_COFFEE_CONTRACT_ADDR = '0xcD3D5E4E498BAb2e0832257569c3Fd4AE439dD6f';
================================================
FILE: app/layout.tsx
================================================
export const viewport = {
width: 'device-width',
initialScale: 1.0,
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
================================================
FILE: app/page.tsx
================================================
import { getFrameMetadata } from '@coinbase/onchainkit/frame';
import type { Metadata } from 'next';
import { NEXT_PUBLIC_URL } from './config';
const frameMetadata = getFrameMetadata({
buttons: [
{
label: 'Story time',
},
{
action: 'tx',
label: 'Send Base Sepolia',
target: `${NEXT_PUBLIC_URL}/api/tx`,
postUrl: `${NEXT_PUBLIC_URL}/api/tx-success`,
},
],
image: {
src: `${NEXT_PUBLIC_URL}/park-3.png`,
aspectRatio: '1:1',
},
input: {
text: 'Tell me a story',
},
postUrl: `${NEXT_PUBLIC_URL}/api/frame`,
});
export const metadata: Metadata = {
title: 'zizzamia.xyz',
description: 'LFG',
openGraph: {
title: 'zizzamia.xyz',
description: 'LFG',
images: [`${NEXT_PUBLIC_URL}/park-1.png`],
},
other: {
...frameMetadata,
},
};
export default function Page() {
return (
<>
zizzamia.xyz
>
);
}
================================================
FILE: next-env.d.ts
================================================
///
///
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
================================================
FILE: package.json
================================================
{
"name": "a-frame-in-100-lines",
"version": "0.14.0",
"scripts": {
"build": "rm -rf .next && next build",
"dev": "next dev",
"format": "prettier --log-level warn --write .",
"start": "next start",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "https://twitter.com/Zizzamia",
"license": "MIT",
"dependencies": {
"@coinbase/onchainkit": "^0.27.0",
"next": "13.5.6",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^20.11.8",
"@types/react": "18.2.48",
"prettier": "^3.2.4",
"typescript": "^5.3.3"
}
}
================================================
FILE: prettier.config.js
================================================
module.exports = {
arrowParens: 'always',
bracketSameLine: false,
jsxSingleQuote: false,
plugins: [],
printWidth: 100,
semi: true,
singleQuote: true,
tabWidth: 2,
trailingComma: 'all',
useTabs: false,
};
================================================
FILE: tsconfig.json
================================================
{
"compilerOptions": {
"target": "es2020",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
]
},
"include": ["custom.d.ts", "next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["contracts", "node_modules"],
}