# Smart Contract

#### **Smart Contract Development on XSPACE Protocol**

The XSPACE Protocol supports the development and deployment of Ethereum-compatible smart contracts, enabling seamless integration with existing blockchain tools and workflows. This guide provides an overview of smart contracts on XSPACE, including deployment, interaction, and best practices.

***

### **Overview of XSPACE Smart Contracts**

#### **1. Ethereum Virtual Machine (EVM) Compatibility**

XSPACE is **EVM-compatible**, meaning developers can write and deploy smart contracts using the same tools and languages (e.g., Solidity) as on Ethereum. This ensures a low learning curve for developers transitioning from other EVM-based blockchains.

#### **2. Key Features**

* **High Performance:**\
  Contracts execute with near-instant finality (\~1-2 seconds) thanks to XSPACE’s sharded architecture and Delegated Proof-of-Stake (DPoS 2.0).
* **Low Transaction Fees:**\
  XSPACE’s efficient consensus mechanism and sharding result in significantly lower gas costs compared to Ethereum.
* **Interoperability:**\
  Smart contracts can interact with external blockchains via XSPACE’s cross-chain bridges, enabling multi-chain dApps.
* **Enhanced Tokenization Standards:**\
  Use the **XSPACE Asset Tokenization Standard (XATS)** to tokenize real-world assets with integrated metadata and compliance tools.

***

### **Deploying Smart Contracts**

#### **Step 1: Create a Smart Contract**

Smart contracts on XSPACE are written in **Solidity**, a popular language for EVM-based blockchains.

**Example: A Simple Storage Contract**

Create a new file in your `contracts` directory, e.g., `SimpleStorage.sol`:

```solidity
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private data;

    // Set the value of `data`
    function set(uint256 _data) public {
        data = _data;
    }

    // Retrieve the value of `data`
    function get() public view returns (uint256) {
        return data;
    }
}
```

***

#### **Step 2: Configure the Development Environment**

Ensure your `hardhat.config.js` file is configured for the XSPACE Testnet:

```javascript
require("@nomiclabs/hardhat-waffle");

module.exports = {
  solidity: "0.8.0",
  networks: {
    xspaceTestnet: {
      url: "https://testnet.xspaceprotocol.io/rpc",
      chainId: 80001,
      accounts: ["YOUR_PRIVATE_KEY"]
    }
  }
};
```

Replace `"YOUR_PRIVATE_KEY"` with the private key of your Testnet wallet (use Metamask to export it).

***

#### **Step 3: Deploy the Smart Contract**

Write a deployment script in the `scripts` directory, e.g., `deploy.js`:

```javascript
async function main() {
    // Compile and deploy the SimpleStorage contract
    const SimpleStorage = await ethers.getContractFactory("SimpleStorage");
    const contract = await SimpleStorage.deploy();
    await contract.deployed();

    console.log("Contract deployed to:", contract.address);
}

main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});
```

Deploy the contract to the XSPACE Testnet:

```bash
npx hardhat run scripts/deploy.js --network xspaceTestnet
```

***

#### **Step 4: Verify Deployment**

1. Note the contract address output from the deployment script.
2. Use the **XSPACE Testnet Explorer** to verify the contract:\
   [https://testnet-explorer.xspace.io](https://testnet-explorer.xspace.io/).

***

### **Interacting with Smart Contracts**

Once deployed, you can interact with your smart contract using tools like Hardhat, Web3.js, or Ethers.js.

***

#### **Method 1: Using Hardhat Console**

Hardhat provides an interactive console for directly interacting with deployed contracts.

1. Open the Hardhat console:

   ```bash
   npx hardhat console --network xspaceTestnet
   ```
2. Load the deployed contract:

   ```javascript
   const contract = await ethers.getContractAt("SimpleStorage", "DEPLOYED_CONTRACT_ADDRESS");
   ```
3. Call the `set` function to store a value:

   ```javascript
   await contract.set(42);
   ```
4. Retrieve the stored value using the `get` function:

   ```javascript
   const value = await contract.get();
   console.log("Stored value:", value.toString());
   ```

***

#### **Method 2: Using a JavaScript dApp**

Integrate your smart contract with a JavaScript frontend using **Ethers.js** or **Web3.js**.

**Frontend Setup**

Install Ethers.js:

```bash
npm install ethers
```

**Connect to the XSPACE Testnet**

Create a connection to the blockchain:

```javascript
const { ethers } = require("ethers");

// Connect to the XSPACE Testnet
const provider = new ethers.providers.JsonRpcProvider("https://testnet.xspaceprotocol.io/rpc");

// Wallet setup
const privateKey = "YOUR_PRIVATE_KEY";
const wallet = new ethers.Wallet(privateKey, provider);

// Contract ABI and address
const abi = [
    "function set(uint256 _data) public",
    "function get() public view returns (uint256)"
];
const contractAddress = "DEPLOYED_CONTRACT_ADDRESS";

// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, wallet);

// Interact with the contract
(async () => {
    // Set a value
    const tx = await contract.set(42);
    await tx.wait();

    // Get the value
    const value = await contract.get();
    console.log("Stored value:", value.toString());
})();
```

***

### **Best Practices for Smart Contract Development**

1. **Optimize Gas Usage:**
   * Avoid unnecessary state variables and computations.
   * Use view/pure functions wherever possible.
2. **Thorough Testing:**
   * Test contracts locally using Hardhat or Truffle.
   * Use tools like Chai for writing test cases.
3. **Security Audits:**
   * Always audit smart contracts to check for vulnerabilities like reentrancy, overflow/underflow, and improper access control.
4. **Use IPFS for Off-Chain Data:**
   * Store large metadata (e.g., property details, asset history) off-chain on IPFS and link it to the contract.

***

### **Next Steps**

1. **Build Advanced Contracts:** Explore multi-shard interactions, privacy-preserving transactions (zk-SNARKs), and token standards (ERC-20/721).
2. **Deploy dApps:** Create decentralized applications integrating smart contracts with frontend frameworks.
3. **Explore Tokenization:** Use the **XATS framework** to tokenize real-world assets.

This guide sets the foundation for building, deploying, and interacting with smart contracts on XSPACE.&#x20;


---

# 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://docs.xspaceprotocol.io/getting-started/developer-docs/smart-contract.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.
