Demo: Token gate

Token gating is a popular way to grant or prevent access to some web property like a webpage, or chat room.

Here we define an address for the owner we want to check, and the target asset of SATOSHIDICE Next we get 20 of the unclaimed vaults owned by the defined address using the Get Vaults by ownerendpoint

Next we loop through each and using the Get Vault Balance endpoint check the contents of each vault for a SATOSHIDICE

NOTE: This is a simplistic example meant to illustrate how combining different endpoints you can make complex applications. Under real world conditions you would handle paginating through a user's entire collection of vaults.

EXTRA: You can also check for the existence of claimed vaults within a user's account.

const request = require('request');

const baseUrl = 'https://metadata.emblemvault.io';
const ownerAddress = '0x3B31925EeC78dA3CF15c4503604c13b0eEBC57e5';
const chainId = 1;
const vaultType = 'unclaimed';
const size = 20;
const start = 0;
const targetAsset = 'SATOSHIDICE'

const options = {
    url: `${baseUrl}/myvaults/${ownerAddress}?start=${start}&size=${size}`,
    headers: {
        'chainId': chainId,
        'VaultType': vaultType
    }
};

function getVaultBalance(vault, callback) {
    const balanceOptions = {
        url: `${baseUrl}/meta/${vault.tokenId}?live=true`
    };

    request(balanceOptions, (error, response, balanceBody) => {
        if (!error && response.statusCode === 200) {
            const balanceData = JSON.parse(balanceBody);
            for (const asset of balanceData.values) {
                if (asset.name === targetAsset) {
                    return callback(true);
                }
            }
            return callback(false);
        } else {
            console.log('Error:', error);
            console.log('Status Code:', response.statusCode);
            console.log('Body:', balanceBody);
            return callback(false);
        }
    });
}

function checkVaultsForAsset(vaults, index, callback) {
    if (index >= vaults.length) {
        return callback(false);
    }
    getVaultBalance(vaults[index], (hasAsset) => {
        if (hasAsset) {
            return callback(true);
        } else {
            checkVaultsForAsset(vaults, index + 1, callback);
        }
    });
}

request(options, (error, response, body) => {
    if (!error && response.statusCode === 200) {
        const parsedBody = JSON.parse(body);
        checkVaultsForAsset(parsedBody, 0, (hasTargetAsset) => {
            console.log(hasTargetAsset);
        });
    } else {
        console.log('Error:', error);
        console.log('Status Code:', response.statusCode);
        console.log('Body:', body);
    }
});

Last updated