Skip to content

Instantly share code, notes, and snippets.

@34r7h
Last active September 29, 2025 02:21
Show Gist options
  • Save 34r7h/5ee0966be331290997abb71faa809ff8 to your computer and use it in GitHub Desktop.
Save 34r7h/5ee0966be331290997abb71faa809ff8 to your computer and use it in GitHub Desktop.
// OG Token Payment Integration Script
// Add this to the custom script area in admin/advanced
(function () {
"use strict";
console.log("πŸš€ OG Token Payment Script: Starting...");
// Load Web3 from CDN if not available
if (typeof window.Web3 === "undefined") {
console.log("πŸ“¦ Loading Web3...");
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js";
script.onload = initOGTokenPayment;
document.head.appendChild(script);
} else {
initOGTokenPayment();
}
// 0G Network Configuration - Updated with correct chain ID
const OG_NETWORK = {
chainId: "0x40D9", // 16601 in hex - correct per 0G docs
chainName: "0G-Galileo-Testnet",
rpcUrls: ["https://evmrpc-testnet.0g.ai"],
blockExplorerUrls: ["https://chainscan-galileo.0g.ai"],
nativeCurrency: {
name: "OG",
symbol: "OG",
decimals: 18,
},
};
function initOGTokenPayment() {
console.log("πŸ”§ OG Token Payment Script: Initializing...");
// Use the exposed store from the custom script wrapper
const store = window.$store;
const state = window.$state;
const api = window.$api;
if (!store || !state) {
console.error("❌ Store not available");
return;
}
console.log("βœ… Store available:", store);
console.log("βœ… State available:", state);
// Add OG Token option to payment options
addOGTokenToPaymentOptions();
// Override transact action with complete OG Token flow
const originalTransact = store._actions.transact[0];
store._actions.transact[0] = async function (context, payload) {
console.log("πŸ’³ Transact called:", payload);
if (payload.payment && payload.payment["payment-type"] === "OG Token") {
console.log("πŸͺ™ Processing OG Token payment with complete flow...");
return await handleCompleteOGTokenPayment(payload);
}
return originalTransact.call(this, context, payload);
};
// Prevent form submission until payment is confirmed
const originalSubmitMethod = store._actions.submitMethod;
if (originalSubmitMethod) {
store._actions.submitMethod = async function(context, payload) {
console.log("πŸ“ Submit method called:", payload);
// Check if this is an order submission with OG Token payment
if (payload.type === 'order' && payload.data && payload.data.payment && payload.data.payment['payment-type'] === 'OG Token') {
if (!window.ogPaymentCompleted) {
console.log("🚫 Blocking order submission - OG Token payment must be completed first");
alert("Please complete the OG Token payment before submitting the order.");
return { success: false, error: "Payment not completed" };
} else {
console.log("βœ… OG Token payment completed, allowing order submission");
}
}
return originalSubmitMethod.call(this, context, payload);
};
}
// Add OG token icons
if (state.icons) {
state.icons.OG = "fas fa-coins";
state.icons.og = "fas fa-coins";
}
console.log("πŸŽ‰ OG Token Payment Script: Initialization complete!");
}
function addOGTokenToPaymentOptions() {
const state = window.$state;
// Check if checkout form exists
if (!state.models || !state.models.iform || !state.models.iform.checkout) {
console.log("πŸ“ Creating checkout form...");
// Initialize models structure
if (!state.models) state.models = {};
if (!state.models.iform) state.models.iform = {};
// Create checkout form
state.models.iform.checkout = {
name: "Checkout",
forms: [
{
name: "Shipping",
inputs: [
{
inputType: "input",
label: "name",
type: "text",
placeholder: "Your Name",
required: true,
},
{
inputType: "input",
label: "street",
type: "text",
placeholder: "Street address",
required: true,
},
{
inputType: "input",
label: "city",
type: "text",
placeholder: "City / town",
required: true,
},
{
inputType: "input",
label: "country",
type: "text",
placeholder: "Country",
required: true,
},
{
inputType: "input",
label: "zip",
type: "text",
placeholder: "Zip / postal code",
required: true,
},
],
},
{
name: "Payment",
inputs: [
{
inputType: "select",
label: "payment-type",
type: "text",
placeholder: "Select payment method",
options: [
{ name: "XMBL", icon: "fas fa-coins" },
{ name: "Credit", icon: "fas fa-credit-card" },
{ name: "PayPal", icon: "fab fa-paypal" },
{ name: "Crypto", icon: "fab fa-btc" },
{
name: "OG Token",
icon: "fas fa-coins",
content: `
<div style="text-align: left; padding: 12px; background: linear-gradient(135deg, #ff6b35, #f7931e); border-radius: 8px; color: white; margin: 4px 0;">
<div style="display: flex; align-items: center; margin-bottom: 8px;">
<i class="fas fa-coins" style="font-size: 24px; margin-right: 8px;"></i>
<strong style="font-size: 16px;">Pay with 0G Network</strong>
<button id="connect-wallet-btn-option" style="
background: rgba(255,255,255,0.2);
color: white;
border: 1px solid rgba(255,255,255,0.3);
padding: 6px 12px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
cursor: pointer;
margin-left: auto;
transition: all 0.3s ease;
" onclick="event.stopPropagation(); window.handleConnectWallet();">
<i class="fas fa-wallet"></i> Connect Wallet
</button>
</div>
<div style="font-size: 12px; opacity: 0.9; line-height: 1.4;">
<div style="margin-bottom: 3px;">βœ“ Connect your MetaMask wallet</div>
<div style="margin-bottom: 3px;">βœ“ Payment processed instantly</div>
<div style="margin-bottom: 3px;">βœ“ Order completed automatically</div>
<div>βœ“ Secure blockchain transaction</div>
</div>
</div>
`,
},
],
required: true,
},
// Credit card fields
{
inputType: "input",
label: "number",
type: "text",
placeholder: "Card Number",
if: ["payment-type", "Credit"],
},
{
inputType: "input",
label: "month",
type: "text",
placeholder: "MM",
if: ["payment-type", "Credit"],
},
{
inputType: "input",
label: "year",
type: "text",
placeholder: "YY",
if: ["payment-type", "Credit"],
},
{
inputType: "input",
label: "cvc",
type: "text",
placeholder: "CVC",
if: ["payment-type", "Credit"],
},
// Crypto fields
{
inputType: "select",
label: "currency",
type: "text",
options: ["bitcoin", "ethereum", "litecoin"],
if: ["payment-type", "Crypto"],
},
// OG Token wallet connection section - REPLACE INPUT WITH BUTTONS
{
inputType: "div",
label: "og-wallet",
if: ["payment-type", "OG Token"],
content: `
<div style="text-align: left; padding: 16px; background: #f8f9fa; border-radius: 8px; margin-top: 12px; border-left: 4px solid #ff6b35;">
<div style="font-size: 16px; font-weight: bold; color: #333; margin-bottom: 12px; display: flex; align-items: center;">
<i class="fas fa-wallet" style="color: #007bff; margin-right: 8px; font-size: 18px;"></i>
Connect Your Wallet
</div>
<div style="font-size: 14px; color: #666; line-height: 1.6; margin-bottom: 16px;">
To pay with OG tokens, you need to connect your MetaMask wallet first.
</div>
<button id="connect-wallet-btn" style="
background: linear-gradient(135deg, #ff6b35, #f7931e);
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
font-size: 14px;
font-weight: bold;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: all 0.3s ease;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.2)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.1)'">
<i class="fas fa-wallet"></i>
Connect MetaMask Wallet
</button>
<div style="font-size: 12px; color: #999; margin-top: 12px; padding: 8px; background: #e9ecef; border-radius: 4px; font-style: italic;">
<i class="fas fa-info-circle" style="margin-right: 4px;"></i>
<strong>Note:</strong> You need MetaMask installed.
<a href="https://metamask.io" target="_blank" style="color: #007bff; text-decoration: underline;">Download MetaMask</a>
</div>
</div>
`,
},
],
},
],
submit: {
method: "create",
type: "order",
},
};
} else {
console.log("πŸ”§ Modifying existing checkout form...");
// Add OG Token option to existing form
const paymentForm = state.models.iform.checkout.forms.find(
(f) => f.name === "Payment"
);
if (paymentForm) {
const paymentTypeInput = paymentForm.inputs.find(
(i) => i.label === "payment-type"
);
if (paymentTypeInput && paymentTypeInput.options) {
const hasOG = paymentTypeInput.options.some(
(opt) => opt.name === "OG Token"
);
if (!hasOG) {
paymentTypeInput.options.push({
name: "OG Token",
icon: "fas fa-coins",
content: `
<div style="text-align: left; padding: 12px; background: linear-gradient(135deg, #ff6b35, #f7931e); border-radius: 8px; color: white; margin: 4px 0;">
<div style="display: flex; align-items: center; margin-bottom: 8px;">
<i class="fas fa-coins" style="font-size: 24px; margin-right: 8px;"></i>
<strong style="font-size: 16px;">Pay with 0G Network</strong>
<button id="connect-wallet-btn-option" style="
background: rgba(255,255,255,0.2);
color: white;
border: 1px solid rgba(255,255,255,0.3);
padding: 6px 12px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
cursor: pointer;
margin-left: auto;
transition: all 0.3s ease;
" onclick="event.stopPropagation(); window.handleConnectWallet();">
<i class="fas fa-wallet"></i> Connect Wallet
</button>
</div>
<div style="font-size: 12px; opacity: 0.9; line-height: 1.4;">
<div style="margin-bottom: 3px;">βœ“ Connect your MetaMask wallet</div>
<div style="margin-bottom: 3px;">βœ“ Payment processed instantly</div>
<div style="margin-bottom: 3px;">βœ“ Order completed automatically</div>
<div>βœ“ Secure blockchain transaction</div>
</div>
</div>
`,
});
console.log("βœ… Added OG Token option");
}
}
// Add OG wallet field with connect button - REPLACE INPUT WITH BUTTONS
const hasOGWallet = paymentForm.inputs.some(
(i) => i.label === "og-wallet"
);
if (!hasOGWallet) {
paymentForm.inputs.push({
inputType: "div",
label: "og-wallet",
if: ["payment-type", "OG Token"],
content: `
<div style="text-align: left; padding: 16px; background: #f8f9fa; border-radius: 8px; margin-top: 12px; border-left: 4px solid #ff6b35;">
<div style="font-size: 16px; font-weight: bold; color: #333; margin-bottom: 12px; display: flex; align-items: center;">
<i class="fas fa-wallet" style="color: #007bff; margin-right: 8px; font-size: 18px;"></i>
Connect Your Wallet
</div>
<div style="font-size: 14px; color: #666; line-height: 1.6; margin-bottom: 16px;">
To pay with OG tokens, you need to connect your MetaMask wallet first.
</div>
<div id="wallet-address-display" style="display: none; font-size: 12px; color: #28a745; font-weight: bold; margin-bottom: 16px; padding: 8px; background: #d4edda; border-radius: 4px;">
<i class="fas fa-check-circle"></i> Connected: <span class="wallet-address"></span>
</div>
<button id="connect-wallet-btn" style="
background: linear-gradient(135deg, #ff6b35, #f7931e);
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
font-size: 14px;
font-weight: bold;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: all 0.3s ease;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.2)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.1)'">
<i class="fas fa-wallet"></i>
Connect MetaMask Wallet
</button>
<div style="font-size: 12px; color: #999; margin-top: 12px; padding: 8px; background: #e9ecef; border-radius: 4px; font-style: italic;">
<i class="fas fa-info-circle" style="margin-right: 4px;"></i>
<strong>Note:</strong> You need MetaMask installed.
<a href="https://metamask.io" target="_blank" style="color: #007bff; text-decoration: underline;">Download MetaMask</a>
</div>
</div>
`,
});
console.log("βœ… Added OG wallet field with connect button");
}
}
}
console.log("πŸ“‹ Final checkout form:", state.models.iform.checkout);
// Add event listener for connect wallet buttons
setTimeout(() => {
const connectBtn = document.getElementById("connect-wallet-btn");
const connectBtnOption = document.getElementById("connect-wallet-btn-option");
if (connectBtn) {
connectBtn.addEventListener("click", window.handleConnectWallet);
console.log("βœ… Connect wallet button event listener added");
}
if (connectBtnOption) {
connectBtnOption.addEventListener("click", (e) => {
e.stopPropagation();
window.handleConnectWallet();
});
console.log("βœ… Connect wallet option button event listener added");
}
}, 1000);
}
// Connect wallet handler - make it global
window.handleConnectWallet = async function handleConnectWallet() {
try {
console.log("πŸ”„ Connecting to MetaMask...");
// Check if MetaMask is installed
if (typeof window.ethereum === "undefined") {
throw new Error(
"MetaMask not found. Please install MetaMask to use OG Token payments."
);
}
// Request account access
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
const userAddress = accounts[0];
console.log("πŸ‘€ Connected to MetaMask:", userAddress);
// Switch to 0G Network
console.log("πŸ”„ Switching to 0G Network...");
await switchToOGNetwork();
// Update the wallet display
const walletDisplay = document.querySelector("#og-wallet");
if (walletDisplay) {
const addressSpan = walletDisplay.querySelector(".wallet-address");
if (addressSpan) {
addressSpan.textContent = `${userAddress.substring(
0,
6
)}...${userAddress.substring(userAddress.length - 4)}`;
}
}
// Update the connect buttons
const connectBtn = document.getElementById("connect-wallet-btn");
const connectBtnOption = document.getElementById("connect-wallet-btn-option");
if (connectBtn) {
connectBtn.innerHTML = '<i class="fas fa-check"></i> Wallet Connected';
connectBtn.style.background =
"linear-gradient(135deg, #28a745, #20c997)";
connectBtn.disabled = true;
}
if (connectBtnOption) {
connectBtnOption.innerHTML = '<i class="fas fa-check"></i> Connected';
connectBtnOption.style.background = "rgba(40, 167, 69, 0.3)";
connectBtnOption.style.borderColor = "rgba(40, 167, 69, 0.5)";
connectBtnOption.disabled = true;
}
// Enable the purchase button
const purchaseBtn = document.querySelector('button[type="submit"]');
if (purchaseBtn) {
purchaseBtn.disabled = false;
purchaseBtn.style.background =
"linear-gradient(135deg, #28a745, #20c997)";
console.log("βœ… Purchase button enabled");
}
console.log("βœ… Wallet connected successfully!");
} catch (error) {
console.error("❌ Wallet connection error:", error);
alert(`Wallet Connection Failed: ${error.message}
Please make sure MetaMask is installed and try again.`);
}
}
// Complete OG Token payment handler - handles entire flow
async function handleCompleteOGTokenPayment(payload) {
try {
// Check if MetaMask is installed
if (typeof window.ethereum === "undefined") {
throw new Error(
"MetaMask not found. Please install MetaMask to use OG Token payments."
);
}
console.log("πŸ”„ Starting complete OG Token payment flow...");
// Step 1: Connect to MetaMask
console.log("πŸ”„ Connecting to MetaMask...");
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
const userAddress = accounts[0];
console.log("πŸ‘€ Connected to MetaMask:", userAddress);
// Step 2: Switch to 0G Network
console.log("πŸ”„ Switching to 0G Network...");
await switchToOGNetwork();
// Step 3: Calculate payment amount
const usdAmount = parseFloat(payload.fullOrder.total);
const ogAmount = usdAmount / 10; // Adjust conversion rate as needed
const ogAmountWei = window.Web3.utils.toWei(ogAmount.toString(), "ether");
console.log(
`πŸ’° Payment amount: $${usdAmount} USD = ${ogAmount} OG tokens`
);
// Step 4: Create and send transaction
const transaction = {
from: userAddress,
to: "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d1b5", // Replace with your receiving address
value: ogAmountWei,
gas: "0x5208",
gasPrice: "0x3B9ACA00",
};
console.log("πŸš€ Sending transaction to MetaMask...");
const txHash = await window.ethereum.request({
method: "eth_sendTransaction",
params: [transaction],
});
console.log("βœ… Transaction sent:", txHash);
// Step 5: Wait for confirmation
console.log("⏳ Waiting for transaction confirmation...");
const receipt = await waitForTransactionConfirmation(txHash);
if (receipt && receipt.status === "0x1") {
console.log("βœ… Transaction confirmed!");
// Step 6: Update order with payment info
console.log("πŸ”„ Updating order with payment confirmation...");
await window.$api("update", {
type: "orders",
id: payload.orderId,
data: {
paid: "OG Token",
txHash: txHash,
ogAmount: ogAmount.toString(),
network: "0G Network",
status: "paid",
paymentConfirmed: true,
auctions: null, // Fix Firebase error by setting undefined field to null
},
});
// Step 7: Set payment completion flag
console.log("πŸ”„ Setting payment completion flag...");
window.ogPaymentCompleted = true;
// Step 8: Complete the order (run the original transact logic)
console.log("πŸ”„ Completing order...");
const originalTransact = window.$store._actions.transact[0];
const orderResult = await originalTransact.call(window.$store, payload);
// Step 8: Show success notification
console.log("πŸ”„ Sending success notification...");
await window.$api("notify", {
type: "billing",
message: `OG Token payment successful! Transaction: ${txHash.substring(
0,
10
)}...`,
to: [window.$state.auth.uid],
from: "OG Token Payment",
link: `/orders/${payload.orderId}`,
id: payload.orderId,
});
// Step 9: Show success message
console.log("βœ… Payment and order completed successfully!");
alert(`Payment Successful! πŸŽ‰
Transaction Hash: ${txHash}
Amount: ${ogAmount} OG tokens ($${usdAmount} USD)
Network: 0G Network
Your order has been processed and you will receive a confirmation email.`);
return {
success: true,
txHash: txHash,
ogAmount: ogAmount,
orderId: payload.orderId,
message: "Payment and order completed successfully",
};
} else {
throw new Error("Transaction failed or was rejected");
}
} catch (error) {
console.error("❌ Payment error:", error);
// Show error notification
await window.$api("notify", {
type: "billing",
message: `OG Token payment failed: ${error.message}`,
to: [window.$state.auth.uid],
from: "OG Token Payment",
link: `/orders/${payload.orderId}`,
id: payload.orderId,
});
// Show error alert
alert(`Payment Failed: ${error.message}
Please try again or contact support if the problem persists.`);
throw error;
}
}
// Global payment completion flag
window.ogPaymentCompleted = false;
// Network switching function
async function switchToOGNetwork() {
try {
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: OG_NETWORK.chainId }],
});
console.log("βœ… Switched to 0G Network");
} catch (switchError) {
if (switchError.code === 4902) {
console.log("βž• Adding 0G Network to MetaMask...");
try {
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [OG_NETWORK],
});
console.log("βœ… Added 0G Network to MetaMask");
} catch (addError) {
console.error("❌ Failed to add 0G Network:", addError);
throw new Error(
`Failed to add 0G Network to MetaMask: ${addError.message}. Please add the network manually.`
);
}
} else {
throw new Error(
`Failed to switch to 0G Network: ${switchError.message}`
);
}
}
}
// Transaction confirmation waiting
function waitForTransactionConfirmation(txHash) {
return new Promise((resolve, reject) => {
const checkConfirmation = async () => {
try {
const receipt = await window.ethereum.request({
method: "eth_getTransactionReceipt",
params: [txHash],
});
if (receipt) {
resolve(receipt);
} else {
setTimeout(checkConfirmation, 2000);
}
} catch (error) {
reject(error);
}
};
checkConfirmation();
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment