@adamsoffer/3box 中文文档教程

发布于 4年前 浏览 9 项目主页 更新于 3年前

CircleCI 不和谐”></a> 
  <a href=npm npm Codecov 推特关注 Greenkeeper 徽章

< a href="#install">安装 | 用法 | 例子 | 数据标准 | API 文档

3box-js

这是一个允许您设置、获取和删除与以太坊帐户关联的私人和公共数据的库。 使用支持 web3 的浏览器的 dapp 可以使用它来存储身份数据、用户设置等。 只要用户可以访问所用以太坊帐户的私钥,就可以检索数据。 数据经过加密处理,任何未经用户授权的第三方均无法读取。 默认情况下,所有授权 dapps 访问的数据有一个共享空间,然后 dapps 必须请求明确同意访问的空间。

Getting Started

Installation

在您的 npm 项目中安装 3box:

$ npm install 3box

Usage

Import 3Box into your project

导入 3box 模块

const Box = require('3box')

在您的 html 代码中使用 dist 构建导入

<script type="text/javascript" src="../dist/3box.js"></script>

或选择从 unpkg CDN 加载远程副本。

<!-- The most recent version  -->
<script src="https://unpkg.com/3box/dist/3box.js"></script>
<!-- The most recent minified version  -->
<script src="https://unpkg.com/3box/dist/3box.min.js"></script>
<!-- Load specific versions by specifying the version as follows -->
<script src="https://unpkg.com/3box@<version>/dist/3box.js"></script>

Profiles API

Get the existing public profile of an address (or DID)

3Box 允许用户为其以太坊地址创建一个公共配置文件。 在你的 dapp 中,你可能有多个以太坊地址,你希望为这些地址显示名称、图像和其他基本社交元数据。 getProfile 方法允许您获取任何以太坊地址(如果有的话)的公开资料。 这是一个静态 方法,因此您可以直接从Box 对象调用它。

const profile = await Box.getProfile('0x12345abcde')
console.log(profile)

Update (get, set, remove) public and private profile data

3Box 允许应用程序创建、读取、更新和删除存储在用户 3Box 中的公共和私有数据。 要启用此功能,应用程序必须首先通过调用 auth 方法对用户的 3Box 进行身份验证。 此方法提示用户对您的 dapp 进行身份验证(登录)并返回带有 threeBox 实例的承诺。 您只能更新(设置、获取、删除)已通过身份验证并当前正在与您的 dapp 交互的用户的数据。 下面的 ethereumProvider 指的是您将从 web3.currentProviderwindow.ethereum 获得的对象。

1. Create a 3Box instance

要创建 3Box 会话,您可以调用 create 方法。 这将创建 Box 类的一个实例,该实例可用于以任何顺序打开线程和验证用户。 为了创建一个 3Box 会话,需要传递一个 provider。 这可以是 ethereum provider(来自 web3.currentProviderwindow.ethereum)或 3ID Provider(来自 IdentityWallet)。 现在建议使用 3ID Connect Provider,这是一个 3ID 提供程序,它包装了可用的 ethereum providers 并将管理/许可 3ID 密钥、身份验证和 iframe 中的区块链帐户链接。 这将很快成为默认设置,并将覆盖通过的 ethereum providers。 您可以按如下方式获取 3ID Connect Provider。

const provider = await Box.get3idConnectProvider()
const box = await Box.create(provider)

2. Authenticate user

调用 auth 方法将对用户进行身份验证。 如果您想将用户验证到一个或多个空间,您可以在此处指定。 如果您在创建 3Box 会话时使用了以太坊提供商,则需要将以太坊地址传递给 auth 方法。 如果用户没有现有的 3Box 帐户,此方法将在后台自动为他们创建一个。

const address = '0x12345abcde'
const spaces = ['myDapp']
await box.auth(spaces, { address })

3. Sync user's available 3Box data from the network

当您第一次验证 dapp 中的盒子时,所有数据可能尚未从网络同步。 因此,您应该等待数据完全同步。 为此,您只需等待 box.syncDone 承诺:

await box.syncDone

这将使您知道何时可以使用所有用户数据。 我们建议不要在此同步发生之前设置任何数据。 但是,在同步完成之前读取数据是很好的,也是值得鼓励的——只要记住在同步完成后检查更新! 请注意,box.syncDone 只能在用户通过身份验证后调用,如果仅调用 Box.create 方法则不可能。

如果您不想使用承诺,您可以使用 onSyncDone 方法添加回调。

3. Interact with 3Box profile data

您现在可以使用 box 实例对象与存储在用户配置文件中的公共和私人数据进行交互。 在公共和私有数据存储中,您都使用 key 来设置 value

// use the public profile
// get
const nickname = await box.public.get('name')
console.log(nickname)
// set
await box.public.set('name', 'oed')
// remove
await box.public.remove('name')

// use the private store
// get
const email = await box.private.get('email')
console.log(email)
// set
await box.private.set('email', 'oed@email.service')
// remove
await box.private.remove('email')
Set multiple fields at once:
const fields = ['name', 'website', 'employer']
const values = ['Jon Schwartz', 'openworklabs.com', 'Open Work Labs']

await box.public.setMultiple(fields, values)

const privateFields = ['age', 'coinBalance']
const privateValues = ['xxx', 'yyy']

await box.private.setMultiple(privateFields, privateValues)
Open a thread

创建 3Box 会话后,您可以打开一个线程来查看其中的数据。 这可以在您对用户进行身份验证之前完成(他们需要在线程中发帖)。 打开线程时,需要提供审核选项。 您可以传递 firstModerator,第一个主持人的 3ID(或以太坊地址),以及一个指示它是否是成员线程的 members 布尔值。

const thread = await box.openThread('myDapp', 'myThread', { firstModerator: 'did:3:bafy...', members: true })

打开一个线程后,您可以调用 getPosts() 方法来检索帖子。

Spaces API (Storage)

Open a space

空间是用户 3Box 的命名部分。 每个空间都有一个公共商店和一个私人商店,对于您打开的每个空间,用户必须明确同意才能查看该空间。 这意味着,如果您的 dapp 使用其他 dapp 未使用的空间,则只有您的 dapp 可以更新数据并读取该特定空间的私有存储。 要打开一个名为 narwhal 的空间,您只需

const space = await box.openSpace('narwhal')

Sync user's available space data from the network

await space.syncDone

Get, set, and remove space data

调用 空间的完成方式与与 box.publicbox.private 的交互方式相同(参见此处). 例如:

const config = await space.private.get('dapp-config')

Threads API (Messaging)

Add public and confidential message threads to your app

线程是一种共享数据存储,通过允许一个或多个用户按顺序发布消息,实现用户之间的去中心化通信。 此功能非常适合向您的应用程序添加评论、聊天、消息传递、提要和流媒体功能。 线程保存在一个空间中,加入线程的用户(具有相同的名称、空间、审核配置和访问配置)将能够在该线程中进行通信。

如需完整详细的规范,请查看文档

Viewing a Public Thread

您可以在不打开空间的情况下获取公共线程中的所有帖子。 这对于允许您网站的访问者查看其他用户发表的评论非常有用。 这是通过调用 Box 对象的 getThread 方法实现的。 线程可以通过其所有配置选项或地址来引用。

const posts = await Box.getThread(spaceName, threadName, firstModerator, membersThread)
console.log(posts)

也可以在不打开空间的情况下查看线程,或者通过对从 openThread 返回的线程对象调用 getPosts() 方法进行身份验证(请参阅上面的打开线程部分)。

const posts = await Box.getThreadByAddress(threadAddress)
console.log(posts)

但是,如果应用程序想要向线程添加交互性,例如允许用户在线程中发帖或关注线程中的更新,则需要打开它们的空间以启用其他功能。 机密线程也是如此,这需要您进行身份验证才能访问以查看机密线程中的帖子。

Interacting with a Thread

1.a Creating a Public Thread

要创建和加入公共线程,您只需加入线程即可。 这将隐式使用当前用户为 firstModeratormembers 为 false 的审核选项。

const thread = await space.joinThread('myThread')

线程也可以在加入时获得审核选项。 您可以传递 firstModerator、第一个主持人的 3ID 和一个指示它是否是成员线程的 members 布尔值。 版主可以添加其他版主、添加成员以及删除话题中的任何帖子。 会员可以在仅限会员的主题中发帖。

const thread = await space.joinThread('myThread', { firstModerator: 'some3ID', members: true })
1.b Creating a Confidential Thread

创建并加入机密线程。

const thread = await space.createConfidentialThread('myConfThread')

在创建时,您可能希望添加其他成员,以便他们可以读取消息并将消息写入线程,如下所示。

2. Joining a Thread

现有的公共或机密线程可以通过其地址加入。 机密线程最好通过其地址引用。

const thread = await space.joinThreadByAddress('/orbitdb/zdpuAp5QpBKR4BBVTvqe3KXVcNgo4z8Rkp9C5eK38iuEZj3jq/3box.thread.testSpace.testThread')

虽然可以通过地址或通过传递已知配置(与上述相同)加入公共线程。

const publicThread = await space.joinThread('myThread', { firstModerator: 'some3ID', members: true })

线程加入后可以找到如下地址。

const threadAddress = thread.address
3. Posting to a thread

这允许用户向线程添加消息。 消息的作者将是用户的 3Box DID。 当用户在线程中发帖时,他们会自动订阅该线程,并将其保存在应用程序使用的空间中,关键字为 thread-threadName

await thread.post('hello world')
4. Getting all posts in a thread

这允许应用程序获取线程中的帖子。

const posts = await thread.getPosts()
console.log(posts)
5. Listening for updates in thread

这允许应用程序侦听线程中的新帖子,并在发生时执行操作,例如将新消息添加到应用程序的 UI。

thread.onUpdate(myCallbackFunction)
6. Handling moderation and capabilities

添加主持人并列出所有现有主持人

await thread.addModerator('some3ID')

const mods = await thread.listModerators()

添加成员并列出所有现有成员,如果成员仅线程

await thread.addMember('some3ID')

const members = await thread.listMembers()

监听何时添加了主持人或成员。

thread.onNewCapabilities(myCallbackFunction)

Example Application

您可以通过查看 /example 文件夹中的文件来快速运行某些代码并与之交互。 您使用以下命令运行该示例:

$ npm ci
$ npm run example:start

这将在 http://localhost:3000/ 运行一个简单的服务器,该服务器为静态 example/index.html 文件提供服务。 这使它可以轻松地与元掩码交互。 您可以编辑 example/index.html 文件来尝试不同的代码。

Build

Optimize build for read-only 3Box API

如果您只想从 3Box 的配置文件 API 获取配置文件数据,您可以通过仅导入那些函数或特定于 API 的 dist 文件来进行优化。 由于这包括最小的依赖项,因此文件大小约为 80kb,而完整构建的文件大小为 4+mb。

const { profileGraphQL, getProfile, getProfiles, getVerifiedAccounts } = require('3box/lib/api')
<script src="https://unpkg.com/3box/dist/3box.api.min.js"></script>

Resolving build size issues and out of memory errors

某些平台、工具或配置导致构建过程抛出内存不足错误。 这是我们库的大小(加上依赖项)和您构建的特定配置的组合。 它可能是在依赖项上运行的工具之类的东西,而不仅仅是你的源代码或依赖项被递归解析。 无论如何,您都可以尝试通过添加以下环境变量来构建库,以增加节点进程的内存。

NODE_OPTIONS=--max_old_space_size=4096 npm run build

Data Standards

Dapp 可以存储仅与他们的 dapp 相关的用户数据。 然而,我们鼓励 dapps 在它们之间共享数据以获得更丰富的 web3 体验。 因此,我们创建了Key Conventions 以便促进这一点。 请随时对此文件进行 PR,以向社区解释您如何使用 3Box!

Validate claims

使用 idUtils 模块验证声明。 看 did-jwt 库了解更多详情。

const { idUtils } = require('3box')

const claim = 'eyJ0eX...'
idUtils.verifyClaim(claim)
  .then(valid => console.info('details:', valid)
  .catch(err => console.error('claim verification failed:', err)

API Documentation

Box ⇐ BoxApi

种类:全局类
扩展BoxApi

new Box()

请使用openBox< /strong> 方法来实例化一个 3Box

box.public

Kind: Box
Properties

Name Type Description
public KeyValueStore access the profile store of the users 3Box

box.private

KindBox
Properties

Name Type Description
private KeyValueStore access the private store of the users 3Box

box.verified

KindBox
Properties

Name Type Description
verified Verified check and create verifications

box.spaces

KindBox
Properties

Name Type Description
spaces Object an object containing all open spaces indexed by their name.

box.syncDone

KindBox
Properties

Name Type Description
syncDone Promise A promise that is resolved when the box is synced

box.DID

KindBox
Properties

Name Type Description
DID String the DID of the user

box.auth(spaces, opts)

验证用户

Kind: Box 的实例方法

Param Type Description
spaces Array.&lt;String&gt; A list of spaces to authenticate (optional)
opts Object Optional parameters
opts.address String An ethereum address
opts.consentCallback function A function that will be called when the user has consented to opening the box

box.openSpace(name, opts) ⇒ Space

在用户3Box中打开给定名字的空间

Kind: 盒子
返回Space - 给定空间名称的 Space 实例

Param Type Description
name String The name of the space
opts Object Optional parameters
opts.consentCallback function A function that will be called when the user has consented to opening the box
opts.onSyncDone function A function that will be called when the space has finished syncing with the pinning node

< /a>

box.openThread(space, name, opts) ⇒ Thread

打开一个线程。 使用它开始接收更新

KindBox
的实例方法 返回Thread - 加入线程的线程类实例

Param Type Description
space String The name of the space for this thread
name String The name of the thread
opts Object Optional parameters
opts.firstModerator String DID of first moderator of a thread, by default, user is first moderator
opts.members Boolean join a members only thread, which only members can post in, defaults to open thread
opts.noAutoSub Boolean Disable auto subscription to the thread when posting to it (default false)
opts.ghost Boolean Enable ephemeral messaging via Ghost Thread
opts.ghostBacklogLimit Number The number of posts to maintain in the ghost backlog
opts.ghostFilters Array.&lt;function()&gt; Array of functions for filtering messages

box.onSyncDone(syncDone) ⇒ Promise

设置盒子完全同步时调用一次的回调函数。

KindBox
的实例方法 返回Promise - 当框被同步时实现的承诺

Param Type Description
syncDone function The function that will be called

创建链接以太坊地址的证明到用户的 3Box 帐户。 如果给出证明,它将被简单地添加到根存储中。

KindBox

Param Type Description
[link] Object Optional link object with type or proof
[link.proof] Object Proof object, should follow spec

box.removeAddressLink(address)

的实例方法移除给定地址链接,成功则返回true

Kind: Box

Param Type Description
address String address that is linked

的实例方法/a>

box.isAddressLinked([query])

检查是否有证明将外部帐户链接到用户的 3Box 帐户。 如果没有给定参数并且存在任何链接,则返回 true

KindBox

Param Type Description
[query] Object Optional object with address and/or type.
[query.type] String Does the given type of link exist
[query.address] String Is the given adressed linked

box.listAddressLinks() ⇒ Array

列出与此 3Box 关联的地址链接

Kind: Box
的实例方法> 返回Array - 链接对象数组

box.logout()

关闭 3box 实例并清除本地缓存。 如果你这样称呼, 用户需要签署同意消息才能下次登录 你叫 openBox。

KindBox
的实例方法

Box.idUtils

验证 & 的模块 验证声明

KindBox

idUtils.verifyClaim ⇒ Object

验证声明并返回其内容。 有关详细信息,请参阅 https://github.com/uport-project/did-jwt/。

种类idUtils
的静态属性 返回对象 - 经过验证的声明

Param Type Description
claim String
opts Object Optional parameters
opts.audience string The DID of the JWT's audience

idUtils.isSupportedDID(did) ⇒ \* | boolean

检查字符串是否为 muport

种类idUtils
的静态方法 返回\* | boolean - did 是否为受支持的 did

Param Type Description
did String A string containing a user did

idUtils.isClaim(claim, opts) ⇒ Promise.&lt;boolean&gt;

检查字符串是否为有效声明

Kind: idUtils
的静态方法 返回Promise.&lt;boolean&gt; - 参数是否为实际声明

Param Type Description
claim String
opts Object Optional parameters
opts.audience string The DID of the audience of the JWT

Box.create(provider, opts) ⇒ Box

创建一个3Box

Kind 的实例:Box
的静态方法 返回Box - 3Box 会话实例

Param Type Description
provider provider A 3ID provider, or ethereum provider
opts Object Optional parameters
opts.pinningNode String A string with an ipfs multi-address to a 3box pinning node
opts.ipfs Object A js-ipfs ipfs object
opts.addressServer String URL of the Address Server

Box.get3idConnectProvider() ⇒ 3IDProvider

返回和 3ID Connect Provider 来管理密钥、身份验证和帐户链接。 将来成为默认值。

KindBox
的静态方法 返回3IDProvider - 解析为 3ID Connect Provider 的 Promise

Box.openBox(address, provider, opts) ⇒ Box

打开与给定地址关联的 3Box

KindBox
返回Box - 给定地址的 3Box 实例

Param Type Description
address String An ethereum address
provider provider An ethereum or 3ID provider
opts Object Optional parameters
opts.consentCallback function A function that will be called when the user has consented to opening the box
opts.pinningNode String A string with an ipfs multi-address to a 3box pinning node
opts.ipfs Object A js-ipfs ipfs object
opts.addressServer String URL of the Address Server
opts.contentSignature String A signature, provided by a client of 3box using the private keys associated with the given address, of the 3box consent message

Box.isLoggedIn(address) ⇒ Boolean

检查给定地址是否在

Kind 中登录:Box
的静态方法 返回Boolean - 如果用户登录则为真

Param Type Description
address String An ethereum address

Box.getIPFS() ⇒ IPFS

在不调用 openBox 的情况下实例化 3Box 使用的 ipfs。

KindBox
的静态方法 返回IPFS - ipfs 实例

BoxApi

Kind: global class

BoxApi.listSpaces(address, opts) ⇒ Object

获取用户拥有的所有空间的名称

Kind : BoxApi
的静态方法 返回: Object - 一个所有空格都是字符串的数组

Param Type Description
address String An ethereum address
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getSpace(address, name, opts) ⇒ Object

获取给定地址空间中的公共数据具有给定名称

KindBoxApi
的静态方法 返回对象 - 带有公共空间数据的 json 对象

Param Type Description
address String An ethereum address
name String A space name
opts Object Optional parameters
opts.blocklist function A function that takes an address and returns true if the user has been blocked
opts.metadata String flag to retrieve metadata
opts.profileServer String URL of Profile API server

BoxApi.getThread(space, name, firstModerator, members, opts) ⇒ Array.&lt;Object&gt;

获取所有发布到线程的帖子。

种类BoxApi
的静态方法 返回Array.&lt;Object&gt; - 帖子数组

Param Type Description
space String The name of the space the thread is in
name String The name of the thread
firstModerator String The DID (or ethereum address) of the first moderator
members Boolean True if only members are allowed to post
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getThreadByAddress(address, opts) ⇒ Array.&lt;Object&gt;

获取所有帖子做成一个线程。

种类BoxApi
的静态方法 返回Array.&lt;Object&gt; - 一个帖子数组

Param Type Description
address String The orbitdb-address of the thread
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getConfig(address, opts) ⇒ Array.&lt;Object&gt;

获取a的配置users 3Box

Kind: BoxApi
的静态方法 返回Array.&lt;Object&gt; - 帖子数组

Param Type Description
address String The ethereum address
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getProfile(address, opts) ⇒ Object

获取的公开资料给定的地址

KindBoxApi
的静态方法 返回对象 - 具有给定地址配置文件的 json 对象

Param Type Description
address String An ethereum address
opts Object Optional parameters
opts.blocklist function A function that takes an address and returns true if the user has been blocked
opts.metadata String flag to retrieve metadata
opts.profileServer String URL of Profile API server

BoxApi.getProfiles(address, opts) ⇒ Object

获取给定的公共配置文件列表地址。 这依赖于 3Box 配置文件 API。

种类BoxApi
的静态方法 返回对象 - 一个 json 对象,每个键都有一个地址和值配置文件

Param Type Description
address Array An array of ethereum addresses
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.profileGraphQL(query, opts) ⇒ Object

GraphQL for 3Box profile API

< strong>种类:BoxApi
的静态方法 返回对象 - 一个 json 对象,每个键都有一个地址和值配置文件

Param Type Description
query Object A graphQL query object.
opts Object Optional parameters
opts.graphqlServer String URL of graphQL 3Box profile service

BoxApi.getVerifiedAccounts(profile) ⇒ Object

验证社交帐户的证明存在于配置文件中。

种类BoxApi
的静态方法 返回对象 - 包含已验证帐户的对象

Param Type Description
profile Object A user profile object, received from the getProfile function

KeyValueStore

种类:全局类

new KeyValueStore()

请使用box.publicbox.private 获取该类的实例

keyValueStore.get(key, opts) ⇒ String | Object

获取给定键的值和可选的元数据

KindKeyValueStore 的实例方法br> 返回String | Object - 与键关联的值,如果没有这样的键则未定义

Param Type Description
key String the key
opts Object optional parameters
opts.metadata Boolean return both value and metadata

keyValueStore.getMetadata(key) ⇒ Metadata

获取给定键的元数据

Kind: KeyValueStore
的实例方法 返回Metadata - 键的元数据,如果没有这样的键则未定义

Param Type Description
key String the key

keyValueStore.set(key, value) ⇒ Boolean

为给定的键设置一个值

KindKeyValueStore
的实例方法 返回布尔值 - 如果成功则为真

Param Type Description
key String the key
value String the value

keyValueStore.setMultiple(keys, values) ⇒ Boolean

为多个键设置多个值

种类KeyValueStore
的实例方法 返回布尔值 - 如果成功则为真,否则则抛出错误

Param Type Description
keys Array.&lt;String&gt; the keys
values Array.&lt;String&gt; the values

keyValueStore.remove(key) ⇒ Boolean

删除给定键的值

种类KeyValueStore
的实例方法 返回Boolean - 如果成功则为真

Param Type Description
key String the key

keyValueStore.all(opts) ⇒ Array.&lt;(String\|{value: String, timestamp: Number})&gt;

获取所有值和可选的元数据

KindKeyValueStore
的实例方法 返回Array.<(String\|{value: String, timestamp: Number})&gt; - 值

Param Type Description
opts Object optional parameters
opts.metadata Boolean return both values and metadata

keyValueStore.log() ⇒ Array.&lt;Object&gt;

返回底层日志条目的数组。 根据他们的 Lamport 时钟以线性化顺序排列。 用于生成商店中所有操作的完整历史记录。

KindKeyValueStore
的实例方法 返回Array.&lt;Object&gt; - 有序日志条目对象数组
示例

const log = store.log
 const entry = log[0]
 console.log(entry)
 // { op: 'PUT', key: 'Name', value: 'Botbot', timeStamp: '1538575416068' }

User

表示用户的类。

Kind:全局类

user.DID

KindUser 的实例属性
Properties

Name Type Description
DID String the DID of the user

user.signClaim(payload, opts) ⇒ String

签署 JWT 声明

Kind 的实例方法用户
返回String - 签名的 JWT

Param Type Description
payload Object The payload to sign
opts Object Optional parameters

user.encrypt(message, opts, to) ⇒ Object

加密消息。 默认情况下对称加密消息 使用用户私钥。 如果使用 to 参数, 该消息将被非对称加密给收件人。

KindUser
的实例方法 返回对象 - 包含加密负载的对象

Param Type Description
message String The message to encrypt
opts Object Optional parameters
to String The receiver of the message, a DID or an ethereum address

user.decrypt(encryptedObject) ⇒ String

如果用户拥有正确的解密密钥,则解密消息它。

KindUser
的实例方法 返回String - 明文消息

Param Type Description
encryptedObject Object The encrypted message to decrypt (as encoded by the encrypt method

Space

种类:全局类

new Space()

请使用box.openSpace获取此类的实例

space.public

Kind: instance 空间
的属性 Properties

Name Type Description
public KeyValueStore access the profile store of the space

space.private

KindSpace
Properties

Name Type Description
private KeyValueStore access the private store of the space

space.syncDone

KindSpace
Properties

Name Type Description
syncDone Promise A promise that is resolved when the space data is synced

space.user

KindSpace
属性

Name Type Description
user User access the user object to encrypt data and sign claims

space.joinThread(name, opts) ⇒ Thread

加入一个线程。 使用它开始接收来自线程的更新,并在线程中发布

KindSpace
的实例方法 返回Thread - 已加入线程的线程类实例

Param Type Description
name String The name of the thread
opts Object Optional parameters
opts.firstModerator String DID of first moderator of a thread, by default, user is first moderator
opts.members Boolean join a members only thread, which only members can post in, defaults to open thread
opts.confidential Boolean create a confidential thread with true or join existing confidential thread with an encKeyId string
opts.noAutoSub Boolean Disable auto subscription to the thread when posting to it (default false)
opts.ghost Boolean Enable ephemeral messaging via Ghost Thread
opts.ghostBacklogLimit Number The number of posts to maintain in the ghost backlog
opts.ghostFilters Array.&lt;function()&gt; Array of functions for filtering messages

space.createConfidentialThread(name) ⇒ Thread

创建机密线程

种类Space
的实例方法 返回Thread - 已创建线程的线程类实例

Param Type Description
name String The name of the thread

space.joinThreadByAddress(address, opts) ⇒ Thread

通过完整的线程地址加入线程。 使用它开始接收来自线程的更新,并在线程中发布

KindSpace
的实例方法 返回Thread - 加入线程的线程类实例

Param Type Description
address String The full address of the thread
opts Object Optional parameters
opts.noAutoSub Boolean Disable auto subscription to the thread when posting to it (default false)

space.subscribeThread(address, config)

订阅给定的线程,如果尚未订阅

种类Space 的实例方法

Param Type Description
address String The address of the thread
config Object configuration and thread meta data
opts.name String Name of thread
opts.firstModerator String DID of the first moderator
opts.members String Boolean string, true if a members only thread

space.unsubscribeThread(address)

如果已订阅,则取消订阅给定的线程

种类Space 的实例方法/a>

Param Type Description
address String The address of the thread

space.subscribedThreads() ⇒ Array.&lt;Objects&gt;

获取该空间所有订阅的线程列表

Kind的实例方法空间
返回Array.&lt;Objects&gt; - 作为{address, firstModerator, members, name}
的线程对象列表

Thread

Kind:全局类

new Thread()

请使用space.joinThread获取此类的实例

thread.post(message) ⇒ String

向线程发送消息

种类Thread<的实例方法/代码>
返回String - 新帖子的postId

Param Type Description
message Object The message

thread.addModerator(id)

给这个帖子添加版主,抛出错误是用户可以不添加主持人

Kind: Thread

Param Type Description
id String Moderator Id

thread.listModerators() ⇒ Array.&lt;String&gt;

列出版主

种类Thread
的实例方法 返回Array.&lt;String&gt; - 主持人 DID 数组

thread.addMember(id)

添加一个成员到这个线程,如果用户不能添加成员抛出,抛出不是成员线程

Kind: Thread

Param Type Description
id String Member Id

thread.listMembers() ⇒ Array.&lt;String&gt;

列出成员,如果不是成员则抛出线程

Kind: 实例方法线程
返回Array.&lt;String&gt; - 成员 DID 数组

thread.deletePost(id)

删除帖子

种类Thread的实例方法

Param Type Description
id String Moderator Id

< a name="Thread+getPosts">

thread.getPosts(opts) ⇒ Array.&lt;Object&gt;

根据选项返回一组帖子。 如果传递 gt、gte、lt 或 lte 时未找到散列, 迭代器将返回所有项目(尊重限制和反向)。

KindThread
的实例方法 返回Array.&lt;Object&gt; - 如果成功则返回true

Param Type Description
opts Object Optional parameters
opts.gt String Greater than, takes an postId
opts.gte String Greater than or equal to, takes an postId
opts.lt String Less than, takes an postId
opts.lte String Less than or equal to, takes an postId
opts.limit Integer Limiting the number of entries in result, defaults to -1 (no limit)
opts.reverse Boolean If set to true will result in reversing the result

thread.onUpdate(updateFn)

注册一个要调用的函数新更新后 已从网络或本地收到。

KindThread的实例方法

Param Type Description
updateFn function The function that will get called

thread.onNewCapabilities(updateFn)

注册一个函数被称为每一个新的 添加到线程访问控制器的功能。 这包括在添加版主或成员时。 该函数接受一个参数,即 capabilities obj,或者 您可以再次调用 listModerator / listMembers。

KindThread

Param Type Description
updateFn function The function that will get called

Verified

Kind< 的实例方法/strong>: global class

new Verified()

请使用box.verified获取该类的实例

verified.DID() ⇒ String

返回用户的已验证 DID

Kind: Verified
的实例方法 返回String - 用户的 DID

verified.github() ⇒ Object

验证用户是否拥有有效的github账号 否则抛出错误。

种类Verified
的实例方法 返回对象 - 包含用户名和证明的对象

verified.addGithub(gistUrl) ⇒ Object

向用户配置文件添加 github 验证 如果验证失败则抛出错误。

种类Verified
的实例方法 返回对象 - 包含用户名和证明的对象

Param Type Description
gistUrl Object URL of the proof

verified.twitter() ⇒ Object

验证用户是否拥有有效的 Twitter 帐户 否则抛出错误。

种类Verified
的实例方法 返回对象 - 包含用户名、证明和验证者的对象

verified.addTwitter(claim) ⇒ Object

向用户个人资料添加推特验证 如果验证失败则抛出错误。

种类Verified
的实例方法 返回对象 - 包含用户名、证明和验证器的对象

Param Type Description
claim String A did-JWT claim ownership of a twitter username

verified.email() ⇒ Object

验证用户是否拥有经过验证的电子邮件帐户 否则抛出错误。

种类Verified
的实例方法 返回对象 - 包含用户名、证明和验证者的对象

verified.addEmail(claim) ⇒ Object

向用户个人资料添加电子邮件验证 如果验证失败则抛出错误。

种类Verified
的实例方法 返回对象 - 包含用户名、证明和验证者的对象

Param Type Description
claim String A did-JWT claim ownership of an email username

CircleCI Discord npm npm Codecov Twitter Follow Greenkeeper badge

Install | Usage | Example | Data Standards | API Docs

3box-js

This is a library which allows you to set, get, and remove private and public data associated with an ethereum account. It can be used to store identity data, user settings, etc. by dapps that use a web3 enabled browser. The data will be retrievable as long as the user has access to the private key for the used ethereum account. The data is encrypted and can not be read by any third party that the user hasn't authorized. There is one shared space for data which all authorized dapps access by default, then there are spaces which dapps have to request explicit consent to access.

Getting Started

Installation

Install 3box in your npm project:

$ npm install 3box

Usage

Import 3Box into your project

Import the 3box module

const Box = require('3box')

Import using the dist build in your html code

<script type="text/javascript" src="../dist/3box.js"></script>

Or optionally by loading remote copy from unpkg CDN.

<!-- The most recent version  -->
<script src="https://unpkg.com/3box/dist/3box.js"></script>
<!-- The most recent minified version  -->
<script src="https://unpkg.com/3box/dist/3box.min.js"></script>
<!-- Load specific versions by specifying the version as follows -->
<script src="https://unpkg.com/3box@<version>/dist/3box.js"></script>

Profiles API

Get the existing public profile of an address (or DID)

3Box allows users to create a public profile for their Ethereum address. In your dapp you might have multiple ethereum addresses that you would like to display a name, image, and other basic social metadata for. The getProfile method allows you to fetch the public profile of any ethereum address (if it has one). This is a static method so you can call it directly from the Box object.

const profile = await Box.getProfile('0x12345abcde')
console.log(profile)

Update (get, set, remove) public and private profile data

3Box allows applications to create, read, update, and delete public and private data stored in a user's 3Box. To enable this functionality, applications must first authenticate the user's 3Box by calling the auth method. This method prompts the user to authenticate (sign-in) to your dapp and returns a promise with a threeBox instance. You can only update (set, get, remove) data for users that have authenticated to and are currently interacting with your dapp. Below ethereumProvider refers to the object that you would get from web3.currentProvider, or window.ethereum.

1. Create a 3Box instance

To create a 3Box session you call the create method. This creates an instance of the Box class which can be used to openThreads and authenticate the user in any order. In order to create a 3Box session a provider needs to be passed. This can be an ethereum provider (from web3.currentProvider, or window.ethereum) or a 3ID Provider (from IdentityWallet). It is now suggested to use the 3ID Connect Provider, which is a 3ID provider that wraps available ethereum providers and will manage/permission 3ID keys, authentication and blockchain account links inside an iframe. This will become the default soon and will overide passed ethereum providers. You can get the 3ID Connect Provider as follows.

const provider = await Box.get3idConnectProvider()
const box = await Box.create(provider)

2. Authenticate user

Calling the auth method will authenticate the user. If you want to authenticate the user to one or multiple spaces you can specify this here. If when you created the 3Box session you used an ethereum provider you need to pass an ethereum address to the auth method. If the user does not have an existing 3Box account, this method will automatically create one for them in the background.

const address = '0x12345abcde'
const spaces = ['myDapp']
await box.auth(spaces, { address })

3. Sync user's available 3Box data from the network

When you first authenticate the box in your dapp all data might not be synced from the network yet. You should therefore wait for the data to be fully synced. To do this you can simply await the box.syncDone promise:

await box.syncDone

This will allow you to know when all the user's data is available to you. We advise against setting any data before this sync has happened. However, reading data before the sync is complete is fine and encouraged - just remember to check for updates once the sync is finished! Please note, box.syncDone can only be called once the user has been authenticated, it is not possible if only the Box.create method has been called.

If you prefer to not use promises you can add a callback using the onSyncDone method.

3. Interact with 3Box profile data

You can now use the box instance object to interact with public and private data stored in the user's profile. In both the public and the private data store you use a key to set a value.

// use the public profile
// get
const nickname = await box.public.get('name')
console.log(nickname)
// set
await box.public.set('name', 'oed')
// remove
await box.public.remove('name')

// use the private store
// get
const email = await box.private.get('email')
console.log(email)
// set
await box.private.set('email', 'oed@email.service')
// remove
await box.private.remove('email')
Set multiple fields at once:
const fields = ['name', 'website', 'employer']
const values = ['Jon Schwartz', 'openworklabs.com', 'Open Work Labs']

await box.public.setMultiple(fields, values)

const privateFields = ['age', 'coinBalance']
const privateValues = ['xxx', 'yyy']

await box.private.setMultiple(privateFields, privateValues)
Open a thread

Once you have created a 3Box session you can open a thread to view data in it. This can be done before you authenticate the user (required for them to post in the thread). When opening a thread the moderation options need to be given. You can pass firstModerator, a 3ID (or ethereum address) of the first moderator, and a members boolean which indicates if it is a members thread or not.

const thread = await box.openThread('myDapp', 'myThread', { firstModerator: 'did:3:bafy...', members: true })

Once a thread has been opened you can call the getPosts() method to retrive the posts.

Spaces API (Storage)

Open a space

A space is a named section of a users 3Box. Each space has both a public and a private store, and for every space you open the user has to grant explicit consent to view that space. This means that if your dapp uses a space that no other dapp uses, only your dapp is allowed to update the data and read the private store of that particular space. To open a space called narwhal you simply call:

const space = await box.openSpace('narwhal')

Sync user's available space data from the network

Similarly to how you need to wait for data to sync in a users main data storage, you may also do the same thing for a space:

await space.syncDone

Get, set, and remove space data

Interacting with data in a space is done in the same way as interacting with box.public and box.private (see here). For example:

const config = await space.private.get('dapp-config')

Threads API (Messaging)

Add public and confidential message threads to your app

Threads are a shared datastore that enable decentralized communication between users, by allowing one or more users to post messages in a sequence. This functionality is great for adding commenting, chat, messaging, feed, and stream features to your application. Threads are saved within a space and users that join a thread (with the same name, space, moderation configs, and access configs) will be able to communicate in that thread.

For the fully detailed spec, view the documentation.

Viewing a Public Thread

You can get all posts made in a public thread without opening a space. This is great for allowing visitors of your site view comments made by other users. This is achieved by calling the getThread method on the Box object. A thread can be referenced by all its configuration options or by its address.

const posts = await Box.getThread(spaceName, threadName, firstModerator, membersThread)
console.log(posts)

Threads can also be viewed without opening space, or authenticating by calling the getPosts() method on the thread object returned from openThread (see Open a thread section above).

const posts = await Box.getThreadByAddress(threadAddress)
console.log(posts)

However if applications want to add interactivity to the thread, such as allowing the user to post in a thread or follow updates in a thread, you will need to open their space to enable additional functionality. Same is true for a confidential thread, which requires you autheticate to get access to view the posts in a confidential thread.

Interacting with a Thread

1.a Creating a Public Thread

To create and join a public thread, you can simply join the thread. This will implicitly use the moderation options where the current user is the firstModerator and members is false.

const thread = await space.joinThread('myThread')

A thread can also be given the moderation options when joining. You can pass firstModerator, a 3ID of the first moderator, and a members boolean which indicates if it is a members thread or not. Moderators can add other moderators, add members, and delete any posts in the thread. Members can post in member only threads.

const thread = await space.joinThread('myThread', { firstModerator: 'some3ID', members: true })
1.b Creating a Confidential Thread

To create and join a confidential thread.

const thread = await space.createConfidentialThread('myConfThread')

At creation you will likely want to add other members so that they can read and write messages to the thread, as shown below.

2. Joining a Thread

An existing public or confidential thread can be joined by its address. Confidential threads are best referenced by their address.

const thread = await space.joinThreadByAddress('/orbitdb/zdpuAp5QpBKR4BBVTvqe3KXVcNgo4z8Rkp9C5eK38iuEZj3jq/3box.thread.testSpace.testThread')

While public threads can be joined by address or by passing known configs (same as above).

const publicThread = await space.joinThread('myThread', { firstModerator: 'some3ID', members: true })

An address of a thread can be found as follows once joined.

const threadAddress = thread.address
3. Posting to a thread

This allows the user to add a message to the thread. The author of the message will be the user's 3Box DID. When a user posts in a thread, they are automatically subscribed to the thread and it is saved in the space used by the application under the key thread-threadName.

await thread.post('hello world')
4. Getting all posts in a thread

This allows applications to get the posts in a thread.

const posts = await thread.getPosts()
console.log(posts)
5. Listening for updates in thread

This allows applications to listen for new posts in the thread, and perform an action when this occurs, such as adding the new message to the application's UI.

thread.onUpdate(myCallbackFunction)
6. Handling moderation and capabilities

Add a moderator and list all existing moderators

await thread.addModerator('some3ID')

const mods = await thread.listModerators()

Add a member and list all existing members, if a members only thread

await thread.addMember('some3ID')

const members = await thread.listMembers()

Listen for when there has been moderators or member added.

thread.onNewCapabilities(myCallbackFunction)

Example Application

You can quickly run and interact with some code by looking at the files in the /example folder. You run the example with the following commands:

$ npm ci
$ npm run example:start

This runs a simple server at http://localhost:3000/ that serves the static example/index.html file. This allows it easily interact with metamask. You can edit the example/index.html file to try differnt code.

Build

Optimize build for read-only 3Box API

If you only want to fetch profile data from 3Box's profile APIs you can optimize by importing only those functions or the API specific dist file. Since this includes minimal dependencies, file size is ~ 80kb vs 4+mb for the full build.

const { profileGraphQL, getProfile, getProfiles, getVerifiedAccounts } = require('3box/lib/api')
<script src="https://unpkg.com/3box/dist/3box.api.min.js"></script>

Resolving build size issues and out of memory errors

Some platforms, tooling, or configs have caused the build process to throw out of memory errors. This is a combination of the size of our library (plus dependencies) and the specific configs you have for your build. It could be things like tooling running on dependencies and not just your source or dependencies be recursively resolved. You can attempt to build the library anyways by adding the follow environment variable to increase memory for the node process.

NODE_OPTIONS=--max_old_space_size=4096 npm run build

Data Standards

Dapps can store data about users that relate to only their dapp. However we encurage dapps to share data between them for a richer web3 experience. Therefore we have created Key Conventions in order to facilitate this. Feel free to make a PR to this file to explain to the community how you use 3Box!

Validate claims

Use the idUtils module to validate claims. See the did-jwt library for more details.

const { idUtils } = require('3box')

const claim = 'eyJ0eX...'
idUtils.verifyClaim(claim)
  .then(valid => console.info('details:', valid)
  .catch(err => console.error('claim verification failed:', err)

API Documentation

Box ⇐ BoxApi

Kind: global class
Extends: BoxApi

new Box()

Please use the openBox method to instantiate a 3Box

box.public

Kind: instance property of Box
Properties

Name Type Description
public KeyValueStore access the profile store of the users 3Box

box.private

Kind: instance property of Box
Properties

Name Type Description
private KeyValueStore access the private store of the users 3Box

box.verified

Kind: instance property of Box
Properties

Name Type Description
verified Verified check and create verifications

box.spaces

Kind: instance property of Box
Properties

Name Type Description
spaces Object an object containing all open spaces indexed by their name.

box.syncDone

Kind: instance property of Box
Properties

Name Type Description
syncDone Promise A promise that is resolved when the box is synced

box.DID

Kind: instance property of Box
Properties

Name Type Description
DID String the DID of the user

box.auth(spaces, opts)

Authenticate the user

Kind: instance method of Box

Param Type Description
spaces Array.&lt;String&gt; A list of spaces to authenticate (optional)
opts Object Optional parameters
opts.address String An ethereum address
opts.consentCallback function A function that will be called when the user has consented to opening the box

box.openSpace(name, opts) ⇒ Space

Opens the space with the given name in the users 3Box

Kind: instance method of Box
Returns: Space - the Space instance for the given space name

Param Type Description
name String The name of the space
opts Object Optional parameters
opts.consentCallback function A function that will be called when the user has consented to opening the box
opts.onSyncDone function A function that will be called when the space has finished syncing with the pinning node

box.openThread(space, name, opts) ⇒ Thread

Open a thread. Use this to start receiving updates

Kind: instance method of Box
Returns: Thread - An instance of the thread class for the joined thread

Param Type Description
space String The name of the space for this thread
name String The name of the thread
opts Object Optional parameters
opts.firstModerator String DID of first moderator of a thread, by default, user is first moderator
opts.members Boolean join a members only thread, which only members can post in, defaults to open thread
opts.noAutoSub Boolean Disable auto subscription to the thread when posting to it (default false)
opts.ghost Boolean Enable ephemeral messaging via Ghost Thread
opts.ghostBacklogLimit Number The number of posts to maintain in the ghost backlog
opts.ghostFilters Array.&lt;function()&gt; Array of functions for filtering messages

box.onSyncDone(syncDone) ⇒ Promise

Sets the callback function that will be called once when the box is fully synced.

Kind: instance method of Box
Returns: Promise - A promise that is fulfilled when the box is syned

Param Type Description
syncDone function The function that will be called

Creates a proof that links an ethereum address to the 3Box account of the user. If given proof, it will simply be added to the root store.

Kind: instance method of Box

Param Type Description
[link] Object Optional link object with type or proof
[link.proof] Object Proof object, should follow spec

box.removeAddressLink(address)

Remove given address link, returns true if successful

Kind: instance method of Box

Param Type Description
address String address that is linked

box.isAddressLinked([query])

Checks if there is a proof that links an external account to the 3Box account of the user. If not params given and any link exists, returns true

Kind: instance method of Box

Param Type Description
[query] Object Optional object with address and/or type.
[query.type] String Does the given type of link exist
[query.address] String Is the given adressed linked

box.listAddressLinks() ⇒ Array

Lists address links associated with this 3Box

Kind: instance method of Box
Returns: Array - An array of link objects

box.logout()

Closes the 3box instance and clears local cache. If you call this, users will need to sign a consent message to log in the next time you call openBox.

Kind: instance method of Box

Box.idUtils

A module to verify & validate claims

Kind: static property of Box

idUtils.verifyClaim ⇒ Object

Verify a claim and return its content. See https://github.com/uport-project/did-jwt/ for more details.

Kind: static property of idUtils
Returns: Object - The validated claim

Param Type Description
claim String
opts Object Optional parameters
opts.audience string The DID of the JWT's audience

idUtils.isSupportedDID(did) ⇒ \* | boolean

Check whether a string is a muport did or not

Kind: static method of idUtils
Returns: \* | boolean - Whether the did is a supported did or not

Param Type Description
did String A string containing a user did

idUtils.isClaim(claim, opts) ⇒ Promise.&lt;boolean&gt;

Check whether a string is a valid claim or not

Kind: static method of idUtils
Returns: Promise.&lt;boolean&gt; - whether the parameter is an actual claim

Param Type Description
claim String
opts Object Optional parameters
opts.audience string The DID of the audience of the JWT

Box.create(provider, opts) ⇒ Box

Creates an instance of 3Box

Kind: static method of Box
Returns: Box - the 3Box session instance

Param Type Description
provider provider A 3ID provider, or ethereum provider
opts Object Optional parameters
opts.pinningNode String A string with an ipfs multi-address to a 3box pinning node
opts.ipfs Object A js-ipfs ipfs object
opts.addressServer String URL of the Address Server

Box.get3idConnectProvider() ⇒ 3IDProvider

Returns and 3ID Connect Provider to manage keys, authentication and account links. Becomes default in future.

Kind: static method of Box
Returns: 3IDProvider - Promise that resolves to a 3ID Connect Provider

Box.openBox(address, provider, opts) ⇒ Box

Opens the 3Box associated with the given address

Kind: static method of Box
Returns: Box - the 3Box instance for the given address

Param Type Description
address String An ethereum address
provider provider An ethereum or 3ID provider
opts Object Optional parameters
opts.consentCallback function A function that will be called when the user has consented to opening the box
opts.pinningNode String A string with an ipfs multi-address to a 3box pinning node
opts.ipfs Object A js-ipfs ipfs object
opts.addressServer String URL of the Address Server
opts.contentSignature String A signature, provided by a client of 3box using the private keys associated with the given address, of the 3box consent message

Box.isLoggedIn(address) ⇒ Boolean

Check if the given address is logged in

Kind: static method of Box
Returns: Boolean - true if the user is logged in

Param Type Description
address String An ethereum address

Box.getIPFS() ⇒ IPFS

Instanciate ipfs used by 3Box without calling openBox.

Kind: static method of Box
Returns: IPFS - the ipfs instance

BoxApi

Kind: global class

BoxApi.listSpaces(address, opts) ⇒ Object

Get the names of all spaces a user has

Kind: static method of BoxApi
Returns: Object - an array with all spaces as strings

Param Type Description
address String An ethereum address
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getSpace(address, name, opts) ⇒ Object

Get the public data in a space of a given address with the given name

Kind: static method of BoxApi
Returns: Object - a json object with the public space data

Param Type Description
address String An ethereum address
name String A space name
opts Object Optional parameters
opts.blocklist function A function that takes an address and returns true if the user has been blocked
opts.metadata String flag to retrieve metadata
opts.profileServer String URL of Profile API server

BoxApi.getThread(space, name, firstModerator, members, opts) ⇒ Array.&lt;Object&gt;

Get all posts that are made to a thread.

Kind: static method of BoxApi
Returns: Array.&lt;Object&gt; - An array of posts

Param Type Description
space String The name of the space the thread is in
name String The name of the thread
firstModerator String The DID (or ethereum address) of the first moderator
members Boolean True if only members are allowed to post
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getThreadByAddress(address, opts) ⇒ Array.&lt;Object&gt;

Get all posts that are made to a thread.

Kind: static method of BoxApi
Returns: Array.&lt;Object&gt; - An array of posts

Param Type Description
address String The orbitdb-address of the thread
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getConfig(address, opts) ⇒ Array.&lt;Object&gt;

Get the configuration of a users 3Box

Kind: static method of BoxApi
Returns: Array.&lt;Object&gt; - An array of posts

Param Type Description
address String The ethereum address
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.getProfile(address, opts) ⇒ Object

Get the public profile of a given address

Kind: static method of BoxApi
Returns: Object - a json object with the profile for the given address

Param Type Description
address String An ethereum address
opts Object Optional parameters
opts.blocklist function A function that takes an address and returns true if the user has been blocked
opts.metadata String flag to retrieve metadata
opts.profileServer String URL of Profile API server

BoxApi.getProfiles(address, opts) ⇒ Object

Get a list of public profiles for given addresses. This relies on 3Box profile API.

Kind: static method of BoxApi
Returns: Object - a json object with each key an address and value the profile

Param Type Description
address Array An array of ethereum addresses
opts Object Optional parameters
opts.profileServer String URL of Profile API server

BoxApi.profileGraphQL(query, opts) ⇒ Object

GraphQL for 3Box profile API

Kind: static method of BoxApi
Returns: Object - a json object with each key an address and value the profile

Param Type Description
query Object A graphQL query object.
opts Object Optional parameters
opts.graphqlServer String URL of graphQL 3Box profile service

BoxApi.getVerifiedAccounts(profile) ⇒ Object

Verifies the proofs of social accounts that is present in the profile.

Kind: static method of BoxApi
Returns: Object - An object containing the accounts that have been verified

Param Type Description
profile Object A user profile object, received from the getProfile function

KeyValueStore

Kind: global class

new KeyValueStore()

Please use box.public or box.private to get the instance of this class

keyValueStore.get(key, opts) ⇒ String | Object

Get the value and optionally metadata of the given key

Kind: instance method of KeyValueStore
Returns: String | Object - the value associated with the key, undefined if there's no such key

Param Type Description
key String the key
opts Object optional parameters
opts.metadata Boolean return both value and metadata

keyValueStore.getMetadata(key) ⇒ Metadata

Get metadata for for a given key

Kind: instance method of KeyValueStore
Returns: Metadata - Metadata for the key, undefined if there's no such key

Param Type Description
key String the key

keyValueStore.set(key, value) ⇒ Boolean

Set a value for the given key

Kind: instance method of KeyValueStore
Returns: Boolean - true if successful

Param Type Description
key String the key
value String the value

keyValueStore.setMultiple(keys, values) ⇒ Boolean

Set multiple values for multiple keys

Kind: instance method of KeyValueStore
Returns: Boolean - true if successful, throw error if not

Param Type Description
keys Array.&lt;String&gt; the keys
values Array.&lt;String&gt; the values

keyValueStore.remove(key) ⇒ Boolean

Remove the value for the given key

Kind: instance method of KeyValueStore
Returns: Boolean - true if successful

Param Type Description
key String the key

keyValueStore.all(opts) ⇒ Array.&lt;(String\|{value: String, timestamp: Number})&gt;

Get all values and optionally metadata

Kind: instance method of KeyValueStore
Returns: Array.&lt;(String\|{value: String, timestamp: Number})&gt; - the values

Param Type Description
opts Object optional parameters
opts.metadata Boolean return both values and metadata

keyValueStore.log() ⇒ Array.&lt;Object&gt;

Returns array of underlying log entries. In linearized order according to their Lamport clocks. Useful for generating a complete history of all operations on store.

Kind: instance method of KeyValueStore
Returns: Array.&lt;Object&gt; - Array of ordered log entry objects
Example

const log = store.log
 const entry = log[0]
 console.log(entry)
 // { op: 'PUT', key: 'Name', value: 'Botbot', timeStamp: '1538575416068' }

User

Class representing a user.

Kind: global class

user.DID

Kind: instance property of User
Properties

Name Type Description
DID String the DID of the user

user.signClaim(payload, opts) ⇒ String

Sign a JWT claim

Kind: instance method of User
Returns: String - The signed JWT

Param Type Description
payload Object The payload to sign
opts Object Optional parameters

user.encrypt(message, opts, to) ⇒ Object

Encrypt a message. By default encrypts messages symmetrically with the users private key. If the to parameter is used, the message will be asymmetrically encrypted to the recipient.

Kind: instance method of User
Returns: Object - An object containing the encrypted payload

Param Type Description
message String The message to encrypt
opts Object Optional parameters
to String The receiver of the message, a DID or an ethereum address

user.decrypt(encryptedObject) ⇒ String

Decrypts a message if the user owns the correct key to decrypt it.

Kind: instance method of User
Returns: String - The clear text message

Param Type Description
encryptedObject Object The encrypted message to decrypt (as encoded by the encrypt method

Space

Kind: global class

new Space()

Please use box.openSpace to get the instance of this class

space.public

Kind: instance property of Space
Properties

Name Type Description
public KeyValueStore access the profile store of the space

space.private

Kind: instance property of Space
Properties

Name Type Description
private KeyValueStore access the private store of the space

space.syncDone

Kind: instance property of Space
Properties

Name Type Description
syncDone Promise A promise that is resolved when the space data is synced

space.user

Kind: instance property of Space
Properties

Name Type Description
user User access the user object to encrypt data and sign claims

space.joinThread(name, opts) ⇒ Thread

Join a thread. Use this to start receiving updates from, and to post in threads

Kind: instance method of Space
Returns: Thread - An instance of the thread class for the joined thread

Param Type Description
name String The name of the thread
opts Object Optional parameters
opts.firstModerator String DID of first moderator of a thread, by default, user is first moderator
opts.members Boolean join a members only thread, which only members can post in, defaults to open thread
opts.confidential Boolean create a confidential thread with true or join existing confidential thread with an encKeyId string
opts.noAutoSub Boolean Disable auto subscription to the thread when posting to it (default false)
opts.ghost Boolean Enable ephemeral messaging via Ghost Thread
opts.ghostBacklogLimit Number The number of posts to maintain in the ghost backlog
opts.ghostFilters Array.&lt;function()&gt; Array of functions for filtering messages

space.createConfidentialThread(name) ⇒ Thread

Create a confidential thread

Kind: instance method of Space
Returns: Thread - An instance of the thread class for the created thread

Param Type Description
name String The name of the thread

space.joinThreadByAddress(address, opts) ⇒ Thread

Join a thread by full thread address. Use this to start receiving updates from, and to post in threads

Kind: instance method of Space
Returns: Thread - An instance of the thread class for the joined thread

Param Type Description
address String The full address of the thread
opts Object Optional parameters
opts.noAutoSub Boolean Disable auto subscription to the thread when posting to it (default false)

space.subscribeThread(address, config)

Subscribe to the given thread, if not already subscribed

Kind: instance method of Space

Param Type Description
address String The address of the thread
config Object configuration and thread meta data
opts.name String Name of thread
opts.firstModerator String DID of the first moderator
opts.members String Boolean string, true if a members only thread

space.unsubscribeThread(address)

Unsubscribe from the given thread, if subscribed

Kind: instance method of Space

Param Type Description
address String The address of the thread

space.subscribedThreads() ⇒ Array.&lt;Objects&gt;

Get a list of all the threads subscribed to in this space

Kind: instance method of Space
Returns: Array.&lt;Objects&gt; - A list of thread objects as { address, firstModerator, members, name}

Thread

Kind: global class

new Thread()

Please use space.joinThread to get the instance of this class

thread.post(message) ⇒ String

Post a message to the thread

Kind: instance method of Thread
Returns: String - The postId of the new post

Param Type Description
message Object The message

thread.addModerator(id)

Add a moderator to this thread, throws error is user can not add a moderator

Kind: instance method of Thread

Param Type Description
id String Moderator Id

thread.listModerators() ⇒ Array.&lt;String&gt;

List moderators

Kind: instance method of Thread
Returns: Array.&lt;String&gt; - Array of moderator DIDs

thread.addMember(id)

Add a member to this thread, throws if user can not add member, throw is not member thread

Kind: instance method of Thread

Param Type Description
id String Member Id

thread.listMembers() ⇒ Array.&lt;String&gt;

List members, throws if not member thread

Kind: instance method of Thread
Returns: Array.&lt;String&gt; - Array of member DIDs

thread.deletePost(id)

Delete post

Kind: instance method of Thread

Param Type Description
id String Moderator Id

thread.getPosts(opts) ⇒ Array.&lt;Object&gt;

Returns an array of posts, based on the options. If hash not found when passing gt, gte, lt, or lte, the iterator will return all items (respecting limit and reverse).

Kind: instance method of Thread
Returns: Array.&lt;Object&gt; - true if successful

Param Type Description
opts Object Optional parameters
opts.gt String Greater than, takes an postId
opts.gte String Greater than or equal to, takes an postId
opts.lt String Less than, takes an postId
opts.lte String Less than or equal to, takes an postId
opts.limit Integer Limiting the number of entries in result, defaults to -1 (no limit)
opts.reverse Boolean If set to true will result in reversing the result

thread.onUpdate(updateFn)

Register a function to be called after new updates have been received from the network or locally.

Kind: instance method of Thread

Param Type Description
updateFn function The function that will get called

thread.onNewCapabilities(updateFn)

Register a function to be called for every new capability that is added to the thread access controller. This inlcudes when a moderator or member is added. The function takes one parameter, which is the capabilities obj, or you can call listModerator / listMembers again instead.

Kind: instance method of Thread

Param Type Description
updateFn function The function that will get called

Verified

Kind: global class

new Verified()

Please use box.verified to get the instance of this class

verified.DID() ⇒ String

Returns the verified DID of the user

Kind: instance method of Verified
Returns: String - The DID of the user

verified.github() ⇒ Object

Verifies that the user has a valid github account Throws an error otherwise.

Kind: instance method of Verified
Returns: Object - Object containing username, and proof

verified.addGithub(gistUrl) ⇒ Object

Adds a github verification to the users profile Throws an error if the verification fails.

Kind: instance method of Verified
Returns: Object - Object containing username, and proof

Param Type Description
gistUrl Object URL of the proof

verified.twitter() ⇒ Object

Verifies that the user has a valid twitter account Throws an error otherwise.

Kind: instance method of Verified
Returns: Object - Object containing username, proof, and the verifier

verified.addTwitter(claim) ⇒ Object

Adds a twitter verification to the users profile Throws an error if the verification fails.

Kind: instance method of Verified
Returns: Object - Object containing username, proof, and the verifier

Param Type Description
claim String A did-JWT claim ownership of a twitter username

verified.email() ⇒ Object

Verifies that the user has a verified email account Throws an error otherwise.

Kind: instance method of Verified
Returns: Object - Object containing username, proof, and the verifier

verified.addEmail(claim) ⇒ Object

Adds an email verification to the users profile Throws an error if the verification fails.

Kind: instance method of Verified
Returns: Object - Object containing username, proof, and the verifier

Param Type Description
claim String A did-JWT claim ownership of an email username
更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文