Cookbook
Reward XP
Cookbook
Reward XP
A full code example that rewards a given user 10 XP for completing an activity in an application.
Javascript - ethers v5
// Import necessary libraries for HTTP requests and Ethereum blockchain interactions
import axios from "axios";
import { ethers } from "ethers";
// Asynchronously rewards experience points (XP) to a user for completing an activity
async function RewardXP() {
// Define the base URL for interacting with the OPENFORMAT API
const OPENFORMAT_API_BASE_URL = "https://api.openformat.tech";
// Specify the API key obtained from OPENFORMAT to authenticate requests
const OPENFORMAT_API_KEY = "";
// Setup the API client with headers for content type and authorization using the API key
const apiClient = axios.create({
baseURL: OPENFORMAT_API_BASE_URL,
headers: {
"Content-Type": "application/json",
"X-API-Key": OPENFORMAT_API_KEY,
},
});
// Your Ethereum private key associated with the account used to register the app on OPENFORMAT
const ETH_PRIVATE_KEY = "";
// Initialize a blockchain provider to interact with the Mumbai test network of the Polygon blockchain
const blockchainProvider = new ethers.providers.JsonRpcProvider(
"https://rpc-mumbai.maticvigil.com"
);
// Create a wallet instance with the private key and provider to enable signing transactions
const wallet = new ethers.Wallet(
ETH_PRIVATE_KEY,
blockchainProvider
);
// Define reward data including the app identifier, recipient address, and reward specifics
const APP_ID = ""; // Unique identifier for the app issuing the reward
const RECEIVER_ADDRESS = ""; // Ethereum address of the user receiving the XP reward
const rewardData = {
receiver: RECEIVER_ADDRESS,
amount: 10, // Amount of XP to reward
action_id: "complete_activity", // Identifier for the rewarded activity
app_id: APP_ID, // Application identifier for tracking
};
// Attempt to issue the XP reward through the OPENFORMAT API, handling the promise response or error
let transactionResponse = await apiClient
.post("/v1/reward/XP", rewardData)
.then((res) => res.data)
.catch((err) => console.error("Error issuing reward:", err));
// Sign the transaction for the reward with the wallet's private key
const signedTx = await wallet.signTransaction(
transactionResponse.unsignedTransaction
);
const executeData = { signed_transaction: signedTx };
// Execute the signed transaction through the OPENFORMAT API and handle the response or error
transactionResponse = await apiClient
.post("/v1/transactions/execute", executeData)
.then((res) => res.data)
.catch((err) =>
console.error("Error executing transaction:", err)
);
// Log the transaction hash for the executed transaction, linking to the PolygonScan explorer for the Mumbai network
console.log(
`Transaction executed, hash: https://mumbai.polygonscan.com/tx/${transactionResponse.transactionHash}`
);
}
// Execute the RewardXP function and catch any unhandled errors
RewardXP().catch((err) =>
console.error("Unhandled error in RewardXP:", err)
);