Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/code structure #38

Merged
merged 15 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4,254 changes: 3,809 additions & 445 deletions push-snap-site/pnpm-lock.yaml

Large diffs are not rendered by default.

3,731 changes: 1,498 additions & 2,233 deletions push-snap-site/yarn.lock

Large diffs are not rendered by default.

84 changes: 50 additions & 34 deletions snap-optin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,62 @@ import * as PushAPI from '@pushprotocol/restapi';
import { ENV } from '@pushprotocol/restapi/src/lib/constants';
import axios from 'axios';

const snapOptIn = async (signer:PushAPI.SignerType,address:string, channelAddress: string, chainid: string) => {
/**
* Opt-in a user to a Push Notification channel using Snaps.
* @param signer The signer type used for channel subscription.
* @param address The user's Ethereum address.
* @param channelAddress The address of the channel to opt into.
* @param chainid The ID of the blockchain chain.
*/
const snapOptIn = async (signer: PushAPI.SignerType, address: string, channelAddress: string, chainid: string) => {

const defaultSnapOrigin='npm:@pushprotocol/snap'
// Define the default Snap origin
const defaultSnapOrigin = 'npm:@pushprotocol/snap'

// Request user opt-in using the wallet_invokeSnap method
const res = await window.ethereum?.request({
method: "wallet_invokeSnap",
params: {
snapId: defaultSnapOrigin,
request: { method: "pushproto_optin", params:{
channelAddress: channelAddress
} },
},
method: "wallet_invokeSnap",
params: {
snapId: defaultSnapOrigin,
request: {
method: "pushproto_optin",
params: {
channelAddress: channelAddress
}
},
},
});

// If user opt-in is successful, subscribe the user to the channel
if (res) {
await PushAPI.channels.subscribe({
signer: signer,
channelAddress: `eip155:${chainid}:${channelAddress}`,
userAddress: `eip155:${chainid}:${address}`,
onSuccess: () => {
console.log("opt in success");
},
onError: () => {
console.error("opt in error");
},
env: ENV.PROD,
});

let subscribed = await axios.get(`https://backend-staging.epns.io/apis/v1/users/eip155:${chainid}:${address}/subscriptions`);
subscribed = subscribed.data.subscriptions;
if(subscribed.length == 1){
await window.ethereum?.request({
method: "wallet_invokeSnap",
params: {
snapId: defaultSnapOrigin,
request: { method: "pushproto_firstchanneloptin"},
},
await PushAPI.channels.subscribe({
signer: signer,
channelAddress: `eip155:${chainid}:${channelAddress}`,
userAddress: `eip155:${chainid}:${address}`,
onSuccess: () => {
console.log("opt in success");
},
onError: () => {
console.error("opt in error");
},
env: ENV.PROD,
});
}

// Check if the user has only one subscription and trigger the first channel opt-in
let subscribed = await axios.get(`https://backend-staging.epns.io/apis/v1/users/eip155:${chainid}:${address}/subscriptions`);
subscribed = subscribed.data.subscriptions;
if (subscribed.length == 1) {
await window.ethereum?.request({
method: "wallet_invokeSnap",
params: {
snapId: defaultSnapOrigin,
request: {
method: "pushproto_firstchanneloptin"
},
},
});
}
}
};
};

export default snapOptIn;
export default snapOptIn;
2 changes: 1 addition & 1 deletion snap-ui/src/components/SnapButton/SnapOptInButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const SnapOptInButton = ({ address, signer }: Props) => {
}, [signer, address]);

const checkSubscription = async () => {
const url = `https://backend-staging.epns.io/apis/v1/channels/eip155:5:${address}/subscribers`;
const url = `https://backend-staging.epns.io/apis/v1/channels/eip155:11155111:${address}/subscribers`;

let response = await fetch(url, {
method: "get",
Expand Down
Binary file added snap/.DS_Store
Binary file not shown.
16 changes: 16 additions & 0 deletions snap/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ['plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: ['@typescript-eslint'],
rules: {
},
ignorePatterns: ['!.eslintrc.js', 'dist/'],
};
4 changes: 4 additions & 0 deletions snap/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules

# Optional eslint cache
.eslintcache
63 changes: 63 additions & 0 deletions snap/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@

# Push Protocol Snap

A MetaMask Snap for delivering channel notifications and chat notifications right in your metamask wallet


## Run Locally

Clone the project

```bash
git clone https://github.com/ethereum-push-notification-service/push-protocol-snaps
```

Go to the snap directory

```bash
cd snap
```

Install dependencies

```bash
yarn install
```

Start the server

```bash
yarn start
```

Go to the dapp directory

```bash
cd push-snap-site
```

Install dependencies

```bash
npm i
```

Start the server

```bash
npm run dev
```

## Using the npm package
Make the following changes in the dapp
- Change all occurrences of ```defaultSnapOrigin``` from ```local:http://localhost:8080``` to ```npm:push-v1``` in the push-snap-site codebase

## Permissions asked by the Snap
- Local-storage : To store the addresses to send notifications and pgp private key to send PUSH Chat notifications
- Periodic actions (Cron job) : This include sending notifications every minute to the wallet
- Dialog Boxes : This includes Popups for showing notifications on screen and initial screen
- Internet Access : The snap has internet access and can make api calls using fetch()
- Ethereum Provider : This allows the snap to access the first connected account in metamask (🚨 This doesn’t not have access to your funds neither can do transaction on your behalf)



1 change: 1 addition & 0 deletions snap/dist/bundle.js

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions snap/images/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added snap/images/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
63 changes: 63 additions & 0 deletions snap/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"name": "@pushprotocol/snap",
"version": "1.1.12",
"description": "Get Push Notifications directly in your MetaMask wallet!",
"repository": {
"type": "git",
"url": "https://github.com/ethereum-push-notification-service/push-protocol-snaps"
},
"license": "GNU General Public License v2.0",
"main": "src/index.ts",
"files": [
"dist/",
"images/",
"snap.manifest.json"
],
"scripts": {
"build": "mm-snap build",
"build:clean": "yarn clean && yarn build",
"build:website": "node ./scripts/build-website.js",
"clean": "rimraf dist",
"lint": "yarn lint:eslint && yarn lint:misc --check",
"lint:eslint": "eslint . --cache --ext js,ts",
"lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
"lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' --ignore-path .gitignore",
"serve": "mm-snap serve",
"start": "tsc --noEmit && mm-snap watch"
},
"devDependencies": {
"@lavamoat/allow-scripts": "^2.0.3",
"@metamask/auto-changelog": "^2.6.0",
"@metamask/eslint-config": "^10.0.0",
"@metamask/eslint-config-jest": "^10.0.0",
"@metamask/eslint-config-nodejs": "^10.0.0",
"@metamask/eslint-config-typescript": "^10.0.0",
"@metamask/snaps-cli": "^4.0.1",
"@metamask/snaps-types": "^0.32.2",
"@metamask/snaps-ui": "^0.32.2",
"@typescript-eslint/eslint-plugin": "^5.33.0",
"@typescript-eslint/parser": "^5.33.0",
"eslint": "^8.21.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jest": "^26.8.2",
"eslint-plugin-jsdoc": "^39.2.9",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.2.1",
"prettier": "^2.2.1",
"prettier-plugin-packagejson": "^2.2.11",
"rimraf": "^3.0.2",
"typescript": "^4.7.4"
},
"packageManager": "[email protected]",
"engines": {
"node": ">=16.0.0"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"dependencies": {
"ethers": "5.7.2"
}
}
6 changes: 6 additions & 0 deletions snap/snap.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
cliOptions: {
src: './src/index.ts',
port: 8080,
},
};
42 changes: 42 additions & 0 deletions snap/snap.manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"version": "1.1.12",
"description": "Get Push Notifications directly in your MetaMask wallet!",
"proposedName": "Push",
"repository": {
"type": "git",
"url": "https://github.com/ethereum-push-notification-service/push-protocol-snaps"
},
"source": {
"shasum": "3h8QmRFISxpD5m+g41R5ZvNlMFMSe14ITrjkVnLwI9M=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
"iconPath": "images/icon.svg",
"packageName": "@pushprotocol/snap",
"registry": "https://registry.npmjs.org/"
}
}
},
"initialPermissions": {
"snap_dialog": {},
"endowment:rpc": {
"dapps": true,
"snaps": false
},
"snap_notify": {},
"endowment:cronjob": {
"jobs": [
{
"expression": "* * * * *",
"request": {
"method": "notifCronJob"
}
}
]
},
"endowment:network-access": {},
"snap_manageState": {},
"endowment:ethereum-provider": {}
},
"manifestVersion": "0.1"
}
15 changes: 15 additions & 0 deletions snap/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { LatestSnapState } from "../types";

export const allowedSnapOrigins = [
"https://app.push.org",
"https://staging.push.org",
"https://dev.push.org",
"http://localhost:3000",
];

export const BASE_URL = 'https://backend.epns.io/apis/v1'; // Modify this as needed

export const defaultLatestSnapState: LatestSnapState = {
version: 1,
addresses: {}
}
33 changes: 33 additions & 0 deletions snap/src/handlers/cronJobHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { OnCronjobHandler } from "@metamask/snaps-types";
import { notifCronJob } from "../methods";
import { SnapCronJobMethod } from "../types";

/**
* Handles cronjobs for the Snap, executing the appropriate method based on the request.
* @param {object} options - The options for handling the cronjob.
* @param {object} options.request - The request object containing information about the cronjob.
* @param {string} options.request.method - The method to execute for the cronjob.
* @throws {Error} Throws an error if the specified method is not found.
*/
export const onCronjob: OnCronjobHandler = async ({ request }) => {
try {
switch (request.method as SnapCronJobMethod) {
case SnapCronJobMethod.NotifCronJob:
await notifCronJob();
break;
// case SnapCronJobMethod.CheckActivityCronJob:
// await checkActivityCronJob();
// break;
// case SnapCronJobMethod.RemoveSnoozeCronJob:
// await removeSnoozeCronJob();
// break;
default:
throw new Error("Method not found.");
}
} catch (error) {
// Handle or log the error as needed
console.error("Error in onCronjob:", error);
// Optionally rethrow the error if you want it to propagate further
throw error;
}
};
Loading