import axios from "axios"; import { splitSignature } from "ethers/lib/utils"; import { BackendApi } from "./backend/api"; import { Web3Provider } from "./web3/web3.provider"; import { isSmartWallet } from "./helpers/ethers"; import { isValidUrl } from "./helpers/validity"; import { getDomain, getSignedDataStruct } from "./helpers/message"; import { InvalidUrlError } from "./errors"; export class ClientLibrary { private _backendApi: BackendApi; /** * Construct the Client Library instance. Optionally * pass the backend URL to initialize directly. * @param newBackendUrl */ constructor(newBackendUrl?: string) { if (newBackendUrl) { this.initialize(newBackendUrl); } } /** * Initialize the web3Provider by providing the URL * to the backend. * @param newBackendUrl * @throws InvalidUrlError */ public initialize(newBackendUrl: string) { if (isValidUrl(newBackendUrl)) { this._backendApi = new BackendApi(axios.create({ baseURL: newBackendUrl })); } else { throw new InvalidUrlError(newBackendUrl); } } /** * Authenticate the user by asking them to sign * a message. The web3Provider argument is used * to sign the authentication message. * This returns a JWT token which should be used * for subsequent calls. * @param account * @param web3Provider * @returns JWT Token */ public async authenticateUser(account: string, web3Provider: Web3Provider): Promise { const isSmartWalletAccount = isSmartWallet(web3Provider); const nonce = await this._backendApi.generateNonce(account); const AuthSignature: Array<{ name: string; type: string; }> = [{ name: "value", type: "string" }]; const domain = getDomain(web3Provider.provider.network.chainId); const messageData = getSignedDataStruct(AuthSignature, domain, nonce); const signatureLike = await web3Provider.provider.signTypedData_v4(account, messageData); const signature = await splitSignature(signatureLike); return await this._backendApi.verifySignature( account, isSmartWalletAccount, domain, {AuthSignature}, signature ); } /** * This handles the sequence of interactions to * complete the Commit action (with backend and * with contracts via the contracts SDK library). * @param web3Provider * @param voucherSetId * @param jwt * @returns Success status of commit */ public commitToBuy(web3Provider: any, voucherSetId: string, jwt: any): string {return ""} // TODO implement }