Giter VIP home page Giter VIP logo

catoff-reclaim-integration-proposal's Introduction

Reclaim Integration Open Source Project

Welcome to the Catoff-Reclaim Integration Open Source Project! This project allows users to integrate different data providers with the Reclaim protocol for use within the Catoff platform. By following the steps outlined in this guide, you can contribute new integrations to the project.

Table of Contents

Introduction

The Catoff-Reclaim Integration Project is designed to facilitate the integration of various data providers with the Reclaim protocol for use within the Catoff platform. Each integration is managed through a service file that processes data from a specific provider and formats it into the ReclaimServiceResponse structure.

How to Contribute

1. Submit a Proposal

Before adding a new integration, you must submit a proposal. Your proposal should follow the template provided below. The proposal serves to explain your intended integration, gather community feedback, and document the design decisions.

Proposal Template

| proposal | title              | description                   | author                     | discussions-to | status | type        | category | created    | requires |
|----------|--------------------|-------------------------------|----------------------------|----------------|--------|-------------|----------|------------|----------|
| <Proposal Number> | <Proposal Title> | <Brief description of the proposal> | <Your Name> <Your Email> |                | Draft  | Integration | CRIP     | <Date>    |          |

## Title

<Provide a concise title for your proposal>

## Introduction

<Provide an introduction to the integration you are proposing. Explain the context and motivation behind the proposal.>

## External APIs Needed

<List any external APIs that are required for this integration.>

## Use Cases

<Describe the use cases for this integration. Explain how it can be used and who will benefit from it.>

## Data Provider

- **Name**: <Data Provider Name>
- **Hash Value**: <Hash Value from Reclaim Website>

## Code Snippet

<Provide a code snippet that demonstrates the key parts of the integration. Use the service file template as a guide.>

2. Implement the Integration

Once your proposal is accepted, follow the steps below to add your new integration:

  1. Create a new service file in the services directory.
  2. Add the necessary logic to process data from the new provider.
  3. Update the constants in utils/constants.js.
  4. Modify services/reclaimService.js to include your new integration.

3. Submit a Pull Request

After implementing the integration, submit a pull request for review. Ensure your code follows the project's style guidelines and passes all tests.

Service File Template

Create a new file in the services directory, e.g., newIntegrationService.js, and use the template below.

services/newIntegrationService.js

const { ReclaimServiceResponse } = require('../utils/reclaimServiceResponse')

exports.processNewIntegrationData = async (proof, providerName) => {
  // TODO: Extract relevant data from the proof
  // Replace 'newParameter' with the actual parameter you need to extract
  const newData = JSON.parse(proof[0].claimData.context).extractedParameters.newParameter

  // TODO: Process the extracted data
  // Adjust the extraction logic based on the actual format of the data
  // For example, if the data is a string with numeric value
  const newValue = newData.match(/value=\\"([\d,]+)/)[1].replace(/,/g, '')

  // TODO: Extract additional relevant data from the proof
  const url = JSON.parse(proof[0].claimData.parameters).url
  const matchurl = url.match(/user\/([^\/]+)/)
  const username = matchurl ? matchurl[1] : null
  const lastUpdateTimeStamp = JSON.parse(proof[0].claimData.timestampS)

  // TODO: Create a ReclaimServiceResponse object with the processed data
  // Adjust the parameters and processing logic based on the actual data structure
  return new ReclaimServiceResponse(providerName, lastUpdateTimeStamp, username, parseInt(newValue, 10), proof[0])
}

Update Constants

Add the new integration to the constants.js file.

utils/constants.js

exports.RECLAIM_PROVIDER_ID = {
  newIntegration: 'NEW_INTEGRATION_SERVICE',  // Add this line
}

exports.RECLAIM_APP_ID = {
  NEW_INTEGRATION_SERVICE: 'your-new-integration-app-id',  // Add this line
}

Update Reclaim Service

Import the new service and update the reclaimService.js file to handle the new integration.

services/reclaimService.js

const { Reclaim } = require('@reclaimprotocol/js-sdk')
const { RECLAIM_PROVIDER_ID, RECLAIM_APP_ID } = require('../utils/constants')
const { processSampleData } = require('./sampleService')
const { processNewIntegrationData } = require('./newIntegrationService')  // Add this line

exports.signWithProviderID = async (userId, challengeId, providerId) => {
  const providerName = RECLAIM_PROVIDER_ID[providerId]
  const reclaimAppID = RECLAIM_APP_ID[providerName]
  const reclaimAppSecret = process.env[`${providerName}_SECRET`]

  console.log(`Sending signature request to Reclaim for userId: ${userId} with providerName: ${providerName}`)

  try {
    const reclaimClient = new Reclaim.ProofRequest(reclaimAppID)
    await reclaimClient.buildProofRequest(providerId)
    reclaimClient.setSignature(await reclaimClient.generateSignature(reclaimAppSecret))
    const { requestUrl: signedUrl } = await reclaimClient.createVerificationRequest()

    await handleReclaimSession(userId, reclaimClient, providerName)
    return signedUrl
  } catch (error) {
    console.error(`Failed to process Reclaim request for userId: ${userId}`, error)
    throw error
  }
}

const handleReclaimSession = async (userId, reclaimClient, providerName) => {
  await reclaimClient.startSession({
    onSuccessCallback: async proof => {
      console.log(`Successful reclaim callback with proof: ${JSON.stringify(proof)}`)

      try {
        let processedData
        switch (providerName) {
          case 'SAMPLE_SERVICE':
            processedData = await processSampleData(proof, providerName)
            break
          case 'NEW_INTEGRATION_SERVICE':  // Add this case
            processedData = await processNewIntegrationData(proof, providerName)
            break
          default:
            throw new Error(`No handler for provider: ${providerName}`)
        }

        console.log(`Processed data: ${JSON.stringify(processedData)}`)
      } catch (error) {
        console.error(`Failed to process Reclaim proof for userId: ${userId}`, error)
      }
    },
    onFailureCallback: error => {
      console.error(`Verification failed for userId: ${userId}`, error)
    },
  })
}

Installation and Setup

  1. Clone the repository

    git clone https://github.com/CatoffGaming/catoff-reclaim-integration-proposal.git
    cd catoff-reclaim-integration-proposal
  2. Install dependencies

    npm install
  3. Create a .env file

    cp .env.example .env
  4. Update the .env file with your secrets.

  5. Run the application

    npm start
  6. Run linting and formatting

    npm run lint
    npm run lint:fix
    npm run format

Summary

Thank you for contributing to the Catoff-Reclaim Integration Open Source Project! Your contributions help expand the capabilities of Reclaim by integrating new data providers for use within Catoff. Follow the steps outlined in this guide to submit proposals and implement new integrations efficiently. If you have any questions, feel free to open an issue or reach out to the project maintainers.

catoff-reclaim-integration-proposal's People

Contributors

aryamanraj avatar

Stargazers

Adefokun Adeoluwa Israel avatar ASHWIN KV avatar Viraj Patva avatar JO3Y avatar  avatar Deepansh Gupta avatar Shashvat Patel avatar Raazi Muhammed K avatar Amir kamal avatar  avatar Danish avatar shahbaz avatar Madhu Lokesh avatar Sweta Karar avatar baturaλp avatar

catoff-reclaim-integration-proposal's Issues

Proposal - fitbit number of steps

proposal title description author discussions-to status type category created requires
CRIP-002 Fitbit Steps Integration Integrate Fitbit step count data with Reclaim Protocol for Catoff Your Name [email protected] Draft Integration CRIP 2024-08-06

Title

Fitbit Steps Integration for Reclaim Protocol

Introduction

This proposal aims to integrate Fitbit step count data with the Reclaim Protocol for use within the Catoff platform. By leveraging Fitbit's OAuth 2.0 authorization and step count API, we can create zero-knowledge proofs of users' walking activities, enabling innovative fitness-based challenges and wagers on the Catoff platform.

External APIs Needed

  • Fitbit OAuth 2.0 API
  • Fitbit Activities API (specifically, the step count endpoint)

Use Cases

  1. Daily Step Challenge: Users can create or participate in challenges to reach a certain number of steps per day, with wagers based on achieving the goal.
  2. Weekly Fitness Competition: Groups can compete for the highest total step count over a week, with automated payouts to the winners.

Data Provider

  • Name: Fitbit
  • Hash Value: [To be provided by Reclaim Protocol]

Code Snippet

const axios = require('axios')
const { ReclaimServiceResponse } = require('../utils/reclaimServiceResponse')

exports.processFitbitStepsData = async (proof, providerName) => {
  const fitbitUserId = JSON.parse(proof[0].claimData.context).extractedParameters.userId
  const lastUpdateTimeStamp = proof[0].claimData.timestampS
  const stepCount = await getUserSteps(fitbitUserId, accessToken)
  
  return new ReclaimServiceResponse(
    providerName,
    lastUpdateTimeStamp,
    fitbitUserId,
    stepCount,
    proof[0]
  )
}

const getUserSteps = async (userId, accessToken) => {
  const today = new Date().toISOString().split('T')[0]
  const url = `https://api.fitbit.com/1/user/${userId}/activities/steps/date/today/1d.json`
  
  try {
    const response = await axios.get(url, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    })
    
    const stepData = response.data['activities-steps'][0]
    console.log(`Total steps for ${userId} on ${today}: ${stepData.value}`)
    return parseInt(stepData.value, 10)
  } catch (error) {
    console.error('Error fetching Fitbit step data:', error.message)
    throw error
  }
}
}

handleReclaimSession not receiving response from startSession

In the handleReclaimSession function within reclaimService.js, the startSession call from the Reclaim library is coming undefined. The success or failure callbacks through onSuccessCallback and onFailureCallback are not being received.

While the logs indicate the session ends successfully, there's no data on its actual outcome.

Screenshot (304)
Screenshot (305)
Screenshot (306)

how to get the userId

I just had a look and was trying to run the code and so connected my github with reclaim. But I am not getting that what will be my user id ( which the server receive in req.body in reclaimController.js file. Can anyone help me out?

proposal - Twitter Hashtag Likes Verification - Integration to verify likes on tweets with a specific hashtag

proposal title description author discussions-to status type category created requires
001 Tweet Likes Verification Service Integration to verify the number of likes on a tweet with a specific hashtag Ritik Raj [email protected] Draft Integration CRIP 2024-07-11

Title

Tweet Likes Verification Service

Introduction

This proposal aims to introduce an integration that verifies the number of likes on a tweet containing a specific hashtag. This service will allow users to link their Twitter accounts and retrieve the number of likes on their tweets with specified hashtags. This feature enhances our application by providing users with deeper insights into the engagement their tweets receive based on specific topics.

External APIs Needed

Twitter API
Reclaim API

Use Cases

Marketing Analysis: Marketers can track the performance of their campaigns by monitoring likes on tweets with campaign-specific hashtags.
Content Creators: Influencers and content creators can measure the engagement of their posts related to particular topics or trends.
Research: Researchers can analyze public sentiment and engagement on tweets associated with specific hashtags.

Data Provider

Name: Twitter
Hash Value:

Code Snippet

utils/constants.js
exports.RECLAIM_PROVIDER_ID = {
twitter: 'TWITTER_ANALYTICS_VIEWS',
github: 'GITHUB_ACCOUNT_VERIFICATION',
tweetLikes: 'TWEET_LIKES_VERIFICATION', // Added for the new service
}

exports.RECLAIM_APP_ID = {
TWITTER_ANALYTICS_VIEWS: 'your-twitter-app-id',
GITHUB_ACCOUNT_VERIFICATION: 'your-github-app-id',
TWEET_LIKES_VERIFICATION: 'your-tweet-likes-app-id', // Added for the new service
}

services/reclaimService.js

const axios = require('axios')
const { Reclaim } = require('@reclaimprotocol/js-sdk')
const { RECLAIM_PROVIDER_ID, RECLAIM_APP_ID } = require('../utils/constants')
const { processTwitterData } = require('./twitterService')
const { processGitHubData } = require('./githubService')
const { processTweetLikesData } = require('./tweetLikesService') // Import the new service

exports.signWithProviderID = async (userId, providerId) => {
const providerName = RECLAIM_PROVIDER_ID[providerId]
const reclaimAppID = RECLAIM_APP_ID[providerName]
const reclaimAppSecret = process.env[${providerName}_SECRET]

console.log(
Sending signature request to Reclaim for userId: ${userId} with providerName: ${providerName}
)

try {
const reclaimClient = new Reclaim.ProofRequest(reclaimAppID)
await reclaimClient.buildProofRequest(providerId)
reclaimClient.setSignature(
await reclaimClient.generateSignature(reclaimAppSecret)
)
const { requestUrl: signedUrl } =
await reclaimClient.createVerificationRequest()

await handleReclaimSession(userId, reclaimClient, providerName)
return signedUrl

} catch (error) {
console.error(
Failed to process Reclaim request for userId: ${userId},
error
)
throw error
}
}

const handleReclaimSession = async (userId, reclaimClient, providerName) => {
await reclaimClient.startSession({
onSuccessCallback: async proof => {
console.log(
Successful reclaim callback with proof: ${JSON.stringify(proof)}
)

  try {
    let processedData
    switch (providerName) {
      case 'TWITTER_ANALYTICS_VIEWS':
        processedData = await processTwitterData(proof, providerName)
        break
      case 'GITHUB_ACCOUNT_VERIFICATION':
        processedData = await processGitHubData(proof, providerName)
        break
      case 'TWEET_LIKES_VERIFICATION':  // Handle the new service
        processedData = await processTweetLikesData(proof, providerName)
        break
      default:
        throw new Error(`No handler for provider: ${providerName}`)
    }

    console.log(`Processed data: ${JSON.stringify(processedData)}`)
  } catch (error) {
    console.error(
      `Failed to process Reclaim proof for userId: ${userId}`,
      error
    )
  }
},
onFailureCallback: error => {
  console.error(`Verification failed for userId: ${userId}`, error)
},

})
}

services/tweetLikesService.js

const { ReclaimServiceResponse } = require('../utils/reclaimServiceResponse')

exports.processTweetLikesData = async (proof, providerName) => {
// Extract relevant data from the proof
const tweetData = JSON.parse(proof[0].claimData.context).extractedParameters
const tweetLikes = tweetData.likes
const tweetHashtag = tweetData.hashtag
const tweetId = tweetData.tweetId

// Process the extracted data
const tweetLikesValue = tweetLikes.match(/likes=\"([\d,]+)/)[1].replace(/,/g, '')

// Extract additional relevant data from the proof
const url = JSON.parse(proof[0].claimData.parameters).url
const matchurl = url.match(/user/([^\/]+)/)
const username = matchurl ? matchurl[1] : null
const lastUpdateTimeStamp = JSON.parse(proof[0].claimData.timestampS)

// Create a ReclaimServiceResponse object with the processed data

return new ReclaimServiceResponse(
providerName,
lastUpdateTimeStamp,
username,
parseInt(tweetLikesValue, 10),
proof[0]
)
}

utils/reclaimServiceResponse.js

class ReclaimServiceResponse {
constructor(flag, timestamp, userName, targetValue, data) {
this.flag = flag
this.timestamp = timestamp
this.userName = userName
this.targetValue = targetValue
this.data = data
}
}

module.exports = { ReclaimServiceResponse }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.