Skip to content

Commit 39a2b94

Browse files
committed
New APIs: Near, Social, Storage; Fixed issue with where the webpack was sending a message first and making the app to freeze; README.md Update.
1 parent f847bf8 commit 39a2b94

File tree

11 files changed

+585
-26
lines changed

11 files changed

+585
-26
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ yarn-error.log*
33
node_modules
44
dist
55
temp
6+
notas.txt
67

78
# build
9+
/api
810
/components
911
/hooks
1012
/auth

README.md

Lines changed: 176 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,35 @@ npm install near-social-bridge
2525
yarn add near-social-bridge
2626
```
2727

28-
## Table of contents
28+
## Quick Guide
29+
30+
Here's a quick guide to you get to know how to use Near Social Bridge with basic stuff.
2931

3032
- [Setup](#setup)
33+
- [BOS API](#bos-api)
34+
- [Near API](#near-api)
35+
- [Social API](#social-api)
36+
- [Storage API](#storage-api)
37+
- [Requests](#requests)
38+
- [Simple Request](#simple-request)
39+
- [Handling the requests inside the Widget](#handling-the-requests-inside-the-widget)
40+
- [Using request handler Utils - Widget side](#using-request-handler-utils-widget-side)
41+
- [Persist Storage](#persist-storage)
42+
- [Hooks](#hooks)
43+
- [useAuth](#useauth)
44+
- [useSyncContentHeight](#usesynccontentheight)
45+
- [Preparing a new Widget](#preparing-a-new-widget)
46+
- [Testing the Application Inside the Widget](#testing-the-application-inside-the-widget)
47+
48+
## Complete Guide
49+
50+
Here's a complete guide where you can go over all features provided by Near Social Bridge.
51+
52+
- [Setup](#setup)
53+
- [BOS API](#bos-api)
54+
- [Near API](#near-api)
55+
- [Social API](#social-api)
56+
- [Storage API](#storage-api)
3157
- [Requests](#requests)
3258
- [Simple Request](#simple-request)
3359
- [Create Requests Mocks](#create-requests-mocks)
@@ -95,6 +121,137 @@ const App = () => {
95121
}
96122
```
97123

124+
## BOS API
125+
126+
We've incorporated some APIs to allow your app to interact with different blockchains, websites, and store data in a decentralized way. These features are basically mirroring the [BOS API](https://docs.near.org/bos/api/home) features.
127+
128+
There is a deployed `Hello World` smart contract in the NEAR network at `nearsocialexamples.near` that we're going to use. The contract exposes two methods:
129+
130+
- `set_greeting(message: string): void`, which accepts a message and stores it in the contract state.
131+
- `get_greeting(): string` which returns the stored greeting.
132+
133+
### Near API
134+
135+
A convenient API to interact with the NEAR blockchain. [Complete Docs Here](https://docs.near.org/bos/api/near).
136+
137+
**Near.view**
138+
139+
This will conduct a call to a smart contract that will get a stored message onchain.
140+
141+
```ts
142+
import { Near } from 'near-social-bridge/api'
143+
144+
// Contract
145+
const CONTRACT_ID = 'nearsocialexamples.near'
146+
147+
Near.view<string>(CONTRACT_ID, 'get_greeting').then((response) => console.log(response))
148+
// {message: "The most recent stored greeting message"}
149+
```
150+
151+
**Near.call**
152+
153+
This will conduct a call to a smart contract that will store a message onchain.
154+
155+
```ts
156+
import { Near } from 'near-social-bridge/api'
157+
158+
// Contract
159+
const CONTRACT_ID = 'nearsocialexamples.near'
160+
161+
// Set data
162+
Near.call<{ message: string }>(CONTRACT_ID, 'set_greeting', { message: greeting })
163+
```
164+
165+
### Social API
166+
167+
A convenient API to get data from the SocialDB contract. [Complete Docs Here](https://docs.near.org/bos/api/social).
168+
169+
**Social.get**
170+
171+
```ts
172+
import { Social } from 'near-social-bridge/api'
173+
174+
Social.get('wendersonpires.testnet/widget/*').then((response) => console.log(res))
175+
// {HelloWorld: '...', Chat: '...', ChatV2: '...'}
176+
```
177+
178+
**Social.getr**
179+
180+
```ts
181+
Social.getr('wendersonpires.testnet/profile').then((response) => console.log(res))
182+
// {name: 'Wenderson Pires'}
183+
```
184+
185+
**Social.index**
186+
187+
```ts
188+
Social.index('widget-chatv2-dev', 'room', {
189+
limit: 1000,
190+
order: 'desc',
191+
}).then((response) => console.log(res))
192+
// [{accountId: 'xyz', blockHeight: 99, value: 'xyz'}, {...}, {...}, {...}]
193+
```
194+
195+
**Social.set**
196+
197+
```ts
198+
const data = { experimental: { test: 'test' } }
199+
Social.set(data).then((response) => console.log(res))
200+
// If Success: {wendersonpires.testnet: {experimental: {...}}}
201+
// If Canceled: {error: 'the action was canceled'}
202+
```
203+
204+
**Social.keys**
205+
206+
```ts
207+
Social.keys('wendersonpires.testnet/experimental').then((response) => console.log(res))
208+
// {wendersonpires.testnet: {experimental: {...}}}
209+
```
210+
211+
### Storage API
212+
213+
`Storage` object to store data for components that is persistent across refreshes. [Complete Docs Here](https://docs.near.org/bos/api/storage).
214+
215+
**Storage.set**
216+
217+
`Storage.set(key, value)` - sets the public value for a given key under the current widget. The value will be public, so other widgets can read it.
218+
219+
```ts
220+
import { Storage } from 'near-social-bridge/api'
221+
222+
Storage.set('my-storage-key', JSON.stringify({ age: 33, name: 'Wendz' })).then((response) => console.log(response))
223+
// {ok: true}
224+
```
225+
226+
**Storage.get**
227+
228+
`Storage.get(key, widgetSrc?)` - returns the public value for a given key under the given widgetSrc or the current component if `widgetSrc` is omitted. Can only read public values.
229+
230+
```ts
231+
Storage.get('my-storage-key').then((response) => console.log(response))
232+
// {"age":33,"name":"Wendz"}
233+
```
234+
235+
**Storage.privateSet**
236+
237+
`Storage.privateSet(key, value)` - sets the private value for a given key under the current component. The value is private, only the current component can read it.
238+
239+
```ts
240+
Storage.privateSet('my-private-key', JSON.stringify({ age: 18, name: 'Wendz Private' })).then((response) =>
241+
console.log(response)
242+
)
243+
// {ok: true}
244+
```
245+
246+
**Storage.privateGet**
247+
248+
`Storage.privateGet(key)` - returns the private value for a given key under the current component.
249+
250+
```ts
251+
Storage.privateGet('my-private-key').then((response) => console.log(response))
252+
// {"age":18,"name":"Wendz Private"}
253+
```
254+
98255
## Requests
99256

100257
You can make requests to the Widget and each request must be handled appropriately by the Widget. You can also mock your requests so that they work locally while you are developing the application. All mocks will be automatically disabled when the app is running inside the Widget.
@@ -342,7 +499,7 @@ const Profile: React.FC<ProfileScreenProps> = ({ navigation, route }) => {
342499

343500
## Session Storage
344501

345-
This feature stores data for one session. While testing inside a Widget, data is lost when the browser tab is reloaded or closed. You will have access to methods like `setItem`, `getItem`, `removeItem`, `clear` and `keys`. Data is automatically synchronized between the React App and the Widget.
502+
This feature stores data for components that is persistent across refreshes. You will have access to methods like `setItem`, `getItem`, `removeItem`, `clear` and `keys`. Data is automatically synchronized between the React App and the BOS Component.
346503

347504
```ts
348505
import { sessionStorage } from 'near-social-bridge'
@@ -381,7 +538,7 @@ export const store = init<RootModel>({
381538

382539
### useNearSocialBridge
383540

384-
Allow to get message from Widget and send messages to Widget:
541+
Allow to get message from BOS Component and send messages to BOS Component:
385542

386543
```tsx
387544
import { useNearSocialBridge } from 'near-social-bridge'
@@ -390,16 +547,16 @@ const MyComponent = () => {
390547
const { onGetMessage, postMessage } = useNearSocialBridge()
391548

392549
useEffect(() => {
393-
// Receives a message from Widget
550+
// Receives a message from BOS Component
394551
onGetMessage((message: any) => {
395-
console.log('Got message from Widget:', message)
552+
console.log('Got message from BOS Component:', message)
396553
})
397554

398555
return () => onGetMessage(null)
399556
}, [])
400557

401558
const sendMessageToWidget = () => {
402-
// Sends a message to Widget
559+
// Sends a message to BOS Component
403560
postMessage('My awesome message! :D')
404561
}
405562

@@ -409,14 +566,14 @@ const MyComponent = () => {
409566

410567
### useInitialPayload
411568

412-
Returns the initial payload sent by the Widget:
569+
Returns the initial payload sent by the BOS Component:
413570

414571
```ts
415572
import { useInitialPayload } from 'near-social-bridge'
416573

417574
const MyComponent = () => {
418575
const initialPayload = useInitialPayload()
419-
console.log(initialPayload) // initial payload sent by the Widget
576+
console.log(initialPayload) // initial payload sent by the BOS Component
420577
// ...
421578
}
422579
```
@@ -469,15 +626,15 @@ const MyComponent = () => {
469626

470627
### useWidgetView
471628

472-
Provides access to methods and props which can affect the Widget View:
629+
Provides access to methods and props which can affect the BOS Component View:
473630

474631
```ts
475632
import { useWidgetView } from 'near-social-bridge'
476633

477634
const MyComponent = () => {
478635
const widgetView = useWidgetView()
479636

480-
// Set the widget view height to 700px
637+
// Set the BOS Component view height to 700px
481638
widgetView.setHeight(700)
482639
}
483640
```
@@ -552,7 +709,7 @@ useEffect(() => {
552709

553710
### overrideLocalStorage
554711

555-
This is a feature that overrides the `window.localStorage` with the Widget's `Storage`, so that, you can keep using `window.localStorage` but the Widget's `Storage` is going to be the source of data.
712+
This is a feature that overrides the `window.localStorage` with the BOS Component's `Storage`, so that, you can keep using `window.localStorage` but the BOS Component's `Storage` is going to be the source of data.
556713

557714
**If using CSR:**
558715

@@ -562,7 +719,7 @@ import { overrideLocalStorage } from 'near-social-bridge/utils'
562719
// using `sessionStorage` under the hood
563720
overrideLocalStorage()
564721

565-
// The Widget won't break
722+
// The BOS Component won't break
566723
localStorage.setItem('name', 'Wenderson')
567724
localStorage.getItem('name') // "Wenderson"
568725
```
@@ -605,9 +762,9 @@ const MyComponent2 = () => {
605762
}
606763
```
607764

608-
## Preparing a new Widget
765+
## Preparing a new BOS Component
609766

610-
Create a new Widget, copy [the content of file **widget-setup.js**](./widget-setup.js) and paste it inside your new Widget. Then set its initial props as you wish:
767+
Create a new BOS Component, copy [the content of file **widget-setup.js**](./widget-setup.js) and paste it inside your new BOS Component. Then set its initial props as you wish:
611768

612769
```js
613770
/**
@@ -647,7 +804,7 @@ const getAccountIdHandler = (request, response) => {
647804
response(request).send({ accountId })
648805
}
649806

650-
// NearSocialBridgeCore widget is the core that makes all the "magic" happens
807+
// NearSocialBridgeCore BOS Component is the core that makes all the "magic" happens
651808
// use `wendersonpires.testnet/widget/NearSocialBridgeCore` as source if you want to use "testnet" environment
652809
return (
653810
<Widget
@@ -665,17 +822,17 @@ return (
665822

666823
**testnet:** Use `wendersonpires.testnet/widget/NearSocialBridgeCore` while creating your application using the testnet environment.
667824

668-
And that's basically it. Again, remember that once your application is running inside the Widget, if it is making requests, you must handle each one of them inside the Widget, otherwise the unhandled requests will fail.
825+
And that's basically it. Again, remember that once your application is running inside the BOS Component, if it is making requests, you must handle each one of them inside the BOS Component, otherwise the unhandled requests will fail.
669826

670827
## Good to know
671828

672829
### Server-Side Rendering
673830

674831
SSR is supported starting with version 1.3.0!
675832

676-
## Testing the Application Inside the Widget
833+
## Testing the Application Inside a Local Viewer
677834

678-
To test your app, you can install the [**NEAR Social Local Viewer CLI**](https://github.com/wpdas/near-social-local-viewer). It will allow you to execute and test your Widget locally using all the Discovery API resources without any problem.
835+
To test your app, you can install the [**NEAR Social Local Viewer CLI**](https://github.com/wpdas/near-social-local-viewer). It will allow you to execute and test your BOS Component locally using all the Discovery API resources without any problem.
679836

680837
1 - Install NEAR Social Local Viewer CLI using npm or yarn:
681838

@@ -705,6 +862,6 @@ npx init-viewer path/to/widgets/
705862
# e.g: npx init-viewer widgets/
706863
```
707864

708-
4 - Once your Widget is ready, you can deploy it to Near Social: <br/>
865+
4 - Once your BOS Component is ready, you can deploy it to Near Social: <br/>
709866
4.1 - You can deploy it by copying and pasting; <br/>
710867
4.2 - Or using [near-social CLI](https://github.com/FroVolod/near-social).

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
{
22
"name": "near-social-bridge",
3-
"version": "1.4.1",
3+
"version": "1.5.0",
44
"description": "This library allows you to create a common application using ReactJS and inject it in a controlled way into a Widget on Near Social. Therefore, the Widget talks to the React application and vice versa, making it possible to consume Discovery API resources within the React application.",
55
"main": "./dist/cjs/index.js",
66
"module": "./index.js",
77
"types": "./index.d.ts",
88
"scripts": {
9-
"clean": "rm -rf dist components hooks auth bridge navigation request services session-storage utils constants.d.ts constants.js index.d.ts index.js",
9+
"clean": "rm -rf dist components hooks auth bridge navigation api request services session-storage utils constants.d.ts constants.js index.d.ts index.js",
1010
"copy-files": "copyfiles -u 1 src/components/spinner.css src/bridge/contexts/fixBadIframe.css ./",
1111
"copy-files-cjs": "copyfiles -u 1 src/components/spinner.css src/bridge/contexts/fixBadIframe.css ./dist/cjs/",
1212
"build": "npm run clean; tsc -p tsconfig.prod.json; npm run copy-files; npm run copy-files-cjs; npm run build:cjs",

src/api/Near.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import request from '../request/request'
2+
import { API_KEYS } from '../constants'
3+
const ONE_DAY_MS = 86400000
4+
5+
/**
6+
* View
7+
* @param contractName Name of the smart contract
8+
* @param methodName Name of the method to call
9+
* @param args Arguments to pass to the method
10+
* @param blockId Block ID or finality of the transaction
11+
* @returns
12+
*/
13+
export const view = <R extends {}>(contractName: string, methodName: string, args?: {}, blockId?: string) =>
14+
request<R>(API_KEYS.API_NEAR_VIEW, { contractName, methodName, args, blockId })
15+
16+
/**
17+
* Call
18+
* @param contractName Name of the smart contract to call
19+
* @param methodName Name of the method to call on the smart contract
20+
* @param args Arguments to pass to the smart contract method as an object instance
21+
* @param gas Maximum amount of gas to be used for the transaction (default 300Tg)
22+
* @param deposit Amount of NEAR tokens to attach to the call as deposit (in yoctoNEAR units)
23+
*/
24+
export const call = <R extends {}>(
25+
contractName: string,
26+
methodName: string,
27+
args?: {},
28+
gas?: string | number,
29+
deposit?: string | number
30+
// Use ONE_DAY_MS to call this method only once. The dev should get the updated data after accepting the transaction
31+
) => request<R>(API_KEYS.API_NEAR_CALL, { contractName, methodName, args, gas, deposit }, { timeout: ONE_DAY_MS })

0 commit comments

Comments
 (0)