import type { ClientConfigType } from './types'; const API_URL = 'https://www.subscribewithnft.com/api'; const clientConfig: ClientConfigType = { id: null, secret: null, }; // set config function config({ id, secret }: ClientConfigType) { // TODO: validate; clientConfig.id = id; clientConfig.secret = secret; } function ethereum() { if (typeof window.ethereum === 'undefined') { return null; } return window.ethereum; } // get wallet async function getWallet() { const metamask = ethereum(); if (!metamask) { throw Error('No Metamask'); } const accounts = await metamask.request({ method: 'eth_requestAccounts' }); // TODO: validate if not connect message return String(accounts[0]); } // validate user has NFT async function hasNFT(address: string): Promise { const request = await fetch(`${API_URL}/has-nft`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Client-Id': clientConfig.id || '', 'Client-Secret': clientConfig.secret || '', }, body: JSON.stringify({ name: clientConfig.id, address, }), }); const response = await request.json(); return response; } // sign message async function signMessage(wallet: string) { const message = 'Verify this message'; const metamask = ethereum(); const signedMessage = await metamask.request({ method: 'personal_sign', params: [message, wallet], }); const { status } = signedMessage; if (status === 4001) { return null; } return String(signedMessage); } // validate sign message async function verifySignature(address: string, signature: string) { const request = await fetch(`${API_URL}/verify-signature`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Client-Id': clientConfig.id || '', 'Client-Secret': clientConfig.secret || '', }, body: JSON.stringify({ address, signature, }), }); const response = await request.json(); return response; } export default { config, getWallet, hasNFT, signMessage, verifySignature, };