# Integrate Skynet package into your Project

What is the Skynet Package?

This package handles CRUD (Create, Read, Updated, and Delete) operations for applications deployed to Skynet.&#x20;

Here are some things you need to know about a SkyID:&#x20;

* It can have single or multiple applications. For example, a database, backend, and frontend website deployed as three applications under a SkyID with an ID 1535.
* You need sUsd tokens to run your SkyID, and you have to deposit them into the SkyID.&#x20;
* The package is modular; this means you can extend and modify it according to your specific use case.&#x20;

The Skynet package handles:&#x20;

* Contract interactions.&#x20;
* Application encryption and decryption.
* Manages uploading and downloading of application payloads to and from decentralized storage platforms.
* Perform CRUD operations on your application–Application manager.&#x20;
* Estimates and manages the cost of running an application; this happens through a drip manager.&#x20;

***

### Prerequisite

To get the best out of this package and the contract calls to perform for specific use cases. You need to:&#x20;

* Have a basic understanding of [Blockchain technology](https://en.wikipedia.org/wiki/Blockchain).
* An understanding of [smart contracts](https://en.wikipedia.org/wiki/Smart_contract).&#x20;
* [Node.js](https://nodejs.org/en) and npm set up.
* A decentralized application project.&#x20;

{% hint style="info" %}
To carry out these contract initialization and calls appropriately. You should include the required files for your specific use case in your project’s root directory.
{% endhint %}

***

### Installation

Run this in your project's root directory:

{% tabs %}
{% tab title="npm" %}

```bash
npm i @decloudlabs/skynet
```

{% endtab %}
{% endtabs %}

***

### Initialise Contract Service

It contains the required definitions for contract application deployment to initialize contract service. Implement this code:

{% tabs %}
{% tab title="" %}

```typescript
import { ethers } from 'ethers';
import SkyBrowserSigner from '@decloudlabs/skynet/lib/services/SkyEtherContractService';
import SkyEtherContractService from '@decloudlabs/skynet/lib/services/SkyEtherContractService';
import SkyMainBrowser from '@decloudlabs/skynet/lib/services/SkyMainBrowser';


const provider = new ethers.providers.Web3Provider(window.ethereum);

const signer = provider.getSigner();

 const envConfig: SkyEnvConfigBrowser = {
        STORAGE_API: {
          IPFS: {
            PROJECT_ID: "infurs ipfs project id",
            PROJECT_SECRET: "infurs ipfs project secret",
          }
        },
        CACHE: {
          TYPE: "CACHE",
        },
      };

const contractInstance = new SkyEtherContractService(provider, signer, address, 11); // 11 is the chain Id of Skynet

const skyMainBrowser = new SkyMainBrowser(
        contractInstance,
        address, // connected wallet address
        new SkyBrowserSigner(address, signer),
        envConfig
      );

await skyMainBrowser.init(true);
```

{% endtab %}
{% endtabs %}

Explaining the parameters:&#x20;

* `provider`:Initializes a Web3 provider using the `window.ethereum` object. The provider here allows the application to read from and send transactions to the Ethereum blockchain.
* `signer`: This allows users to sign transactions and applications to initiate state-changing operations on the blockchain.
* `contractInstance` : it's an SDK library that is used to create an instance of contracts that contains the main contracts deployed in the Skynet chain.
* `address`: The Ethereum address associated with your wallet would be used for performing the transactions. Ensure the signer is authorized to act on behalf of this address.
* `skyMainBrowser`:  This initializes an instance of `skyMainBrowser` while passing `contractInstance`, `address`, and a new instance of `SkyBrowserSigner`.&#x20;

***

### Mint and Fetch SkyId

To mint and fetch the ID of a SkyID, implement this code:

{% code lineNumbers="true" %}

```typescript
const fetchNFTID = async () => {
    const mintResp = await contractService.callContractWrite(
	contractService.AppNFTMinter.mint(address, {
        	value: 10 ** 11,
        	from: address,
    	})
	);
    
    if(!mintResp.success) throw new Error("failed to mint");
    
    const nftCountResp = await appCrypto.contractService.callContractRead(
   		 AppNFT.balanceOf(address),
   		 (res) => res.toNumber()
   	 );
    if(!nftCountResp.success) throw new Error("failed to fetch NFT");
    
    const nftCount = nftCountResp.data;
    
    const nftReq = appCrypto.contractService.callContractRead(
   	 AppNFT.tokenOfOwnerByIndex(address, nftCount-1),
   	 (res) => res.toNumber()
    );
    if(!nftReq.success) throw new Error("failed to fetch the nftID");
    
    const nftID = nftReq.data;
}
```

{% endcode %}

The code does the following:&#x20;

* The `fetchNFTID` function helps you mint a new NFT and fetch the ID of the NFT owned by a specific address.

<details>

<summary>Example Code</summary>

{% code lineNumbers="true" %}

```typescript
import { fetchNFTID } from './filepath';

fetchNFTID()
```

{% endcode %}

</details>

***

### Fetch Application List

Use this code to implement:

{% code lineNumbers="true" %}

```typescript
const appList = await appManager.contractCall.getAppList(nftID);
```

{% endcode %}

Implementing this code does the following:&#x20;

* It retrieves the applications that are linked to specific SkyIDs.
* After retrieving, services related to the applications can be accessed or used.

<details>

<summary>Example Code </summary>

{% code lineNumbers="true" %}

```typescript
import { STKAppManager, ContractApp, SubscriptionParam, APICallReturn } from '@decloudlabs/stk-v2';

// Initialize the necessary services and callbacks
// Replace these with your actual implementations
const appBrowserCache = {};
const multiStorage = {};
const EtherContracts = {};
const appEncryptor = {};
const appDecryptor = {};

const saveAppToLocal = (app: ContractApp): Promise<APICallReturn<string>> => {
    // Implementation here
};

const saveSubParamToLocal = (subParam: SubscriptionParam): Promise<APICallReturn<string>> => {
    // Implementation here
};

const removeAppFromLocal = (nftID: string, appID: string): Promise<APICallReturn<string>> => {
    // Implementation here
};

// Create a new instance of STKAppManager
const appManager = new STKAppManager(
    appBrowserCache,
    multiStorage,
    EtherContracts,
    appEncryptor,
    appDecryptor,
    saveAppToLocal,
    saveSubParamToLocal,
    removeAppFromLocal
);

// Use the getAppList method
// Replace 'nftID' with your actual NFT ID
const nftID = 'nftID';
appManager.contractCall.getAppList(nftID)
    .then(appList => {
        console.log(appList);
    })
    .catch(error => {
        console.error('Failed to get app list:', error);
    });
```

{% endcode %}

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://documentation.skynet.io/skynet/build-your-project-on-skynet/integrate-skynet-package-into-your-project.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
