Using ONT ID
Integrating ONT ID to centralized and decentralized systems
ONT ID can be integrated to centralized and decentralized systems alike to implement a decentralized identity and account mechanism with a rich variety of other functions. The Ontology framework is flexible in terms of the languages that are supported. There are several public SDKs that are available for the community to work and experiment with.
Developers can glance over ONT ID specifications to get a better understanding of the technical architecture.
The ONT ID protocol has been implemented on the Ontology chain using native smart contracts. API methods can be invoked to carry out ONT ID related actions such as registration, cancellation, attribute modification, etc. Follow the link below to navigate to the ONT ID contract API reference.
Integrating the ONT ID framework is a simple enough process. The major steps have been illustrated below.

Use OWallet tool to create a new wallet

OWallet is a wallet tool that can be used to work with Ontology wallets and carry out staking on the Ontology network. You can download the latest version of OWallet by following this link.
Download and install OWallet, and then in the main 'wallets' window click on the '+' icon. Follow the prompts to create a new Ontology wallet. You'll need this perform any interactions with the Ontology chain.
You'll be able to see your wallet address on the top after successfully creating your wallet and exporting the .dat wallet file.
We encourage and value any contributions that are made by community developers to the SDKs for other languages. Support for ONT ID 2.0 allows the developer community to integrate this safe and decentralized identity management protocol to the new applications swiftly and conveniently.

Fetch testnet ONG

Performing on-chain actions consumes ONG in the form of gas/transaction costs. Follow this link to apply for testnet ONG that will come in handy when developing on and working within the Ontology ecosystem. Use your wallet address to apply for testnet ONG tokens on the portal.

Set up SDK environment

Currently, the Java, Golang, and Typescript SDKs support the updated ONT ID 2.0 specifications. For the rest of the SDKs that for now support ONT ID 1.0 can be accessed using the link below.
After obtaining testnet ONG, you're all set to start working with the Ontology framework. The SDKs illustrated below can be used to implement ONT ID related functions. But first, we must set up the environment to use the SDK libraries in your project. Execute the commands specified to set up the SDK.

Golang SDK

Please ensure that you have the latest version of Go set up and running on your local machine.

1. Clone the SDK library

1
git clone https://github.com/ontio/ontology-go-sdk.git
Copied!

2. Install dependencies

Run the following command to enable Go modules in your environment in case they aren't already enabled.
1
export GO111MODULE="on"
Copied!
For Windows OS, configure the environment variables in system settings to enable Go modules.
And then run the following command to install the necessary dependencies.
1
go mod vendor
Copied!

Java SDK

Please confirm that you have the latest version of Java and Maven set up and running on your system.

1. Clone the SDK library

1
git clone https://github.com/ontio/ontology-java-sdk.git
Copied!

2. Install dependencies

1
mvn clean install
Copied!

TypeScript SDK

Please ensure that you have a NodeJS and TypeScript environment set up and running on your local system (we'll be using npm)

1. Clone the SDK library

1
git clone https://github.com/ontio/ontology-ts-sdk.git
Copied!

2. Install the necessary dependencies

1
npm install
Copied!

Initialize and invoke SDK

Once the environment is set up, next up would be initializing the respective SDK. The process has been briefly described individually for each SDK using the testing package that contains several useful demos for reference. Roughly speaking the sequence is as follows:
  1. 1.
    Instantiate and initialize the SDK
  2. 2.
    Create a wallet object that will be used when executing methods and making API calls
  3. 3.
    Create a new ONT ID linked to the account
  4. 4.
    Register the action on chain by storing the DID document into the contract
  5. 5.
    Add attributes if necessary
  6. 6.
    Fetch ONT ID and respective attribute related details
All the sample code used below is used for the purpose of illustration and has been taken from test or demo files that come with the SDK. The name of the file has also been specified with each code snippet.
Move the newly created wallet to the SDK main directory before proceeding to initialize the SDK

Go SDK

One way to initialize an SDK instance would be:
1
/* ontology-go-sdk/ont_sdk_test.go */
2
3
func Init() {
4
testOntSdk = NewOntologySdk()
5
testOntSdk.NewRpcClient().SetAddress("http://polaris1.ont.io") // Set RPC client address to testnet node address
6
var err error
7
var wallet *Wallet
8
if !common.FileExisted("./wallet.dat") {// Checks if a wallet exists in the main directory
9
fmt.Println("Wallet not found")
10
}
11
} else {
12
testWallet, err = testOntSdk.OpenWallet("./wallet.dat") // Imports and uses wallet for the SDK instance
13
if err != nil {
14
fmt.Println("[OpenWallet] error:", err)
15
return
16
}
17
}
18
}
Copied!
Next we can generate an ONT ID and start working with it. The sample code illustrates how to execute certain basic operations.
1
/* ontology-go-sdk/native_contract_test.go */
2
3
func TestOntId(t *testing.T) {
4
Init() // Initializing the SDK
5
6
/* Generating a new ONT ID */
7
8
testIdentity, err := testWallet.NewDefaultSettingIdentity(testPasswd) // Generating a new ONT ID with the default settings
9
if err != nil {
10
t.Errorf("TestOntId NewDefaultSettingIdentity error:%s", err)
11
return
12
}
13
_, err = testOntSdk.Native.OntId.RegIDWithPublicKey(testGasPrice, testGasLimit, testDefAcc, testIdentity.ID, testDefAcc) // Sends transaction to register ONT ID with the wallet account
14
if err != nil {
15
t.Errorf("TestOntId RegIDWithPublicKey error:%s", err)
16
return
17
}
18
testOntSdk.WaitForGenerateBlock(30 * time.Second) // Timeout till next block
19
20
/* Add attributes for the ONT ID */
21
22
attributes := []*DDOAttribute{ // Define DDO attributes for the ONT ID
23
&DDOAttribute{
24
Key: []byte("1"),
25
Value: []byte("2"),
26
ValueType: []byte("3"),
27
},
28
}
29
30
/* Add attributes to the DDO document in the ONT ID contract on chain */
31
32
_, err = testOntSdk.Native.OntId.AddAttributesByIndex(testGasPrice, testGasLimit, testDefAcc, testIdentity.ID, attributes, 1, testDefAcc) // Sending the transaction
33
if err != nil {
34
t.Errorf("TestOntId AddAttributesByIndex error:%s", err)
35
return
36
}
37
testOntSdk.WaitForGenerateBlock(30 * time.Second) // Timeout till next block
38
39
/* Fetch details for particular attribute */
40
41
attribute, err := testOntSdk.Native.OntId.GetAttributeByKey(testIdentity.ID, "1") // Method call to pass the attribute key
42
if err != nil {
43
t.Errorf("TestOntId GetAttributeByKey error:%s", err)
44
return
45
}
46
fmt.Printf("TestOntId GetAttributeByKey:%+v\n", attribute)
47
48
/* Fetch DDO for particular ONT ID */
49
50
document, err := testOntSdk.Native.OntId.GetDocumentJson(testIdentity.ID) // Method call to pass the ONT ID
51
if err != nil {
52
t.Errorf("TestOntId GetDocumentJson error:%s", err)
53
return
54
}
55
fmt.Printf("TestOntId GetDocumentJson:%+v\n", string(document))
56
return
57
}
Copied!
The addresses for the currently active Polaris testnet nodes can be found here.
For a more detailed and practical test case, you can refer to cred_test.go.
Follow this link to find the Go SDK reference on Github.

Java SDK

To instantiate and initialize an SDK object:
1
/* src/test/java/com/github/ontio/smartcontract/nativevm/NativeOntIdTxTest.java */
2
3
public void setUp() throws Exception {
4
ontSdk = OntSdk.getInstance();
5
// Set testnet node URL
6
ontSdk.setRestful(OntSdkTest.URL);
7
ontSdk.setDefaultConnect(ontSdk.getRestful());
8
// Open wallet with SDK object
9
ontSdk.openWalletFile(walletFile);
10
// ontSdk.setSignatureScheme(SignatureScheme.SHA256WITHECDSA);
11
payer = new Account(SignatureScheme.SHA256WITHECDSA);
12
payerAcct = payer;
13
// Generate ONT ID
14
identity = ontSdk.getWalletMgr().createIdentity(password);
15
account = new com.github.ontio.account.Account(SignatureScheme.SHA256WITHECDSA);
16
// Record action on chain
17
// ontSdk.nativevm().ontId().sendRegister(identity,password,payerAcct,ontSdk.DEFAULT_GAS_LIMIT,0);
18
Thread.sleep(6000);
19
20
}
Copied!
The above method is defined in the NativeOntIdTest class. You can refer to the source file and run the test respective test cases.
Sample code that illustrates basic operations:
1
/* src/test/java/com/github/ontio/smartcontract/nativevmNativeOntIdTxTest.java */
2
3
public void sendRegister() throws Exception {
4
5
// Record ONT ID allocation action on chain
6
Transaction tx = ontSdk.nativevm().ontId().makeRegister(identity.ontid, account.serializePublicKey(), payer.getAddressU160().toBase58(), ontSdk.DEFAULT_GAS_LIMIT, 0);
7
ontSdk.addSign(tx, account);
8
ontSdk.addSign(tx, payerAcct);
9
ontSdk.getConnect().sendRawTransaction(tx);
10
11
Identity identity2 = ontSdk.getWalletMgr().createIdentity(password);
12
13
ontSdk.nativevm().ontId().sendRegister(identity2.ontid, account, payerAcct, ontSdk.DEFAULT_GAS_LIMIT, 0);
14
15
//Adding attributes to an ONT ID
16
Identity identity3 = ontSdk.getWalletMgr().createIdentity(password);
17
Attribute[] attributes = new Attribute[1];
18
attributes[0] = new Attribute("key2".getBytes(), "value2".getBytes(), "type2".getBytes());
19
ontSdk.nativevm().ontId().sendRegisterWithAttrs(identity3.ontid, attributes, account, payerAcct, ontSdk.DEFAULT_GAS_LIMIT, 0);
20
21
Thread.sleep(6000);
22
23
//Fetch DDO object from contract
24
String ddo = ontSdk.nativevm().ontId().sendGetDDO(identity.ontid);
25
Assert.assertTrue(ddo.contains(identity.ontid));
26
27
String dd02 = ontSdk.nativevm().ontId().sendGetDDO(identity3.ontid);
28
Assert.assertTrue(dd02.contains("key2"));
29
30
String keystate = ontSdk.nativevm().ontId().sendGetKeyState(identity.ontid, 1);
31
Assert.assertNotNull(keystate);
32
33
//merkleproof
34
Object merkleproof = ontSdk.nativevm().ontId().getMerkleProof(tx.hash().toHexString());
35
boolean b = ontSdk.nativevm().ontId().verifyMerkleProof(JSONObject.toJSONString(merkleproof));
36
Assert.assertTrue(b);
37
38
//claim
39
Map<String, Object> map = new HashMap<String, Object>();
40
map.put("Issuer", identity.ontid);
41
map.put("Subject", identity2.ontid);
42
43
Map clmRevMap = new HashMap();
44
clmRevMap.put("typ", "AttestContract");
45
clmRevMap.put("addr", identity.ontid.replace(Common.didont, ""));
46
47
String claim = ontSdk.nativevm().ontId().createOntIdClaim(identity.ontid, account, "claim:context", map, map, clmRevMap, System.currentTimeMillis() / 1000 + 100000);
48
boolean b2 = ontSdk.nativevm().ontId().verifyOntIdClaim(claim);
49
Assert.assertTrue(b2);
50
}
Copied!
You can refer to the NativeOntIdTxTest.java in the test directory of the SDK to find and experiment with the test class methods.
Follow this link to find the Java SDK reference on Github.

TypeScript SDK

1
/* test/newOntidContractTxBuilder.test.ts */
2
3
// Generate ONT ID and send a transaction to record action on chain
4
test('buildRegIDWithPublicKeyTx', async () => {
5
const tx = NewOntidTxBuilder.buildRegIDWithPublicKeyTx(did1, pk1, gasPrice, gasLimit, address1);
6
signTransaction(tx, privateKey1);
7
const res = await socketClient.sendRawTransaction(tx.serialize(), false, true);
8
console.log(res);
9
expect(res.Error).toEqual(0);
10
}, 100000);
11
12
// Add attributes to an ONT ID document
13
test('buildAddAttributeTx', async () => {
14
const attr = new DDOAttribute();
15
attr.key = 'hello2';
16
attr.type = 'string',
17
attr.value = 'world2';
18
const tx = NewOntidTxBuilder.buildAddAttributeTx(did4, [attr], pk4, gasPrice, gasLimit, address4);
19
signTransaction(tx, pri4);
20
const res = await socketClient.sendRawTransaction(tx.serialize(), false, true);
21
console.log(res);
22
expect(res.Error).toEqual(0);
23
}, 100000);
24
25
// Fetch attribute information
26
test('buildGetAttributesTx', async () => {
27
const tx = NewOntidTxBuilder.buildGetAttributesTx(did4);
28
const res = await socketClient.sendRawTransaction(tx.serialize(), true);
29
console.log(res);
30
expect(res.Error).toEqual(0);
31
}, 100000);
32
33
// Fetch document information
34
test('buildGetDocumentTx', async () => {
35
const ontid = 'did:ont:AN3iwgee5JKzZV99gknpdmQf5XUJJbQ7xQ';
36
const doc = await NewOntidTxBuilder.getDocumentJson(ontid, 'http://polaris1.ont.io:20334');
37
console.log(doc);
38
}, 100000);
Copied!
Follow this link to find the TypeScript SDK reference on Github.
A wide variety of functions operations can be performed with ONT ID by calling the public API exposed from the native contract deployed on the Ontology chain. The API reference for the contract and the chain itself is available here.
Last modified 6mo ago