# Polkadot Hackathon - KILT Protocol integration The following is a showcase of what KILT can do and how we can integrate. The showcase will be using react, but it can be done on other libaries. During the demo, I will be writing the code in real-time and answering questions when I can. Along side the real-time demo is this document where if you get stuck or lost you can copy the code over. It will be fast paced and try to cram in as much goodness as possible. ## Demo For the following Demo you need to have Chromium/Firefox, Node js and Yarn installed. Lets start by creating a folder in the terminal. Hop into your fav terminal and lets get hacking! ```bash mkdir KILTHack && cd KILTHack ``` We will work from this folder. The demo will go through different aspects of KILT and will require the sporran wallet to show case some of the features. Now lets move on to getting the sporran wallet ## Sporran Wallet (5 min) The sporran wallet can hold KILT credentials and DIDs. The Sporran wallet, Credential API and DIDs are open-source so you can integrate the features shown here into other wallets. At the moment, only the Sporran has the functionatilty, therefore, required. We can download the [sporran wallet](https://github.com/BTE-Trusted-Entity/sporran-extension) following the quick start guide. I will copy over the code from the sporran wallet start guide here for easy. :::info 1. We recommend using a different browser or a different profile of your browser to avoid mixing up the real Sporran and the play coins Sporran 2. Have git, Node.js, and yarn installed 3. `git clone https://github.com/KILTprotocol/sporran-extension.git` 4. `cd sporran-extension` 5. `yarn install && yarn dev` 6. Start Chrome and navigate to chrome://extensions (or in Firefox about:debugging#/runtime/this-firefox) 7. Enable Developer Mode by clicking the toggle switch next to Developer mode (Chrome only) 8. Click the Load unpacked button and select the `sporran-extension/dist directory` (or in Firefox click Load Temporary Add-on... and select sporran-extension/dist/manifest.json) 9. Now you have the internal version of Sporran installed. DO NOT USE IT for real KILT identities/addresses/coins! Choose `wss://peregrine.kilt.io/parachain-public-ws` in ⚙ Settings > Custom Endpoint. Click the Sporran icon in the browser toolbar and follow the flow to create an Identity. Click the Receive link and copy the Identity address on the next screen. 10. Visit the [Faucet](https://faucet.peregrine.kilt.io/), paste the Identity address there, accept the Terms, and click Request Tokens to get some play KILT coins ::: :::warning **KNOWN ISSUES** - You must have `node >= v16.15.0` ```bash= nvm install 16.15.0 nvm use 16.15.0 ``` ::: Now you have the sporran and some tokens we can move on to the actual coding side of things. ## ViteJS [ViteJS](https://vitejs.dev/guide/) is a great tool to bootstrap your project. As for all browser based projects, you have to make sure that nodejs polyfills are in place to make the SDK work. If you start from any ViteJS template, you only have to make sure to install and enable the polyfills. Lets path back to the folder `KILTHack` Now we can create a new project here. Bootstrap using the template of your choice and install KILT + NodeJS polyfills: ```bash= yarn create vite KILT-Vitejs --template react-ts cd KILT-Vitejs yarn add @kiltprotocol/sdk-js@0.27.0 yarn add --dev @esbuild-plugins/node-globals-polyfill yarn add --dev @esbuild-plugins/node-modules-polyfill ``` Adjust the `vite.config.ts` file to activate the polyfills: ```javascript= import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill' import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill' import rollupNodePolyFill from 'rollup-plugin-node-polyfills' export default defineConfig({ plugins: [react()], optimizeDeps: { esbuildOptions: { plugins: [ NodeGlobalsPolyfillPlugin({ process: true, buffer: true }), NodeModulesPolyfillPlugin() ] } }, build: { rollupOptions: { plugins: [ rollupNodePolyFill() ] } } }) ``` After that you can initialize and use the SDK as usual. Inside Let try and query a DID's web3 name ```javascript= import { useState, useEffect } from 'react' import * as Kilt from '@kiltprotocol/sdk-js'; export function App() { const [did, setDid] = useState(''); useEffect(() => { const resolveWeb3Name = async () => { await Kilt.init({ address: "wss://spiritnet.kilt.io:443" }); let did = await Kilt.Did.Web3Names.queryDidForWeb3Name('john_doe'); setDid(did || 'unknown'); }; resolveWeb3Name(); }); return ( <div className="App"> john_doe is {did} </div> ) } ``` ### Accessing the extension Here is the code for getting extensions ```javascript= import { ApiWindow, InjectedWindowProvider } from '../types/types' const apiWindow = window as Window & ApiWindow function documentReadyPromise<T>(creator: () => T): Promise<T> { return new Promise((resolve): void => { if (document.readyState === 'complete') { resolve(creator()) } else { window.addEventListener('load', () => resolve(creator())) } }) } export function getExtensions(): Promise< Record<string, InjectedWindowProvider> > { apiWindow.kilt = apiWindow.kilt || {} return documentReadyPromise(() => apiWindow.kilt) } ``` types ```javascript= import { DidPublicKey, IEncryptedMessage, IIdentity, } from '@kiltprotocol/sdk-js' import { HexString } from '@polkadot/util/types' export type This = typeof globalThis export interface PubSubSession { listen: ( callback: (message: IEncryptedMessage) => Promise<void> ) => Promise<void> close: () => Promise<void> send: (message: IEncryptedMessage) => Promise<void> encryptionKeyId: DidPublicKey['id'] encryptedChallenge: string nonce: string } export interface InjectedWindowProvider { startSession: ( dAppName: string, dAppEncryptionKeyId: DidPublicKey['id'], challenge: string ) => Promise<PubSubSession> name: string version: string specVersion: '1.0' signWithDid: ( plaintext: string ) => Promise<{ signature: string; didKeyUri: DidPublicKey['id'] }> signExtrinsicWithDid: ( extrinsic: HexString, signer: IIdentity['address'] ) => Promise<{ signed: HexString; didKeyUri: DidPublicKey['id'] }> } export interface ApiWindow extends This { kilt: Record<string, InjectedWindowProvider> } ``` example of react hook ```javascript= import { useState, useEffect } from 'react' import { getExtensions } from '../src/getExtension/getExtension' import { InjectedWindowProvider } from '../src/types/types' export default function useSporran() { const [extensionEnabled, setExtensionEnabled] = useState(false) const [extensions, setExtensions] = useState<Record<string, InjectedWindowProvider>>() useEffect(() => { async function doEffect() { const allInjected = await getExtensions() if (allInjected) { setExtensions(allInjected) } setExtensionEnabled(true) } doEffect() }, []) useEffect(() => { if (extensionEnabled) { console.log(extensions) } }, [extensionEnabled, extensions]) return { extensions } } ``` Adding the hook to the main `App.tsx` ```javascript= import useSporran from './useSporran/useSporran' ... const { extensions } = useSporran() ... <button onClick={() => console.log(extensions)} /> ``` If we click on the button we can have a look at what is happening in the inspect tool of the browser. This is a setup to begin a project, unfortunately, due to the time constraint I will not be able to show you how to explicitly to begin the start session from scratch. KILT Protocol provides a complete setup using next js, which I can showcase and generate some test DIDs with credentials. ## KILT Distillery The next step is getting the [KILT Distillery](https://github.com/KILTprotocol/kilt-distillery-cli). The Distillery is a great way to start a project quickly within KILT. We will be looking at this project and the Distillerys code and seeing what is being done. ```bash sudo yarn global add git+https://github.com/KILTprotocol/kilt-distillery-cli ``` from the terminal ```bash kilt-distillery-cli ``` If you do not want to globally install the KILT Distillery CLI, you can clone the repo and build it directly. ### Starting the project We will choose the `create project from recipe` then you can select the `NextJS Credential Login`. Name the project `KILTDistillery`. During the setup you will be able to use the sporran generated mnemonic to create the verifier setup. It would be benefical to create the claimer setup, this should be done with a new mnemonic to make it easier to distinguish who the claimer and verifier are during the setup. Now, lets try out the project. You will need to path into the newly created project. Install and run the project `npm install & npm run dev` #### Creating a claim We will go through a claim process and create an attestation on the fly using the KILT Distillery setup. #### Start Session How does a session begin? What are the integrations between the server and the client. Lets look at the `http://localhost:3000/didConfiguration.json`