Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jlm0 authored Jun 19, 2024
0 parents commit c7d3832
Show file tree
Hide file tree
Showing 29 changed files with 2,734 additions and 0 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This is a basic workflow to help you get started with Actions

name: Build and Deploy

on:
push:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout 🛎️
uses: actions/[email protected]
- name: install dependencies
run: npm install
- name: Build
run: npm run build
env:
CI: false
- name: Deploy 🚀
uses: JamesIves/[email protected]
with:
branch: gh-pages # The branch the action should deploy to.
folder: dist # The folder the action should deploy.

permissions:
contents: write
24 changes: 24 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 TON @ DeFi.org

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.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# twa-template

> Starter template for a new TWA interacting with the TON blockchain
# Overview

The project is highly-opinionated, and there are many other alternate routes it could have taken. Some examples:

- Supports Ton Connect 2 wallets
- Uses vite with react (alternative to create-react-app)
- Uses the `ton` npm package

# Prerequesities

- Node.js v16 (other versions may work, needs more testing)
- A TON Connect compatible wallet (e.g. [Tonkeeper](https://tonkeeper.com/))

# What does this repo contain?

- A react-based TWA-ready app, interacting with TON
- Github actions set to deploy app to github pages
- A script to connect a telegram bot to the deployed app

# How to use

1. Create a template from this repo with the "Use this template" button

1. Choose a name for your repo
2. `**IMPORTANT!!**` mark "Include all branches", otherwise github pages deployment will not work.
![image](https://user-images.githubusercontent.com/5641469/191731317-14e742fd-accb-47d4-a794-fad01148a377.png)

2. Clone this repo and run `yarn`

3. Create a new bot with [botfather](https://t.me/botfather)
1. Type `/newbot`
2. Choose a name for your bot, e.g. `My Ton TWA`
3. Choose a username for your bot, e.g. `my_ton_twa_482765_bot`
4. Take note of the access token, e.g. `5712441624:AAHmiHvwrrju1F3h29rlVOZLRLnv-B8ZZZ`
5. Run `yarn configbot` to link your bot to the webapp

# Development

1. Run `npm run dev` and edit the code as needed
2. On push to the `main` branch, the app will be automatically deployed via github actions.

# Roadmap

- [ ] Jetton transfer support

# License

MIT
89 changes: 89 additions & 0 deletions configure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import axios from "axios";
import { createInterface } from "readline";
import fs from "fs";
import { promisify } from "util";

const rl = createInterface({
input: process.stdin,
output: process.stdout,
});

const question = (question) =>
new Promise((resolve) => rl.question(question, resolve));

function exitError(error) {
console.error(`Error! ${error}`);
process.exit(1);
}

const banner = `
████████╗██╗ ██╗ █████╗ ████████╗███████╗███╗ ███╗██████╗ ██╗ █████╗ ████████╗███████╗
╚══██╔══╝██║ ██║██╔══██╗ ╚══██╔══╝██╔════╝████╗ ████║██╔══██╗██║ ██╔══██╗╚══██╔══╝██╔════╝
██║ ██║ █╗ ██║███████║ ██║ █████╗ ██╔████╔██║██████╔╝██║ ███████║ ██║ █████╗
██║ ██║███╗██║██╔══██║ ██║ ██╔══╝ ██║╚██╔╝██║██╔═══╝ ██║ ██╔══██║ ██║ ██╔══╝
██║ ╚███╔███╔╝██║ ██║ ██║ ███████╗██║ ╚═╝ ██║██║ ███████╗██║ ██║ ██║ ███████╗
╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝
`;

console.log(banner);

let githubUsername, githubRepo, botUsername;

(async () => {
try {
const file = fs.readFileSync(".git/config").toString();
const url = file.match(/url = (.*)/)[1];
console.log(url);
const params = url.match(/github.com[/:]([^/]*)\/(.*)\.git/);
githubUsername = params[1];
githubRepo = params[2];
} catch (e) {}

const accessToken = await question("Enter your bot access token: ");
if (!accessToken?.length > 0) exitError("Token is required");

const githubUsernameQ = await question(
`Enter your github username${
githubUsername ? ` (${githubUsername})` : ``
}: `
);
githubUsername = githubUsernameQ || githubUsername;
if (!githubUsername?.length > 0) exitError("Github username is required");

const githubRepoQ = await question(
`Enter your forked repo name${githubRepo ? ` (${githubRepo})` : ``}: `
);
githubRepo = githubRepoQ || githubRepo;
if (!githubRepo?.length > 0) exitError("Repo name is required");

const getBot = await axios.get(
`https://api.telegram.org/bot${accessToken}/getMe`
).catch(exitError);

botUsername = getBot.data.result.username;
const url = `https://${githubUsername}.github.io/${githubRepo}`;

console.log(`\n\nSetting bot ${botUsername} webapp url to ${url}`);

const resp = await axios.post(
`https://api.telegram.org/bot${accessToken}/setChatMenuButton`,
{
menu_button: {
type: "web_app",
text: "Launch Webapp",
web_app: {
url: url,
},
},
}
).catch(exitError);

if (resp.status === 200) {
console.log(
`\nYou're all set! Visit https://t.me/${botUsername} to interact with your bot`
);
process.exit();
} else {
exitError(`\nSomething went wrong! ${resp.error}`);
}
})();
13 changes: 13 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ton Sample TWA</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
37 changes: 37 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "ton-starter-twa-vite",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"configbot": "node configure.js"
},
"dependencies": {
"@orbs-network/ton-access": "^2.2.2",
"@tanstack/react-query": "^4.24.4",
"@tonconnect/ui-react": "^2.0.0-beta.2",
"@twa-dev/sdk": "^6.4.2",
"buffer": "^6.0.3",
"is-mobile": "^3.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"styled-components": "^5.3.6",
"ton": "13.3.0",
"ton-core": "^0.46.0",
"ton-crypto": "^3.2.0",
"use-local-storage": "^2.3.6",
"vite-plugin-node-polyfills": "^0.7.0"
},
"devDependencies": {
"@types/node": "^18.11.18",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@types/styled-components": "^5.1.26",
"@vitejs/plugin-react": "^3.0.1",
"typescript": "^4.9.5",
"vite": "^4.0.4"
}
}
1 change: 1 addition & 0 deletions public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
:root {
--tg-theme-bg-color: #efeff3;
--tg-theme-button-color: #2eaddc;
--tg-theme-button-text-color: white;
}
55 changes: 55 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import "./App.css";
import { TonConnectButton } from "@tonconnect/ui-react";
import { Counter } from "./components/Counter";
import { Jetton } from "./components/Jetton";
import { TransferTon } from "./components/TransferTon";
import styled from "styled-components";
import { Button, FlexBoxCol, FlexBoxRow } from "./components/styled/styled";
import { useTonConnect } from "./hooks/useTonConnect";
import { CHAIN } from "@tonconnect/protocol";
import "@twa-dev/sdk";

const StyledApp = styled.div`
background-color: #e8e8e8;
color: black;

@media (prefers-color-scheme: dark) {
background-color: #222;
color: white;
}
min-height: 100vh;
padding: 20px 20px;
`;

const AppContainer = styled.div`
max-width: 900px;
margin: 0 auto;
`;

function App() {
const { network } = useTonConnect();

return (
<StyledApp>
<AppContainer>
<FlexBoxCol>
<FlexBoxRow>
<TonConnectButton />
<Button>
{network
? network === CHAIN.MAINNET
? "mainnet"
: "testnet"
: "N/A"}
</Button>
</FlexBoxRow>
<Counter />
<TransferTon />
<Jetton />
</FlexBoxCol>
</AppContainer>
</StyledApp>
);
}

export default App;
45 changes: 45 additions & 0 deletions src/components/Counter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { TonConnectButton } from "@tonconnect/ui-react";
import { useCounterContract } from "../hooks/useCounterContract";
import { useTonConnect } from "../hooks/useTonConnect";

import {
Card,
FlexBoxCol,
FlexBoxRow,
Ellipsis,
Button,
} from "./styled/styled";

export function Counter() {
const { connected } = useTonConnect();
const { value, address, sendIncrement } = useCounterContract();

return (
<div className="Container">
<TonConnectButton />

<Card>
<FlexBoxCol>
<h3>Counter</h3>
<FlexBoxRow>
<b>Address</b>
<Ellipsis>{address}</Ellipsis>
</FlexBoxRow>
<FlexBoxRow>
<b>Value</b>
<div>{value ?? "Loading..."}</div>
</FlexBoxRow>
<Button
disabled={!connected}
className={`Button ${connected ? "Active" : "Disabled"}`}
onClick={() => {
sendIncrement();
}}
>
Increment
</Button>
</FlexBoxCol>
</Card>
</div>
);
}
Loading

0 comments on commit c7d3832

Please sign in to comment.