Reference(Go)

Develop reference for golang SDK

Developers can use the Chain Connector to connect to the Gateway of the blockchain, perform various operations, and access the data in the chain.

The GIT repository of Chain Connector for Golang: https://github.com/taiyi-io/chain-connector-go

Please compiles with go version 1.18 or above

Assume the application already has sufficient privileges and a private access token stored in the file “token.json”.

Use the following code to create a connector and connect to the access gateway “1.2.3.4:9090”

import sdk "github.com/taiyi-io/chain-connector-go"

var targetPath = "./token.json" 
connector, err := sdk.NewconnectorFromFile(targetPath)
if err != nil{
    log.fatalf("load connector fail: %s", err.Error())
    return
}
var gatewayHost = "1.2.3.4"
var gatewayPort = 9090
err = connector.Connect(gatewayHost, gatewayPort)
if err != nil{
    log.fatalf("connect gateway fail: %s", err.Error())
    return
}

The application could use the connector object to access all functions when created.

Schema

Check Schema

Check whether the specified schema exists

var schemaName = "sample"
exists, err := connector.HasSchema(schemaName)
if err != nil{
    log.fatalf("check schema fail: %s", err.Error())
    return
}
if exists {
    log.printf("schema '%s' exists", schemaName)
}else{
    log.printf("schema '%s' not exists", schemaName)
}

Create Schema

Create a new schema using name and properties.

var schemaName = "person"
var properties = []DocumentProperty{
    	{
			Name: "name",
			Type: PropertyTypeString,
		},
		{
			Name: "age",
			Type: PropertyTypeInteger,
		},
		{
			Name: "is_male",
			Type: PropertyTypeBoolean,
		},
}
if err = connector.CreateSchema(schemaName, properties); err != nil {
    log.fatalf("create schema fail: %s", err.Error())
    return
}
log.printf("schema '%s' creaeted", schemaName)

Update Schema

Update the property list of a schema.

var schemaName = "person"
var properties = []DocumentProperty{
    	{
			Name: "name",
			Type: PropertyTypeString,
		},
		{
			Name: "age",
			Type: PropertyTypeInteger,
		},
		{
			Name: "gender",
			Type: PropertyTypeString,
		},
}
if err = connector.UpdateSchema(schemaName, properties); err != nil {
    log.fatalf("update schema fail: %s", err.Error())
    return
}
log.printf("schema '%s' updated", schemaName)

Delete Schema

Delete the specified schema

var schemaName = "target"
err := connector.DeleteSchema(schemaName)
if err != nil{
    log.fatalf("delete schema fail: %s", err.Error())
    return
}
log.printf("schema '%s' deleted", schemaName)

Get Schema

Get the specified schema

var schemaName = "target"
schema, err := connector.GetSchema(schemaName)
if err != nil{
    log.fatalf("get schema fail: %s", err.Error())
    return
}

Get Schema Log

Get the change logs of a schema

var schemaName = "target"
version, logs, err := connector.GetSchemaLog(schemaName)
if err != nil{
    log.fatalf("get schema log fail: %s", err.Error())
    return
}

Query Schemas

Query schemas using pagination mode.

const offset = 9
const recordPerPage = 20
names, offset, limit, total, err := connector.QuerySchemas(offset, recordPerPage)
if err != nil{
    log.fatalf("query schemas fail: %s", err.Error())
    return
}
log.printf("%d / %d schemas returned", len(names), total)

Digital Asset

Check Asset

Check whether the specified digital asset exists

const schemaName = "person"
const docID = "alice"
exists, err := connector.HasDocument(schemaName, docID)
if err != nil{
    log.fatalf("check document fail: %s", err.Error())
    return
}
if exists {
    log.printf("document '%s.%s' exists", schemaName, docID)
}else{
    log.printf("document '%s.%s' not exists", schemaName, docID)
}

Add Asset

Creates a digital asset using the specified identity and document content. If identity is omitted, it will be generated automatically.

const schemaName = "person"
const content = "{'name': 'alice', 'age': 18, 'career': 'nurse'}"
docID, err := connector.AddDocument(schemaName, "", content)
if err != nil{
    log.fatalf("add document fail: %s", err.Error())
    return
}
log.printf("document %s added", docID)

Update Asset

Update the document content of the specified digital asset

const schemaName = "person"
const docID = "alice"
const content = "{'name': 'alice', 'age': 28, 'career': 'doctor'}"
err := connector.UpdateDocument(schemaName, docID, content)
if err != nil{
    log.fatalf("update document fail: %s", err.Error())
    return
}
log.printf("document %s updated", docID)

Update Asset Property

Update the specified property value of a digital asset.

const schemaName = "person"
const docID = "alice"
const propertyName = "age"
err := connector.UpdateDocumentProperty(schemaName, docID, propertyName, PropertyTypeInteger, "18")
if err != nil{
    log.fatalf("update document property fail: %s", err.Error())
    return
}
log.printf("property of document %s updated", docID)

Remove Asset

Remove the specified digital asset.

const schemaName = "person"
const docID = "bob"
err := connector.RemoveDocument(schemaName, docID)
if err != nil{
    log.fatalf("remove document fail: %s", err.Error())
    return
}
log.printf("document '%s.%s' removed", schemaName, docID)

Get Asset

Gets the document content of the specified digital asset

const schemaName = "person"
const docID = "alice"
content, err := connector.GetDocument(schemaName, docID)
if err != nil{
    log.fatalf("get document fail: %s", err.Error())
    return
}
log.printf("document '%s.%s' fetched", schemaName, docID)

Query Asset

Query digital assets using pagination mode.

const beginOffset = 9
const recordPerPage = 20
const schemaName = "person"
//查询条件
var condition QueryCondition
condition.
    MaxRecord(recordPerPage).
    SetOffset(beginOffset).
    PropertyGreaterOrEqual("age", "18").
    PropertyEqual("gender", "female")

documents, limit, offset, total, err := connector.QueryDocuments(schemaName, condition)
if err != nil{
    log.fatalf("query documents fail: %s", err.Error())
    return
}
log.printf("%d / %d documents returned", len(documents), total)

Get Change Log

Gets the change logs of a digital asset

const schemaName = "person"
const docID = "alice"
version, records, err := connector.GetDocumentLog(schemaName, docID)
if err != nil{
    log.fatalf("get document log fail: %s", err.Error())
    return
}
log.printf("document '%s.%s' log fetched", schemaName, docID)

Smart Contract

Check Contract

Check if contract exists

const contractName = "new_car"
exists, err := connector.HasContract(contractName)
if err != nil{
    log.fatalf("check contract fail: %s", err.Error())
    return
}
if exists {
    log.printf("contract '%s' exists", contractName)
}else{
    log.printf("contract '%s' not exists", contractName)
}

Deploy Contract

Smart contracts are identified by name.

Assign name and definition to deploy, create a new one, or update existing contract if it exists.

var define = ContractDefine{
    Steps: []ContractStep{
        {
            Action: "create_doc",
            Params: []string{"sample", "@1", "@2"},
        },
        {
            Action: "set_property",
            Params: []string{"sample", "catalog", "car"},
        },
        {
            Action: "set_property",
            Params: []string{"sample", "price", "556.50"},
        }, 
        {
            Action: "set_property",
            Params: []string{"sample", "color", "black"},
        },
        {
            Action: "update_doc",
            Params: []string{"@1", "sample"},
        },
        {
            Action: "submit",
        },
    },
}
const contractName = "new_car"
if err := connector.DeployContract(contractName, createContract); err != nil {
	log.fatalf("deploy contract fail: %s", err.Error())
    return
}
log.printf("smart contract '%s' deployed", contractName)

Withdraw Contract

Revoke a smart contract with a specified name that can not be accessed later.

const contractName = "new_car"
if err := connector.WithdrawContract(contractName); err != nil {
	log.fatalf("withdraw contract fail: %s", err.Error())
    return
}
log.printf("smart contract '%s' withdrew", contractName)

Call Contract

Execute the contract using name and parameters.

var parameters = []string{
    "alice",
    "18",
    "blonde",
}
const contractName = "update_profile"
if err := connector.CallContract(contractName, parameters); err != nil {
	log.fatalf("call contract fail: %s", err.Error())
    return
}
log.println("call contract success")

Enable Contract Trace

Enable the tracking of a contract to inspect execution.

const contractName = "some_contract"
if err := connector.EnableContractTrace(contractName, parameters); err != nil {
	log.fatalf("enable contract trace fail: %s", err.Error())
    return
}
log.println("contract trace enabled")

Disable Contract Trace

Disable the tracking of a contract to hide execution debugging.

const contractName = "some_contract"
if err := connector.DisableContractTrace(contractName, parameters); err != nil {
	log.fatalf("disable contract trace fail: %s", err.Error())
    return
}
log.println("contract trace disabled")

Blockchain

Query Block List

Query the list of blocks in the specified height range.

const startHeight = 20
const endHeight = 40
idList, currentHeight, err := connector.QueryBlocks(startHeight, endHeight)
if err != nil{
    log.fatalf("query blocks fail: %s", err.Error())
    return
}
log.printf("%d block(s) available, current height %d", len(idList), currentHeight)

Get Block Data

Get block data by ID.

const blockID = "abcdxxx..."
blockData, err := connector.GetBlock(blockID)
if err != nil{
    log.fatalf("get block fail: %s", err.Error())
    return  
}
log.println("get block success")

Query Transaction List

Query transaction list of a block using pagination mode.

const blockID = "abcdxxx..."
const startOffset = 15
const recordPerPage = 30
idList, offset, limit, total, err := connector.QueryTransactions(blockID, startOffset, recordPerPage)
if err != nil{
    log.fatalf("query transactions fail: %s", err.Error())
    return  
}
log.println("query transactions success")

Get Transaction Data

Get detailed data on a transaction.

const blockID = "abcdxxx..."
const transID = "H123bb2"
transaction, err := connector.GetTransaction(blockID, transID)
if err != nil{
    log.fatalf("get transaction fail: %s", err.Error())
    return  
}
log.println("get transaction success")