# Core SDK

### Installation

We recommend switching to Node.js version 16 to make sure common crypto dependencies works.

Then run:

```
npm install @oneid-xyz/core
```

```
yarn add @oneid-xyz/core
```

### Getting Started

<pre class="language-javascript"><code class="lang-javascript"><strong>import { OneIDCore } from '@oneid-xyz/core';
</strong>
const oneId = new OneIDCore({
  provider: provider,
  rpcUrl: string,
  headers: {
    onchainSignature?: string,
  },
  authority: {
    getPerSign: () => string,
  },
  refId?: string,
})

</code></pre>

**Parameters**:

* `provider`: (optional)
  * <https://web3js.readthedocs.io/>
* `rpcUrl`(optional)
  * HTTP Web3 Provider
* `headers`(optional)
  * `onchainSignature` - If DAPP needs to re-initiate SDK in every time using, then use this signature&#x20;
    * This signature is signed message by end-user (`MSG_SIGNED`)
    * When init SDK -> put `MSG_SIGNED` into this `onchainSignature`
    * Each action related to the SDK, DAPP will take the `onchainSignature` and attach it to API requests.
* `authority`
  * `getPerSign()` (required) If DAPP initiates SDK Global, then use this signature&#x20;
    * Initialize the global SDK with getPerSign which is a function that requires the user to sign or cache anywhere.
    * Each action related to the SDK, DAPP will get the `onchainSignature` by the SDK itself calling `getPerSign()` with the string `MSG_SIGNED` to attach to API requests.
* `refId`(optional): Default referral ID when user register.

{% hint style="info" %}
You should set your ID in the `refID to receive the refback amount.`
{% endhint %}

### Functions

#### Init Configuration

`initConfig()` allows to init base configuration from OneID SDK

***Interface**:*

```javascript
await oneid.systemConfig.initConfig()
```

Note:

* Inspect & Core SDK are using same system config, developer shall only need to init once.

#### Sequence Diagrams

Basic Register Flow

<figure><img src="https://2201202020-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fs0fgPoqkYbviHLyPP9et%2Fuploads%2FJ3fcytLZqjZo0QBern4u%2Frenew_extend-Page-1%20(1).jpg?alt=media&#x26;token=fb9e3ad3-3cea-4e77-88ef-d825f80cfb0c" alt=""><figcaption><p>Basic Register Flow</p></figcaption></figure>

* Step 1: Use function `search()` to search the ID Name, this function will return detail information of IDs.
* Step 2: \
  If DAPP use payment on VICTION, then it will need to go through 2 steps

  * Step 1: `preOrders()` in order to secure the ID to avoid front-run
  * Step 2: `postOrders()` to submit the final register.

  If DAPP use payment on Other Chains, then it will need to use the `postOrders()` function only

####

#### 1. Search OneID

`search()` allows users to find the IDs that they want to register.

Search Rule:

* Text and not including special characters
  * or search exactly ID (for example: "test.c98")
* \<search> length must be >= 3 characters

Search result:&#x20;

* `<search>` + all supported Top Level IDs (TLIDs)

***Interface**:*

```javascript
search(search: string): Promise<IDInfo[]>;
```

**Parameter***:*

* `search`: The ID Name that user wants to register (ex: "test")

*Example:*

```javascript
const search = await oneid.search(“test”)
```

***Returns**:*

```json
[
  {
      "name": "test.c98",
      "node": "0x6191afdf8a7ad87cd5e474c91f390cfdc0bb4236c5b3f428433144d2a200dcc6",
      "category": "PROTECTED",
      "tokenId": "70622639689279718371527342103894932928233838121221666359043189029713682937432",
      "contractAddress": "0x090baF1B96702FB73AF0AbBE826388117779D08f",
      "expiredAt": "0",
      "isAvailable": false,
      "price": "35372778101234409918270048885999957117893135449783156737593107166509846491550",
      "paymentToken": "0x0Fd0288AAAE91eaF935e2eC14b23486f86516c8C"
  }
]
```

**Parameter:**

* `category`: OneIDs supports 4 category as following:
  * COMMON
    * This is Regular IDs that allows user to register normally.
  * PROTECTED
    * IDs contain sensitive, inappropriate language and violate the OneID’s policies. You can not register these Governance IDs.
  * BANNED
    * IDs contain sensitive, inappropriate language and violate the OneID’s policies. You can not register these Governance IDs
  * PREMIUM
    * Premium IDs are special and popular IDs. Register fee for these IDs may be higher than normal.
* `tokenID`: the On-chain NFT Token ID of the ID Name
* `contractAddress`: the On-chain contract address of corresponding TLID
* `expireAt:` Expiration time in TimeStamp when the ID is registered
* `isAvailable`: True/False
  * If True: The ID Name not yet registered
  * If False: The ID name is already registered
* `price`: the Price number is in $ with decimal 18
* `paymentToken`: the token address pay with price.

#### 2. Get OneID Info

`getInfo()` supports to get all information of an ID Name.

***Interface**:*

```javascript
getInfo(id: string): Promise<IDInfo>;
```

**Parameter:**

* `id`: The ID Name that needs to get information (ex: "test.c98")

*Example:*

```javascript
const oneIDInfo = await oneid.getInfo(“test.c98”)
```

***Returns**:*

```json
{
  name: "test.c98",
  node: "0x6191afdf8a7ad87cd...d2a200dcc6",
  category: "COMMON",
  tokenId: "7062263968927...3189029713682937432",
  contractAddress: "0x07EE95...AC6aBF90828D",
  expiredAt: "1726201843",
  isAvailable: false,
  price: '1000000000000000000'
  paymentToken: "0x0Fd0288AAAE91eaF935e2eC14b23486f86516c8C"
}
```

####

#### 3. Get OneID detail Price

`price()` will return all the price components of an ID Name

***Interface**:*

```javascript
idPrice.useChainId('1').getPreOrderPrice(params: MultiIDParam[]): Promise<string>;
```

```javascript
MultiIDParam {
  id: string;
  duration: string | number;
  controller: string;
  owner?: string;
  extra?: string;
}
```

**Parameters:**

* `id`: the ID Name that user wants to register
* `duration`: the duration that goes to register (in seconds)
* `controller`: get from top level config in **systemConfig**
* `owner`: custom owner.
* `extra`: **tbu**

*Example*

```javascript
const tldConfig = OneIDCore.systemConfig.getTLDConfig('c98');
const { controller } = tldConfig;

const params = [
    {
        id: 'test.c98',
        duration: 31536000,
        controller: controller,
    }
]

const price = const price = await OneIDCore.idPrice
      .useChainId('88')
      .getPreOrderPrice(list);
```

***Returns***

```json
{
    price: '564135110358930963'
}
```

#### 4. Register OneID

In order to request OneID Registration, developers need to request 2 steps:

1. **`preOrders()`**
   * Commit the ID & submit Pre-oder fee to avoid front-running
     * Pre-order fee = 10% Service Fee as configuration
2. **`postOrders()`**
   * To submit order and request to register the ID.

***Interface**:*

```javascript
OneIDSDK.useChainId('88').preOrders(
    params: MultiIDParam[],
    senderAddress: string,
    paymentToken?: string
): Promise<ResponseExecuteTransaction<TransactionWithApprove>>;
```

After requested **`preOrders()`** , the `commitment` shall be generated & stored in contracts. In order to avoid front-running, the **`postOrders()`** must be in period time between 30 seconds and 1 hour (minCommitmentAge & maxCommitmentAge) since the previous committed time.

Request the function `preOrdersCheck()` to get expiration time of commitment.

After requested **`preOrders()`**, and wait for 30 seconds (minCommitmentAge) to avoid front-running, the user requests **`postOrders()`** to register the ID

```javascript
OneIDSDK.useChainId('88').postOrders(
    params: MultiIDParam[],
    senderAddress: string,
    refId?: string,
    paymentToken?: string
): Promise<ResponseExecuteTransaction<TransactionWithApprove>>;
```

**Parameters**

* `params`:

```
{
    id: the ID Name that user wants to register;
    duration: the duration that goes to register (in seconds)
    controller: get from top level config in systemConfig
    owner?: custom owner.
    extra?: TBU
}
```

* `senderAddress`: the address of registrant
* `paymentToken`: Contract address of Payment token
* `refID`: Optional - by default it will get refId from init, input another ID if you need to change the refID to another.

{% hint style="info" %}
**Note**: You should set your ID in the refID to receive the refback amount. **useChainId** using with other chain (Ethereum - 1, BinanceSmart - 56, Polygon - 137)
{% endhint %}

***Returns**:*

```json
{
    "isError": false,
    "data": {
        "isApproved": true,
        "transaction": {
            "from": "0x123...123",
            "to": "0x123...123",
            "data": "0x309e8757...245",
            "chainId": "0x58",
            "value": "0x0"
        },
        "totalPayment": "564135110358930963",
        "paymentToken": "0x0Fd0288AAAE91eaF935e2eC14b23486f86516c8C"
    }
}
```

#### 5. Extend OneID

`extend()` a name, extending the name's expiration by `duration` seconds.&#x20;

OneID also offers extend multiple IDs through function `multiExtend()`

***Interface**:*

```javascript
extend(id: string, duration: string | number, senderAddress: string, paymentToken: string): 
Promise<ResponseExecuteTransaction<string>>;
```

```javascript
multiExtend(params: MultiIDParams[], senderAddress: string, paymentToken: string): 
Promise<ResponseExecuteTransaction<string>>;
```

```javascript
interface MultiIDParams {
    id: string;
    duration: string | number;
    owner?: string;
}
```

***Returns**:*

```javascript
{
    isError: false,
    data: '0x0748af82cdfbcbea0148ff7854f32d57fb7268f9421c7caebedccfb67a1dfd39'
 }
```

####

#### 6. Link Wallet to OneID

`linkedWallet()` uses to write record of 70+ Multi-chain Wallet to the ID.&#x20;

After linking multi-chain wallet to ID, the ID can be used to receive Tokens from any network.

{% hint style="warning" %}
Use C98 Extension to easily get addresses of 100+ chains in Multi-chain Wallet.

Else, use another wallet will apply EVM Only
{% endhint %}

***Interface**:*

```javascript
linkedWallet(
    senderAddress: string,
    id: string,
    wallets: LinkedWallet[],
    signMessage: (message: string) => Promise<string>
): Promise<ResponseExecuteTransaction<TransactionConfig>>
```

```javascript
interface LinkedWallet {
  chain: ChainKey;
  address: string;
}
```

**Parameters***:*

* `chain`: the chain key (for example: CHAIN\_KEY.BINANCE\_SMART  = 'binanceSmart')
* `address`: the corresponding address of that Chain.

Validation:

* must have VICTION Wallet in `LinkedWallet[]` list

***Returns**:*

```json
{
    isError: false,
    data: {
      from: '0x0b6...ea7',
      to: '0x438...122',
      data: '0xac96....000',
      chainId: '0x58',
      value: '0x0'
    }
  }
```

#### 7. UnLink Multi-chain Wallet

`unlinkWallet()` uses to remove the Multi-chain Wallet records of the ID from that Wallet. Moreover, users can use the Linked Wallet to unlink even if it's not an owner.

***Interface**:*

```javascript
unlinkWallet(
    id: string,
    senderAddress: string,
    signMessage: (message: string) => Promise<string>
): Promise<ResponseExecuteTransaction<TransactionConfig>>;
```

**Parameters***:*

* `id`: the ID Name
* `senderAddress`: the Address of unlink requester

***Returns**:*

<pre class="language-json"><code class="lang-json"><strong>{
</strong>    isError: false,
}
</code></pre>

####

#### 8. Re-claim Permission

Users need to re-claim permission when the Controller address different from Owner address in the contract of an ID Name. This is always happened when the ID NFT is sent to another address (or trading in NFT Marketplace).

***Interface**:*

```javascript
reclaimPermission(
    id: string, 
    senderAddress: string
): Promise<ResponseExecuteTransaction<TransactionConfig>>;
```

**Parameters:**

* `id`: the ID name
* `senderAddress`:  the requester address (this should be owner address)

***Returns**:*

```json
{
    isError: false,
    data: {
      from: '0x0b6...ea7',
      to: '0x438...122',
      data: '0xac96....000',
      chainId: '0x58',
      value: '0x0'
    }
}
```

####

#### 9. Set Primary Name&#x20;

`setPrimaryName()` will assign one of **Linked IDs** as a representative account and serve as a cross-platform Web3 username and profile. Users can only designate one primary name per account.

**Linked IDs** means the ID that currently has records "Linked Wallet" of the current wallet of users, it also means the ID can't be set Primary Name when have no record "Linked Wallet"

***Interface**:*

```javascript
setPrimaryName(id: string): Promise<boolean>;
```

**Parameters:**

* `id`: The ID Name

***Returns**:*

```json
{ "isError": false }
```

### Errors Code

```json
{
  DEFAULT: "OneID Error: Unknown error occurs. Please try again!",
  INVALID_ID: "OneID Error: Invalid ID",
  API_TIMEOUT: "OneID Error: Endpoint timeout",
  INVALID_TOKEN_ADDRESS: "OneID Error: Token address is not support payment",
  INVALID_TOKEN_OWNER: "OneID Error: Invalid token owner",
  WALLET_EMPTY: "OneID Error: TomoChain Wallet is empty",
  LINKED_NOT_FOUND: "OneID Error: Linked wallet not found",
  INVALID_PERMISSION: "OneID Error: Invalid ID permission",
  INVALID_ADDRESS: "OneID Error: Invalid Address",
  INVALID_PARAMS: 'OneID Error: Params invalid',
  INVALID_ID_IN_GRACE: 'OneID Error: ID in grace time. please renew id to continue.',
  INVALID_CHAINID: 'OneID Error: ChainId is no longer support'
};
```
