Skip to main content

Using the JavaScript SDK

In this tutorial, we will use the JavaScript SDK to write and read data from a database. Full SDK documentation can be found here.

Prerequisites

  • Ethereum Wallet Provider - You will need an Ethereum wallet provider in your browser to sign transactions. We recommend using MetaMask.
  • Kwil RPC - You will need the RPC endpoint of the Kwil network you are deploying to. This can be obtained by either running a node locally, or by obtaining an endpoint from Kwil Firebird.
  • A schema deployed to your database. We will use the schema in the dropdown below for this tutorial. To learn how to deploy a schema, see the Create a Table tutorial.
schema.sql
CREATE TABLE users (
id INT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
age INT NOT NULL,
address TEXT NOT NULL UNIQUE // user wallet addresses
);

CREATE ACTION create_user($username TEXT, $age INT) PUBLIC {
INSERT INTO users (id, username, age, address)
VALUES (uuid_generate_kwil(@txid), $username, $age, @caller);
};

CREATE ACTION get_user($name username) PUBLIC VIEW RETURNS (id UUID, username TEXT, age INT, address TEXT) {
for $row in SELECT * FROM users WHERE username = $name {
return $row.id, $row.username, $row.age, $row.address;
}
error('User not found');
};

Install the SDK

First, install the Kwil SDK and the ethers library:

npm install @kwilteam/kwil-js ethers

Initialization

In order to read and write data, we first must initialize the SDK, and get the database ID for our deployed database.

Kwil has different initialization logic for Web and NodeJS.

Kwil Class

The Kwil class is the main class for interacting with Kwil. It is used to initialize the SDK, and to execute procedures.

import { WebKwil } from '@kwilteam/kwil-js';

const kwil = new WebKwil({
kwilProvider: "YOUR_KWIL_URL",
chainId: "YOUR_CHAIN_ID",
});

Signer

The signer is used to sign transactions going to the Kwil network.

import { BrowserProvider } from 'ethers';
import { KwilSigner } from '@kwilteam/kwil-js';

async function getSigner() {
const provider = new BrowserProvider(window.ethereum);
const ethSigner = await provider.getSigner();
const ethAddress = await ethSigner.getAddress();
return new KwilSigner(ethSigner, ethAddress);
}

Write Data

To write data, we can use the execute() method to execute a procedure:

async function createUser(id, username, age) {
const kwilSigner = await getSigner();

const result = await kwil.execute({
name: "create_user",
inputs: [
{
$id: id,
$username: username,
$age: age
}
]
}, kwilSigner);

return result.data;
}

Read Data

To read data, we will call a view procedure on the schema. This will return the data that was written to the database.

async function getUser(username) {
const result = await kwil.call({
name: "get_user",
inputs: [
{
$username: username
}
]
});

return result.data;
}