Developers
  • SWT PROTOCOL
    • Introduction
    • Accounts
    • Transactions
    • Fees
    • Smart Contracts
  • GETTING STARTED
    • Network Node
      • Introduction
      • STEP 1:RENTING A LINUX VPS
      • STEP 2:INSTALLATION OF PUTTY
      • STEP 3:INSTALLATION OF FILEZILLA
      • STEP 4:VPS CONNECTION AND LINUX CONFIGURATION WITH PUTTY (SSH)
      • STEP 5:HOW TO SECURE YOUR VPS
      • STEP 6:USING TMUX THROUGH PUTTY
      • STEP 7:UPLOAD OF THE SWT SOFTWARE WITH FILEZILLA
      • STEP 8:EXTRACT THE SWT SOFTWARE FOLDER
      • STEP 9:RUNNING THE SWT NODE THROUGH TMUX
      • STEP 10:RUNNING THE MONITORING TOOLS
  • API REFERENCE
    • Apache Thrift API
      • Transactions
      • Blocks
      • Smart contract
      • Tokens
      • Wallets
      • Sync info
      • Data structures
    • REST API
      • GetBlocks()
      • GetNodeInfo()
      • GetBalance()
      • GetWalletInfo()
      • GetTokenBalance()
      • GetTransactionsByWallet()
      • GetTransactionInfo()
      • GetEstimatedFee()
      • GetContractByAddress()
      • GetContractFromTransaction()
      • GetContractMethods()
      • ContractValidation()
      • ContractCall()
      • TransactionPack()
      • TransactionExec()
  • SMART CONTRACTS
    • Creating "Hello-world" Smart Contract
    • Smart Contract Methods
    • Smart Contract Standarts
      • Token Smart Contract
      • Escrow Smart Contract
      • Stable coin Token
  • HOW TO REST API
    • Introduction
    • Retrieve a balance from the blockchain
    • Request a specific transaction from the blockchain
    • Sending Transactions to the SWT Blockchain
    • Validating and deploying a Smart Contract with REST API
Powered by GitBook
On this page
  • Introduction
  • Description of cURL Parameters
  • Code
  • Response
  • Deployment
  • Response
  1. HOW TO REST API

Validating and deploying a Smart Contract with REST API

PreviousSending Transactions to the SWT Blockchain

Last updated 1 year ago

Introduction

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

-X POST - type of HTTP request, in this case we use POST. More info here:

-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

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.

Info Let's try it out with the following code !

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!";    }}\"}"

Response

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

{
   "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
}

Success

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

Deployment

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

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

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

{
   "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"
}

Success

Great now you deployed a smart contract on the SWT Blockchain !

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

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

Smart Contract address FAe2em5gQkUaFcWQ1nKVXy2nUwW51p2pgzsZuo1bNpzn.

Here you can view the deployed Smart Contract on the SWT Blockchain ! https://explorer.swttoken.com/Network/contracts

Wikipedia