CoolFace
Apppublic

codenlighten/scrypt

sourceHugging Faceopenrailupdated 3y agoView on Hugging Face
0likes
how-to-integrate-dotwallet.md200 linesDownload Raw Back to root
1# How to integrate DotWallet2 3 4[DotWallet](https://www.dotWallet.com/en) is a lightweight wallet designed to help users easily and securely manage their digital assets. We will show how to integrate it with sCrypt-powered apps.5 6 7## OAuth 2.08 9OAuth 2.0 is an industry-standard authorization framework that enables third-party applications to access the resources of a user on a web service —- such as Facebook, Google, and Twitter -- without requiring the user to share their credentials directly with the application. It provides a secure and standardized way for users to grant limited access to their protected resources, such as their profile information or photos, to other applications. 10It works by introducing an authorization layer between the user, the application, and the web service hosting the user's data. Instead of sharing their username and password with the application, the user is redirected to the web service's authentication server. The user then authenticates themselves on the service, and upon successful authentication, the service issues an access token to the application. This access token represents the user's authorization to access specific resources.11 12If you are new to OAuth 2.0, check out thse helpful tutorials:13- [An Illustrated Guide to OAuth and OpenID Connect](https://developer.okta.com/blog/2019/10/21/illustrated-guide-to-oauth-and-oidc)14- [The Simplest Guide To OAuth 2.0](https://darutk.medium.com/the-simplest-guide-to-oauth-2-0-8c71bd9a15bb)15- [An Introduction to OAuth 2](https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2)16 17## DotWallet's user authorization18 19DotWallet uses OAuth 2.0 to allow third-party applications to safely access certain capabilities authorized by DotWallet users. More specifically, it uses Oauth2's authorization code grant type as the diagram shows. See [RFC6749](https://tools.ietf.org/html/rfc6749#section-4.1) for details. 20 21![](../../static/img/oauth2.png)22 23[Credit: Vihanga Liyanage](https://medium.com/@vihanga_liyanage/iam-for-dummies-oauth-2-grant-types-397197a26024)24 25Follow [these steps](https://developers.dotwallet.com/documents/en/#user-authorization) for a user authorization.26 271. Construct URI. 28 29    Example URI: `https://api.ddpurse.com/v1/oauth2/authorize?client_id=YOUR-CLIENT-ID&redirect_uri=http%3A%2F%2FYOUR-REDIRECT-URL&response_type=code&state=YOUR-STATE&scope=user.info`30 31    URL Parameters:32 33    | Parameter    | Description |34    | -------- | ------- |35    | client_id  | Developer’s dapp client_id    |36    | redirect_uri  | The redirect URL after authorization. Needs to be url_encoded   |37    | state    | It is recommended to use a random string of more than 32 bits (such as UUID). The state is used to verify the consistency of the request and callback. This can prevent csrf attacks.  |38    |response_type | Fill in the fixed value : `code` |39    |scope | Authorization scope. The list of permissions that the user agrees to authorize. These permissions are required for certain API endpoints. Needs to be url_encoded. Use spaces to separate multiple permissions. For a list of currently supported scope permissions, please check the scope list [here](https://developers.dotwallet.com/documents/en/#user-authorization)|40 412. Redirect the user to the URI constructed in step 142   43    After clicking the link, the user will be directed to the DotWallet authorization page. DotWallet will ask the user to log in, and then ask whether they agree to authorize the application for the listed permission scopes.44 453. Receive the `code` through the callback uri.46 47    After the user agrees to authorization in step 2, DotWallet will redirect the client to the `redirect_uri` specified by the application. The authorization code `code` and the provided `state` will be included in the query parameters.48 494. Exchange `code` for access_token. The access tokens are credentials used to access protected resources, which are issued by the authorization server.50   51:::warning52To avoid security issues, any request for using or obtaining `access_token` must be made from the backend server. Do not disclose your `access_token` and `client_secret`<sup>1</sup> on the client side.53:::54 55 56### DotWallet Developer Platform57 581. Before using DotWallet, you need to register and create an app on [DotWallet Developer Platform](https://developers.dotwallet.com/en).59 60![](../../static/img/dotwallet-create-dapp.png)61 622. After creating the app, you will receive an email containing `app_id` and `secret`.63 64 65![](../../static/img/dotwallet-mail.png)66 671. Next, you need to set [redirection URI](https://www.oauth.com/oauth2-servers/redirect-uris). Redirect URLs are a critical part of the OAuth flow. After a user successfully authorizes an application, the authorization server will redirect the user back to the application. For example, in the figure below `http://localhost:3000/callback/` is the redirection.68 69![](../../static/img/dotwallet-uris.png)70 71 72:::note73*Callback domain* in the form is the redirection URIs in OAuth. 74:::75 76## Example Implementation77 78 79Here is an example to integration DotWallet in [Nextjs](https://nextjs.org/), a popular React development framework.80 811. Construct URI. 82 83```ts84export default async function Home() {85    const client_id = process.env.CLIENT_ID;86    const redirect_uri = encodeURIComponent(process.env.REDIRECT_URI || '');87    const scope = encodeURIComponent("user.info autopay.bsv");88    const state = crypto.randomUUID();89    const loginUrl = `https://api.ddpurse.com/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}`;90    91    return (92      <main className="flex min-h-screen flex-col items-center justify-between p-24">93        <div className="m-4 p-4 bg-blue-200 font-bold rounded-lg">94          <a href={loginUrl}>DotWallet Login</a>95        </div>96      </main>97    );98}99```100 101<center>src/app/page.tsx</center>102 103 104If the user clicks the **DotWallet Login** link, the page will be redirected to the wallet authorization page.105 106![](../../static/img/dotwallet-auth.png)107 108 1092. After the user clicks **Agree to authorize** to log in, the authorization server redirects the user to the redirection URI. The following code receives the `code` through the callback uri,  exchanges the `code` for `access_token` and save it.110 111Inside the `app` directory, folders are used to [define routes](https://nextjs.org/docs/app/building-your-application/routing/defining-routes#creating-routes) in nextjs. we create `src/app/callback/route.ts` to handle the redirection request.112 113```ts114import { redirect, notFound } from 'next/navigation';115 116import token from "../token"117 118export async function GET(request: Request) {119  const { searchParams } = new URL(request.url);120  const code = searchParams.get('code');121 122  if (code) {123    // exchange the code for access_token124    const res = await fetch(`https://api.ddpurse.com/v1/oauth2/get_access_token`, {125      body: JSON.stringify({126        code,127        redirect_uri: process.env.REDIRECT_URI,128        grant_type: "authorization_code",129        client_secret: process.env.CLIENT_SECRET,130        client_id: process.env.CLIENT_ID,131      }),132      headers: {133        'Content-Type': 'application/json',134      },135      method: 'POST'136    });137    const { code: apiCode, data, msg } = await res.json();138 139    if (apiCode === 0) {140      const { access_token } = data;141      // save access_token142      token.access_token = access_token;143      // redirect to balance page.144      redirect('/balance');145    }146 147  }148 149  notFound();150}151```152 153<center>src/app/callback/route.ts</center>154 155 156### `DotWalletSigner`157 158sCrypt SDK provides `DotWalletSigner` for quick integration with DotWallet.159 160After redirect to the `/balance` page, we can create a `DotWalletSigner` with the OAuth access token, which is passed as the first argument.161 162 163```ts164import { DotwalletSigner, DefaultProvider } from "scrypt-ts";165import token from "../token";166 167async function getData() {168  const provider = new DefaultProvider();169  const signer = new DotwalletSigner(token.access_token, provider);170 171  const balance = await signer.getBalance();172 173  return { balance: balance.confirmed + balance.unconfirmed };174}175 176export default async function Balance() {177  const data = await getData();178 179  return (180    <main className="flex min-h-screen flex-col items-center justify-between p-24">181      <div className="m-4 p-4 bg-blue-200 font-bold rounded-lg">182        <label>balance</label> {data.balance}183      </div>184    </main>185  );186}187 188```189 190<center>src/app/balance/page.tsx</center>191 192After creating `DotWalletSigner` with access token, you can call all interfaces of `DotWalletSigner` as in other [signers](../how-to-deploy-and-call-a-contract/how-to-deploy-and-call-a-contract.md#signer).193For example, the example uses the signer to check user's balance.194 195Congrats! You have completed the integration of DotWallet. Full code is [here](https://github.com/zhfnjust/dotwallet-example).196 197------------------------198 199[1] `client_secret` is stored in the backend. It's used to exchange authorization code for access token.200