humanity protocol
  • Introduction
    • Overview
    • How Humanity Protocol Works
    • Palm Scanner
  • Getting Started
    • Network Configuration
    • Important Links
  • Testnet Info
    • Onboarding Tutorial
    • Testnet Rewards
    • Testnet FAQ
  • Build on Humanity
    • API
      • Issue Credentials (VCs)
      • Verify Credentials (VCs)
      • Revoke Credentials (VCs)
      • List Client Credentials (VCs)
    • Contracts
      • VC contract
      • Rewards contract
    • Contract Integrations Guide
    • Examples
      • Fairdrops
      • Social Media VCs
  • Glossary
  • Community/Support
Powered by GitBook
On this page
  • Basic Integration Concepts
  • VC Contract Integration
  • Rewards Contract Integration
  • Web3.js/Ethers.js Integration Examples
  • Best Practices
  • Contract Interfaces
  1. Build on Humanity

Contract Integrations Guide

This guide explains how to integrate with the Humanity Protocol's VC and Rewards contracts in your own applications.

Basic Integration Concepts

Interacting with Humanity Protocol typically involves two key aspects:

  1. Verifying a user's humanity via the VC contract

  2. Managing rewards via the Rewards contract

VC Contract Integration

Checking User Verification

The most common integration is checking if a user is verified before allowing them to access your services:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IVC } from "./interfaces/IVC.sol";

contract YourApplication {
    IVC private vcContract;
    
    constructor(address vcContractAddress) {
        vcContract = IVC(vcContractAddress);
    }
    
    modifier onlyVerifiedHuman() {
        require(vcContract.isVerified(msg.sender), "User not verified on Humanity Protocol");
        _;
    }
    
    function protectedFunction() external onlyVerifiedHuman {
        // Logic that requires verified humanity
    }
    
    function getReferrers(address user) external view returns (address[] memory) {
        return vcContract.getReferrersTree(user);
    }
}

Getting Referral Information

You can also use referral data to build custom rewards in your own application:

function implementReferralBonus(address user) external {
    address[] memory referrers = vcContract.getReferrersTree(user);
    if (referrers.length > 0) {
        // Provide bonus to the first referrer
        _grantBonus(referrers[0]);
    }
}

Rewards Contract Integration

Checking Reward Eligibility

You might want to check if a user has claimed their reward before offering additional features:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IRewards } from "./interfaces/IRewards.sol";

contract YourRewardsExtension {
    IRewards private rewardsContract;
    
    constructor(address rewardsContractAddress) {
        rewardsContract = IRewards(rewardsContractAddress);
    }
    
    function checkDailyClaimStatus(address user) public view returns (bool hasClaimed) {
        uint256 currentEpoch = rewardsContract.currentEpoch();
        IRewards.UserClaim memory claim = rewardsContract.userClaimStatus(user, currentEpoch);
        return claim.claimStatus;
    }
    
    function offerBonus() external {
        require(!checkDailyClaimStatus(msg.sender), "Already claimed today");
        // Offer bonus only to users who haven't claimed their daily reward
    }
}

Listening for Reward Events

You can also listen for reward events to trigger actions in your application:

const { ethers } = require('ethers');
const provider = new ethers.providers.JsonRpcProvider('https://rpc.testnet.humanity.org');

const rewardsAddress = '0x8De84C60D8b970fB2152024eB3f1b9a205f45536';
const rewardsAbi = [...]; // Rewards contract ABI

const rewardsContract = new ethers.Contract(rewardsAddress, rewardsAbi, provider);

// Listen for reward claims
rewardsContract.on('RewardClaimed', (user, rewardType, amount, event) => {
  console.log(`User ${user} claimed ${ethers.utils.formatEther(amount)} tokens`);
  console.log(`Reward type: ${rewardType}`); // 0 = Genesis, 1 = Daily, 2 = Referral
  
  // Your application logic here
});

Web3.js/Ethers.js Integration Examples

Checking Verification Status

const { ethers } = require('ethers');
const provider = new ethers.providers.JsonRpcProvider('https://rpc.testnet.humanity.org');

const vcAddress = '0xCC766b5F2d1173E72D9fE9ca8575202Fcee89590';
const vcAbi = [...]; // VC contract ABI

const vcContract = new ethers.Contract(vcAddress, vcAbi, provider);

async function checkUserVerification(userAddress) {
    try {
        const isVerified = await vcContract.isVerified(userAddress);
        console.log(`User ${userAddress} verified: ${isVerified}`);
        return isVerified;
    } catch (error) {
        console.error('Error checking verification:', error);
        return false;
    }
}

Claiming Rewards

const { ethers } = require('ethers');
const provider = new ethers.providers.JsonRpcProvider('https://rpc.testnet.humanity.org');
const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider);

const rewardsAddress = '0x8De84C60D8b970fB2152024eB3f1b9a205f45536';
const rewardsAbi = [...]; // Rewards contract ABI

const rewardsContract = new ethers.Contract(rewardsAddress, rewardsAbi, wallet);

async function claimReward() {
    try {
        const tx = await rewardsContract.claimReward();
        console.log('Transaction sent:', tx.hash);
        
        const receipt = await tx.wait();
        console.log('Transaction confirmed in block:', receipt.blockNumber);
        
        // Parse the event logs
        const claimEvent = receipt.events.find(e => e.event === 'RewardClaimed');
        if (claimEvent) {
            const [user, rewardType, amount] = claimEvent.args;
            console.log(`Claimed ${ethers.utils.formatEther(amount)} tokens`);
        }
        
        return true;
    } catch (error) {
        console.error('Error claiming reward:', error);
        return false;
    }
}

Best Practices

Security Considerations

  1. Always verify contract addresses: Ensure you're interacting with the official Humanity Protocol contracts

  2. Check returned values: Always validate return values from contract calls

  3. Handle error states gracefully: Implement proper error handling for failed transactions

  4. Use event listeners cautiously: Consider the potential for missed events due to network issues

Performance Optimizations

  1. Batch operations: Use the batch functions when possible for multiple registrations or verifications

  2. Cache verification status: Consider caching verification results to reduce RPC calls

  3. Monitor gas costs: Be mindful of gas costs, especially for batch operations

Frontend Integration Tips

  1. Connect wallet first: Always ensure wallet connection before attempting contract interactions

  2. Show pending transactions: Provide feedback for users during transaction processing

  3. Handle network changes: Be prepared for users switching networks

  4. Responsive error handling: Display user-friendly error messages

Contract Interfaces

IVC Interface

interface IVC {
    struct User {
        address userAddr;
        address referrerAddr;
        bool verified;
    }
    
    struct SocialVCParams {
        address userAddr;
        string social;
        string vc;
    }
    
    function totalUsers() external view returns (uint256);
    function totalVerifiedUsers() external view returns (uint256);
    function getUser(address user) external view returns (User memory);
    function isVerified(address user) external view returns (bool);
    function isRegistered(address user) external view returns (bool);
    function getReferrersTree(address user) external view returns (address[] memory);
    function isSocialVerified(address user, string memory social) external view returns (bool);
    function getSocialVerifiedCount(address user) external view returns (uint256);
    function getUsersCountOnRegistration(address user) external view returns (uint256);
    
    function init() external;
    function register(address userAddress, address referrerAddress) external;
    function verifyUser(address user) external;
    function batchSocialVC(SocialVCParams[] calldata params) external;
    function processBatch(User[] calldata users) external;
    
    event UserRegistered(address userAddress, address referrerAddress);
    event UserVerified(address user);
    event SocialVCVerified(address userAddr, string social, string vc);
    event SocialVCRevoked(address userAddr, string social);
}

IRewards Interface

interface IRewards {
    enum RewardType {
        GENESIS,
        DAILY,
        REFERRAL
    }
    
    struct UserClaim {
        bool claimStatus;
        uint256 buffer;
    }
    
    function currentEpoch() external view returns (uint256);
    function cycleStartTimestamp() external view returns (uint256);
    function userBuffer(address user) external view returns (uint256);
    function userClaimStatus(address user, uint256 epochID) external view returns (UserClaim memory);
    function userGenesisClaimStatus(address user) external view returns (bool);
    
    function start(uint256 startTimestamp) external;
    function stop() external;
    function claimBuffer() external;
    function claimReward() external;
    
    event RewardClaimed(address user, RewardType rewardType, uint256 amount);
    event ReferralRewardBuffered(address from, address to, uint256 amount, bool bufferSafe);
}
PreviousRewards contractNextExamples

Last updated 3 months ago