# Validating and deploying a Smart Contract with REST API

### Introduction <a href="#introduction" id="introduction"></a>

This article illustrates how to use REST API to work with the Smart Contracts on the SWT Blockchain Platform.

A Smart Contract is a program written in Java that compiles in byte code and is deployed on the blockchain. Each successful Smart Contract launch results in saving its new state in the blockchain. The next launch of the Smart Contract uses its previous state.

### Description of cURL Parameters <a href="#description-of-curl-parameters" id="description-of-curl-parameters"></a>

-X POST - type of HTTP request, in this case we use POST. More info here: [***Wikipedia***](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods)

-H “accept: application/json”

-H “Content-Type: application/json” - Specification for the transferred parameters and response to be in JSON format

-d {parameters} - With this key, we specify the data transferred with the request. Let’s look at them in more detail:

“authKey”: “” - Authorization key. Not used at present, should be passed “”

“networkAlias”: “Mainnet” - We specify the network, where the request should be executed. Either Testnet or Mainnet.

“sourceString": "source code" - Here we specify the source code of a smart contract.

### Code <a href="#code" id="code"></a>

For compatibility check, REST API provides a “Validate” function. The easiest way to invoke it is to use CURL tool. Example of CURL tool uses is provided below.

{% hint style="info" %}
**Info**\
Let's try it out with the following code !
{% endhint %}

{% code overflow="wrap" %}

```bash
curl -X POST "http://176.113.80.7:62000/api/contract/validate" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"authKey\":\"\",\"networkAlias\":\"Mainnet\", \"sourceString\":\"package com.example.contract;import com.credits.scapi.annotations.*;import com.credits.scapi.v2.SmartContract;import com.credits.scapi.v1.*;mport java.math.BigDecimal; public class my extends SmartContract {    public my() {   }    @Override    public String payable(BigDecimal amount, byte[] userData) {        return null;    }    public String hello() {        return "Hello!";    }}\"}"
```

{% endcode %}

### Response <a href="#response" id="response"></a>

Upon successful compilation REST should return JSON response containing the status “success”: “true”. Example of the successful launch in cURL is provided below.

{% code overflow="wrap" %}

```json
{
   "deploy":{
      "sourceCode":"package com.example.contract;import com.credits.scapi.annotations.*;import com.credits.scapi.v2.SmartContract;import com.credits.scapi.v1.*;mport java.math.BigDecimal; public class my extends SmartContract {    public my() {   }    @Override    public String payable(BigDecimal amount, byte[] userData) {        return null;    }    public String hello() {        return Hello!;    }}",
      "byteCodeObjects":[

      ]
   },
   "tokenStandard":0,
   "success":true,
   "message":null
}
```

{% endcode %}

{% hint style="info" %}
**Success**

Great now we know that the smart contract is validated so let's move on the deployment of the Contract !
{% endhint %}

### Deployment <a href="#deployment" id="deployment"></a>

To deploy a Smart Contract you should sign the resulting byte code with a digital signature. The following Python code allows us deploying the Smart contract in 2 steps:

1. Compile a Smart Contract into byte code
2. Sign the resulting byte code and sent the transaction for Smart Contract deployment

```python
import json
import base58check
import ed25519
from struct import *

contract_code = """package com.example.contract;

import com.credits.scapi.annotations.*;

import com.credits.scapi.v2.SmartContract;

import com.credits.scapi.v1.*;

import java.math.BigDecimal;

public class my extends SmartContract {

    public my() {

    }

    @Override

    public String payable(BigDecimal amount, byte[] userData) {

        return null;

    }

    public String hello() {

        return "Hello!";

    }

}"""

priv = '2SeqBtsQpoSD7DJQpmY6ZnfDosg9VGndoaPSMSh8hrTALySWPEXxQKMrnAVy79U2GxWNAXm6dnmzYdNUToJpLzFm' #put here private Key in base58 form
publ = 'AU8iyCcpwRehfsMv2myrykxWjAsxyrpQbPTaymAxjDYF' #put here public Key in base58 form
proposed_fee = 0.1

headers = {
    'Content-type': 'application/json'
    , 'Accept': 'application/json'
    , 'Content-Encoding': 'utf-8'
    }

url =  'http://176.113.80.7:62000/api/Transaction/Pack'

data = {
    "authKey": ""
    , "NetworkAlias":"Mainnet"
    , "networkIp":""
    , "networkPort":""
    , "MethodApi" : "SmartDeploy"
    , "PublicKey":publ
    , "SmartContractSource":contract_code
    , "Fee":proposed_fee
}

answer_pack = requests.post(url, data=json.dumps(data), headers=headers)
if answer_pack.status_code == 200:
    ts = json.loads(answer_pack.text)
    transaction_packed = ts['dataResponse']['transactionPackagedStr']
    src_priv = base58check.b58decode(priv)
    signing_key = ed25519.SigningKey(src_priv) # Create object for calulate signing
    signature_code = signing_key.sign(base58check.b58decode(transaction_packed))
    signature = base58check.b58encode(signature_code).decode('utf-8')

    url =  'http://176.113.80.7:62000/api/Transaction/Execute'
    data = {
        "authKey": ""
        , "NetworkAlias":"Mainnet"
        , "MethodApi" : "SmartDeploy"
        , "PublicKey":publ
        , "SmartContractSource":contract_code
        , "TransactionSignature":signature
        , "Fee":0.1
    }

    answer_execute = requests.post(url, data=json.dumps(data), headers=headers)
    ts = json.loads(answer_execute.text)

print(ts)
```

### Response <a href="#response" id="response"></a>

After the script execution, you should receive an output similar to the one below (except the addresses).

```json
{
   "transactionInnerId":5,
   "amount":0,
   "dataResponse":{
      "publicKey":"FAe2em5gQkUaFcWQ1nKVXy2nUwW51p2pgzsZuo1bNpzn",
      "transactionPackagedStr":"None"
   },
   "listItem":[

   ],
   "transactionInfo":"None",
   "listTransactionInfo":"None",
   "blockId":0,
   "transactionId":"13707845.1",
   "flowResult":"None",
   "success":True,
   "message":"None"
}
```

{% hint style="info" %}
**Success**

Great now you deployed a smart contract on the SWT Blockchain !
{% endhint %}

Execution status shows the deployment was successful (‘success’: True)

Transaction number in the Blockchain 'transactionId': '*13707845.1*'

Smart Contract address *FAe2em5gQkUaFcWQ1nKVXy2nUwW51p2pgzsZuo1bNpzn*.

{% hint style="info" %}
Here you can view the deployed Smart Contract on the SWT Blockchain ! \
<https://explorer.swttoken.com/Network/contracts>
{% endhint %}


---

# 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.swttoken.com/how-to-rest-api/validating-and-deploying-a-smart-contract-with-rest-api.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.
