Skip to content

xuper sdk go 英文版

liminglei02 edited this page Feb 10, 2021 · 2 revisions

1.Xuper-SDK Overview

Xuper-SDK is a powerful tool for the Go developers to access and use XuperChain easily and quickly.This document will show you what Xuper-SDK is and how to use Xuper-SDK to build your application by simple examples.

2.Module Introduction

Applications can be developed quickly by using Xuper-SDK.Xuper-SDK includes the following API modules:

  • Account: creating blockchain account, restoring blockchain account through mnemonics, saving encryption file of the account to local space, restoring account from local encryption file, etc.
  • Contract account: creating contract account, etc.
  • Smart contract: deploying contract, contract-inovke interaction, contract-query interaction etc.
  • Transaction: Normal transaction and transaction query, etc.

3.Quick Start

3.1 Environment

  • operating system: Linux or Mac Os
  • development language: Go 1.12.x and above
  • compiler: GCC 4.8.x and above
  • version control tools: Git

3.2 Get code and Install

Please download or clone code in github.com

git clone https://github.com/xuperchain/xuper-sdk-go
cd xuper-sdk-go

Compile

make
make test

3.3 Examples

3.3.1 Account

Refer to function testAccount() in github.com/xuperchain/xuper-sdk-go/example/main.go

func testAccount() {
   // create an account for the user,
   // strength 1 means that the number of mnemonics is 12
   // language 1 means that mnemonics is Chinese
   acc, err := account.CreateAccount(1, 1)
   if err != nil {
      fmt.Printf("create account error: %v\n", err)
   }
   // print the account, mnemonics
   fmt.Println(acc)
   fmt.Println(acc.Mnemonic)

   // retrieve the account by mnemonics
   acc, err = account.RetrieveAccount(mnemonics, 1)  // your own mnemonics
   if err != nil {
      fmt.Printf("retrieveAccount err: %v\n", err)
   }
   fmt.Printf("RetrieveAccount: to %v\n", acc)

   // create an account, then encrypt using password and save it to a file
   acc, err = account.CreateAndSaveAccountToFile("./keys", "123", 1, 1)
   if err != nil {
      fmt.Printf("createAndSaveAccountToFile err: %v\n", err)
   }
   fmt.Printf("CreateAndSaveAccountToFile: %v\n", acc)

   // get the account from file, using password decrypt
   acc, err = account.GetAccountFromFile("keys/", "123")
   if err != nil {
      fmt.Printf("getAccountFromFile err: %v\n", err)
   }
   fmt.Printf("getAccountFromFile: %v\n", acc)
}

3.3.2 ContractAccount

Refer to function testContractAccount() in github.com/xuperchain/xuper-sdk-go/example/main.go

// define blockchain node and blockchain name
var (
   contractName = "counter"
   node         = "x.x.x.x:8080"  // node ip
   bcname       = "xuper"
)
func testContractAccount() {
   // retrieve the account by mnemonics
   account, err := account.RetrieveAccount(mnemonics, 1) // your own mnemonics
   if err != nil {
      fmt.Printf("retrieveAccount err: %v\n", err)
   }

   // define the name of the conrtact account to be created
   // conrtact account is XC+16 length digit + @ +bcname
   contractAccount := "XC3343xxxx@xuper" // your contractAccount which belong to the above account

   // initialize a client to operate the contract account
   ca := contractaccount.InitContractAccount(account, node, bcname)

   // create contract account
   txid, err := ca.CreateContractAccount(contractAccount)
   if err != nil {
      log.Printf("CreateContractAccount err: %v", err)
      os.Exit(-1)
   }
   fmt.Println(txid)
}

3.3.3 Transaction

Refer to function testAccount() in github.com/xuperchain/xuper-sdk-go/example/main.go

// define blockchain node and blockchain name
var (
   contractName = "counter"
   node         = "x.x.x.x:8080" // node ip:port
   bcname       = "xuper"
)
func testTransfer() {
   // retrieve the account by mnemonics
   acc, err := account.RetrieveAccount(mnemonics, 1) // your own mnemonics
   if err != nil {
      fmt.Printf("retrieveAccount err: %v\n", err)
   }
   fmt.Printf("account: %v\n", acc)

   // initialize a client to operate the transfer transaction
   trans := transfer.InitTrans(acc, node, bcname)

   // transfer destination address, amount, fee and description
   to := "UgdxaYwTzUjkvQnmeB3VgnGFdXfrsiwFv"
   amount := "200"
   fee := "0"
   desc := ""
   // transfer
   txid, err := trans.Transfer(to, amount, fee, desc)
   if err != nil {
      fmt.Printf("Transfer err: %v\n", err)
   }
   fmt.Printf("transfer tx: %v\n", txid)
}
// get balance
func testGetBalance() {
   // retrieve the account by mnemonics
   acc, err := account.RetrieveAccount(mnemonics, 1) // your own mnemonics
   if err != nil {
      fmt.Printf("retrieveAccount err: %v\n", err)
   }
   fmt.Printf("account: %v\n", acc)

   // initialize a client to operate the transaction
   trans := transfer.InitTrans(acc, node, bcname)

   // get balance of the account
   balance, err := trans.GetBalance()
   log.Printf("balance %v, err %v", balance, err)
}
// query tx
func testQueryTx() {
   // initialize a client to operate the transaction
   trans := transfer.InitTrans(nil, node, bcname)
   txid := "3a78d06dd39b814af113dbdc15239e675846ec927106d50153665c273f51001e"
   
   // query tx by txid
   tx, err := trans.QueryTx(txid)
   log.Printf("query tx %v, err %v", tx, err)
}

3.3.4 Conrtact

Refer to function testAccount() in github.com/xuperchain/xuper-sdk-go/example/main.go

// define blockchain node, blockchain name and contract name
var (
   contractName = "counter"
   node         = "x.x.x.x:8080"  // node ip:port
   bcname       = "xuper"
)
// deploy wasm contract
func testDeployWasmContract() {
   // retrieve the account by mnemonics
   acc, err := account.RetrieveAccount(mnemonics, 1) // your own mnemonics
   if err != nil {
      fmt.Printf("retrieveAccount err: %v\n", err)
   }
   fmt.Printf("account: %v\n", acc)

   // set contract account, contract will be installed in the contract account
   contractAccount := "XC1212xxx@xuper" // your contract account which belongs to your own account

   // initialize a client to operate the contract
   wasmContract := contract.InitWasmContract(acc, node, bcname, contractName, contractAccount)

   // set init args and contract file
   args := map[string]string{
      "creator": "xchain",
   }
   codePath := "example/contract_code/counter.wasm"

   // deploy wasm contract
   txid, err := wasmContract.DeployWasmContract(args, codePath, "c")
   if err != nil {
      log.Printf("DeployWasmContract err: %v", err)
      os.Exit(-1)
   }
   fmt.Printf("DeployWasmContract txid: %v\n", txid)
   return
}
// invoke contract
func testInvokeWasmContract() {
   // retrieve the account by mnemonics
   acc, err := account.RetrieveAccount(mnemonics, 1) // your own mnemonics
   if err != nil {
      fmt.Printf("retrieveAccount err: %v\n", err)
   }
   fmt.Printf("account: %v\n", acc)

   // initialize a client to operate the contract
   contractAccount := ""
   wasmContract := contract.InitWasmContract(acc, node, bcname, contractName, contractAccount)

   // set invoke function method and args
   args := map[string]string{
      "key": "counter",
   }
   methodName := "increase"

   // invoke contract
   txid, err := wasmContract.InvokeWasmContract(methodName, args)
   if err != nil {
      log.Printf("InvokeWasmContract PostWasmContract failed, err: %v", err)
      os.Exit(-1)
   }
   log.Printf("txid: %v", txid)
   return
}
// query contract
func testQueryWasmContract() {
   // retrieve the account by mnemonics
   acc, err := account.RetrieveAccount(mnemonics, 1) // your own mnemonics
   if err != nil {
      fmt.Printf("retrieveAccount err: %v\n", err)
   }
   fmt.Printf("account: %v\n", acc)

   // initialize a client to operate the contract
   contractAccount := ""
   wasmContract := contract.InitWasmContract(acc, node, bcname, contractName, contractAccount)

   // set query function method and args
   args := map[string]string{
      "key": "counter",
   }
   methodName := "get"

   // query contract
   preExeRPCRes, err := wasmContract.QueryWasmContract(methodName, args)
   if err != nil {
      log.Printf("QueryWasmContract failed, err: %v", err)
      os.Exit(-1)
   }
   gas := preExeRPCRes.GetResponse().GetGasUsed()
   fmt.Printf("gas used: %v\n", gas)
   for _, res := range preExeRPCRes.GetResponse().GetResponse() {
      fmt.Printf("contract response: %s\n", string(res))
   }
}

4.Detailed Explanation of APIs

In addition to user account related operations, other types of operations need to initialize a related and reusable client which contains basic data at first, and then call related methods through the client.

4.1 Account

Account means the user's account on the blockchain, which generally includes address, public and private key, mnemonics.Please store the mnemonics properly for the future reference of the recovery of the account. Once you lost the mnemonics, you lost the account. And you can also save the private key to the file which was encrypted by the password, so as to prevent the disclosure of the private key file.

a.Create account

Create an account on blockchain, includes address, public and private key, mnemonics. Please store the mnemonics properly for the future reference of the recovery of the account. When you create an account, you can appointed the strength and the lanuage of mnemonics.

1.Function name

  • func CreateAccount(strength uint8, language int) (*Account, error)

2.Parameters

parmas explanation type
strength account strength,can be
  • 1:Mnemonics of length 12
  • 2:Mnemonics of length 18
  • 3:Mnemonics of length 24
unit8
language mnemonics language,can be
  • 1:Chinese
  • 2:English
int

3.Returns

type explanation
*Account type Account struct {
Address string
PrivateKey string
PublicKey string
Mnemonic string
}
error
  • nil: success
  • non-nil: fail

b.Retrieve account by mnemonics

retrieve account by mnemonics.

1.Function name

  • func RetrieveAccount(mnemonic string, language int) (*Account, error)

2.Parameters

parmas explanation type
mnemonic mnemonics string
language mnemonics language,can be
  • 1:Chinese
  • 2:English
int

3.Returns

type explanation
*Account type Account struct {
Address string
PrivateKey string
PublicKey string
Mnemonic string
}
error
  • nil: success
  • non-nil: fail

c.Create and save account

Encrypt the account by the password and store in file once created. You can retrieve the account by the file and the password. Equally you can alse retrieve the account by the mnemonics.

1.Function name

  • func CreateAndSaveAccountToFile(path, passwd string, strength uint8, language int) (*Account, error)

2.Parameters

parmas explanation type
path file path of account string
passwd password string
strength account strength,can be
  • 1:Mnemonics of length 12
  • 2:Mnemonics of length 18
  • 3:Mnemonics of length 24
unit8
language mnemonics language,can be
  • 1:Chinese
  • 2:English
int

3.Returns

type explanation
*Account type Account struct {
Address string
PrivateKey string
PublicKey string
Mnemonic string
}
error
  • nil: success
  • non-nil: fail

d.Retrieve account from file

Retrieve the account by the file and the password.

1.Function name

  • func GetAccountFromFile(path, passwd string) (*Account, error)

2.Parameters

parmas explanation type
path file path of account string
passwd password string

3.Returns

type explanation
*Account type Account struct {
Address string
PrivateKey string
PublicKey string
Mnemonic string
}
error
  • nil: success
  • non-nil: fail

4.2 Contract Account

Operations about the contract account who manage contracts. Contract must be installed in the conrtact account.

a.Initialize a client

Initialize a client to operate the contract account. The other operation must use the client.

1.Function name

  • func InitContractAccount(account *account.Account, node, bcname string) *ContractAccount

2.Parameters

params explanation type
account user account *account.Account
node host of xchain net string
bcname blockchain name string

3.Returns

type explanation
*ContractAccount client to operate the contract account

b. Create contract account

Create a contract accoint and return the transaction's id. In the process of the creation, you should pay the gas which is priced by the difficulty of the execution. You can get the gas by the function PreCreateContractAccount and PostCreateContractAccount, instead of the function CreateContractAccount.

1.function name

  • func (ca *ContractAccount) CreateContractAccount(contractAccount string) (string, string, error)

2.Parameters

params explanation type
contractAccount contract account name, the16-digit serial number string

3.Returns

type explanation
string txid of the transaction of create contract account
string contract account name
error
  • nil: success
  • non-nil: fail

c. Pre-execution of create contract account

Pre execute the creation of a contract account, which you can get the gas of the creation.

1.Function name

  • func (ca *ContractAccount) PreCreateContractAccount(contractAccount string) (*pb.PreExecWithSelectUTXOResponse, error)

2.Parameters

params explanation type
contractAccount contract account name, the16-digit serial number string

3.Returns

type explanation
*pb.PreExecWithSelectUTXOResponse the result of the pre-execution
error
  • nil: success
  • non-nil: fail

d. Create contract account by the result of the pre-execution

Execute by the result of the pre execution to create a contract account.

1.Function name

  • func (ca *ContractAccount) PostCreateContractAccount(preExeResp *pb.PreExecWithSelectUTXOResponse) (string, error)

2.Parameters

params explanation type
preExeResp the result of the pre-execution *pb.PreExecWithSelectUTXOResponse

3.Returns

type explanation
string txid of the transaction of create contract account
error
  • nil: success
  • non-nil: fail

4.3 Transfer

Transfer, which can complete the transfer of value on the blockchain.

a. Initialize a client

Initialize a client to transfer. The other operation must use the client.

1.Function name

  • func InitTrans(account *account.Account, node, bcname string) *Trans

2.Parameters

params explanation type
account user account *account.Account
node host of xchain net string
bcname blockchain name string

3.Returns

type explanation
*Trans client to operate the contract account

b. Transfer

1.Function name

  • func (t *Trans) Transfer(to, amount, fee, desc string) (string, error)

2.Parameters

params explanation type
to transfer destination address string
amount transfer amount string
fee transfer fee string
desc transfer description string

3.Returns

type explanation
string txid of the transaction of transfer
error
  • nil: success
  • non-nil: fail

c. Query transaction details

Query the transaction by the tansaction's id, which type can be transfer, contract create or contract invoke.

1.function name

  • func (t *Trans) QueryTx(txid string) (*pb.TxStatus, error)

2.Parameters

params explanation type
txid string txid of the transaction of transfer

3.Returns

type explanation
*pb.TxStatus transaction details
error
  • nil: success
  • non-nil: fail

d. Query balance of a user account

Query the balance of the account on the blockchain.

1.Function name

  • func (t *Trans) GetBalance() (string, error)

2.Parameters

null

3.Returns

type explanation
string balance
error
  • nil: success
  • non-nil: fail

4.4 Conratct

Operations about the contract, includes deployment, invoked, and query. The contract name is unique on the blockchain.

a. Initialize a client

Initialize a client to operate the contract. The other operation must use the client.

1.Function name

  • func InitWasmContract(account *account.Account, node, bcName, contractName, contractAccount string) *WasmContract

2.Parameters

params explanation type
account user account *account.Account
node host of xchain net string
bcname blockchain name string
contractName contract name string
contractAccount contract account string

3.Returns

type explanation
*WasmContract client to operate the contract

b. Deploy contract

Deploy the wasm contract and return the transaction's id. You can alse use the function PreDeployWasmContract and PostWasmContract to deploy the contract.

1.Function name

  • func (c *WasmContract) DeployWasmContract(args map[string]string, codepath string, runtime string) (string, error)

2.Parameters

params explanation type
args contract init args map[string]string
codepath contract file string
runtime contract language, c or go string

3.Returns

type explanation
string txid of the transaction of deploy contract
error
  • nil: success
  • non-nil: fail

c. Pre-execution of deploy contract

Pre execute the deployment of the contract, which you can get the gas of the deployment.

1.Function name

  • func (c *WasmContract) PreDeployWasmContract(arg map[string]string, codepath string, runtime string) (*pb.PreExecWithSelectUTXOResponse, error)

2.Parameters

params explanation type
args contract init args map[string]string
codepath contract file string
runtime contract language, c or go string

3.Returns

type explanation
*pb.PreExecWithSelectUTXOResponse the result of the pre-execution of deploy contract
error
  • nil: success
  • non-nil: fail

d. Deploy contract by the result of the pre-execution

Execute by the result of the pre execution to deploy a contract.

1.Function name

  • func (c *WasmContract) PostWasmContract(preExeWithSelRes *pb.PreExecWithSelectUTXOResponse) (string, error)

2.Parameters

params explanation type
preExeWithSelRes the result of the pre-execution *pb.PreExecWithSelectUTXOResponse

3.Returns

type explanation
string txid of the transaction of deploy contract
error
  • nil: success
  • non-nil: fail

e. Invoke contract

Invoke the conrtact and return the transaction's id. You can alse use the function PreInvokeWasmContract and PostWasmContract to invoke the contract.

1.Function name

  • func (c *WasmContract) InvokeWasmContract(methodName string, args map[string]string) (string, error)

2.Parameters

params explanation type
methodName conrtact method to invoke string
args method args map[string]string

3.Returns

type explanation
string txid of the transaction of invoke contract
error
  • nil: success
  • non-nil: fail

e. Pre-execution of invoke contract

Pre execute the invoking of the contract, which you can get the gas of the invoking.

1.Function name

  • func (c *WasmContract) PreInvokeWasmContract(methodName string, args map[string]string) (*pb.PreExecWithSelectUTXOResponse, error)

2.Parameters

params explanation type
methodName conrtact method to invoke string
args method args map[string]string

3.Returns

type explanation
*pb.PreExecWithSelectUTXOResponse the result of the pre-execution of invoke contract
error
  • nil: success
  • non-nil: fail

e. Invoke contract by the result of the pre-execution

Execute by the result of the pre execution to invoke a contract.

1.Function name

  • func (c *WasmContract) PostWasmContract(preExeWithSelRes *pb.PreExecWithSelectUTXOResponse) (string, error)

2.Parameters

params explanation type
preExeWithSelRes the result of the pre-execution *pb.PreExecWithSelectUTXOResponse

3.Returns

type explanation
string txid of the transaction of invoke contract
error
  • nil: success
  • non-nil: fail

f. Query contract

Query the conrtact ledger.

1.Function name

  • func (c *WasmContract) QueryWasmContract(methodName string, args map[string]string) (*pb.InvokeRPCResponse, error)

2.Parameters

params explanation type
methodName conrtact method to invoke string
args method args map[string]string

3.Returns

type explanation
*pb.PreExecWithSelectUTXOResponse the result of query contract
error
  • nil: success
  • non-nil: fail

4.5 EVM contract

Operations about the EVM contract, includes deployment, invoked, and query. The contract name is unique on the blockchain.

a. Initialize a EVM contract client

Initialize a client to operate the EVM contract. The other operation must use the client.

1.Function name

  • func InitEVMContract(account *account.Account, node, bcName, contractName, contractAccount string) *EVMContract

2.Parameters

params explanation Type
account user account *account.Account
node host of xchain net string
bcName blockchain name string
contractName contract name string
contractAccount contract account string

3.Returns

type explanation
*EVMContract client to operate the EVM contract

b. Deploy EVM contract

Deploy the wasm contract and return the transaction's id. You can alse use the function PreDeployWasmContract and PostWasmContract to deploy the contract.

1.Function name

  • func (c *EVMContract) Deploy(args map[string]string, bin, abi []byte) (string, error)

2.Parameters

params explanation Type
args contract init args map[string]string
bin EVM contract bin []byte
abi EVM contract abi []byte

3.Returns

Type explanation
string txid of the transaction of deploy contract
error
  • nil: success
  • non-nil: fail

c. Pre-execution of deploy EVM contract

Pre execute the deployment of the EVM contract, which you can get the gas of the deployment.

1.Function name

  • func (c EVMContract) PreDeployEVMContract(arg map[string]string, bin, abi []byte) (pb.PreExecWithSelectUTXOResponse, error)

2.Parameters

params explanation type
args contract init args map[string]string
bin EVM contract bin []byte
abi EVM contract abi []byte

3.Returns

type explanation
*pb.PreExecWithSelectUTXOResponse the result of the pre-execution of deploy contract
error
  • nil: success
  • non-nil: fail

d. Deploy contract by the result of the pre-execution

Execute by the result of the pre execution to deploy a EVM contract.

1.Function name

  • func (c *EVMContract) PostEVMContract(preExeWithSelRes *pb.PreExecWithSelectUTXOResponse, amount string) (string, error)

2.Parameters

params explanation type
preExeWithSelRes the result of the pre-execution *pb.PreExecWithSelectUTXOResponse

3.Reutrns

type explanation
string txid of the transaction of deploy contract
error nil:success;non-nil:fail

e.Invoke EVM contract

Invoke the EVM conrtact and return the transaction's id. You can alse use the function PreInvokeEVMContract and PostEVMContract to invoke the contract.

1.Function name

  • func (c *EVMContract) Invoke(methodName string, args map[string]string, amount string) (string, error)

2.Parameters

params explanation type
methodName conrtact method to invoke string
args method args map[string]string
amount the amount of transfer to contract string

3.Reutrns

type explanation
string txid of the transaction of invoke contract
error
  • nil: success
  • non-nil: fail

f. Pre-execution of invoke contract

Pre execute the invoking of the EVM contract, which you can get the gas of the invoking.

1.Function name

  • func (c EVMContract) PreInvokeEVMContract(methodName string, args map[string]string, amount string) (pb.PreExecWithSelectUTXOResponse, error)

2.Parameters

params explanation type
methodName conrtact method to invoke string
args method args map[string]string
amount the amount of transfer to contract string

3.Reutrns

type explanation
*pb.PreExecWithSelectUTXOResponse the result of the pre-execution of invoke contract
error
  • nil: success
  • non-nil: fail

g. Invoke contract by the result of the pre-execution

Execute by the result of the pre execution to invoke a EVM contract.

1.Function name

  • func (c *EVMContract) PostEVMContract(preExeWithSelRes *pb.PreExecWithSelectUTXOResponse, amount string) (string, error)

2.Parameters

params explanation type
preExeWithSelRes the result of the pre-execution *pb.PreExecWithSelectUTXOResponse
amount the amount of transfer to contract string

3.Reutrns

type explanation
string txid of the transaction of invoke contract
error
  • nil: success
  • non-nil: fail

h. Query contract

Query the conrtact ledger.

1.Function name

  • func (c EVMContract) Query(methodName string, args map[string]string) (pb.InvokeRPCResponse, error)

2.Parameters

params explanation type
methodName conrtact method to invoke string
args method args map[string]string

3.Reutrns

类型 explanation
*pb.PreExecWithSelectUTXOResponse the result of query contract
error
  • nil: success
  • non-nil: fail

5 Vocabulary

type explanation
account user on the blockchain,includes address,public and private key
contract account regulation is XC+16 numbers +@+ blockchain name,like: “XC1234567890123456@xuper”
transfer base transactions on the blockchain
contract user's application on the blockchain

6 Common problem

  • User A transfer 10 tokens to user B with the fee 5, why user A must pay more 10 tokens? Because the transaction must be checked by the standard which need 10 tokens.
Clone this wiki locally