Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Api developer onboard #129

Open
wants to merge 15 commits into
base: develop
Choose a base branch
from
2 changes: 2 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ plugins:
spec: "@yarnpkg/plugin-workspace-tools"

yarnPath: .yarn/releases/yarn-3.3.1.cjs


9 changes: 7 additions & 2 deletions demo/src/bench.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as Cord from '@cord.network/sdk'
import moment from 'moment'
import Keyring from '@polkadot/keyring'
import { Crypto } from '@cord.network/utils'
import { Crypto, cordApiTx } from '@cord.network/utils'

export const sleep = (ms: number): Promise<void> => {
return new Promise((resolve) => {
Expand Down Expand Up @@ -74,7 +74,12 @@ async function main() {
let BatchAuthor = keyring.addFromUri('//Charlie')
let batchAncStartTime = moment()
try {
api.tx.utility.batchAll(tx_batch).signAndSend(BatchAuthor)
const tx = api.tx.utility.batchAll(tx_batch)
const value = await cordApiTx(tx, 'signAndSend')

if (!value) {
api.tx.utility.batchAll(tx_batch).signAndSend(BatchAuthor)
}
} catch (e: any) {
console.log(e.errorCode, '-', e.message)
}
Expand Down
9 changes: 7 additions & 2 deletions demo/src/demo-score-batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import moment from 'moment'
import Keyring from '@polkadot/keyring'
import { ApiPromise, WsProvider } from '@polkadot/api'
import { ScoreType } from '@cord.network/types'
import { UUID } from '@cord.network/utils'
import { UUID, cordApiTx } from '@cord.network/utils'

export const sleep = (ms: number): Promise<void> => {
return new Promise((resolve) => {
Expand Down Expand Up @@ -184,7 +184,12 @@ async function main() {
}
}
try {
api.tx.utility.batchAll(txBatch).signAndSend(batchTransactionAuthor)
const tx = api.tx.utility.batchAll(txBatch)
const value = await cordApiTx(tx, 'signAndSend')

if (!value) {
api.tx.utility.batchAll(txBatch).signAndSend(batchTransactionAuthor)
}
} catch (e: any) {
console.log(e.errorCode, '-', e.message)
}
Expand Down
2 changes: 0 additions & 2 deletions demo/src/demo-sparknet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ import { randomUUID } from 'crypto'
import { decryptMessage } from './utils/decrypt_message'
import { encryptMessage } from './utils/encrypt_message'
import { generateRequestCredentialMessage } from './utils/request_credential_message'
import { getChainCredits, addAuthority } from './utils/createAuthorities'
import { createAccount } from './utils/createAccount'

function getChallenge(): string {
return Cord.Utils.UUID.generate()
Expand Down
36 changes: 10 additions & 26 deletions demo/src/demo-staging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ function getChallenge(): string {
}

async function main() {
//const networkAddress = 'ws://127.0.0.1:9944'
const networkAddress = 'wss://staging.cord.network'
Cord.ConfigService.set({ submitTxResolveOn: Cord.Chain.IS_IN_BLOCK })
const networkAddress = 'ws://127.0.0.1:9944'
//const networkAddress = 'wss://staging.cord.network'
Cord.ConfigService.set({
submitTxResolveOn: Cord.Chain.IS_IN_BLOCK,
})
await Cord.connect(networkAddress)

// Step 1: Setup Authority
Expand All @@ -40,8 +42,11 @@ async function main() {
'//Alice',
'sr25519'
)
console.log("Alice (AuthorIdentity for this run): ", authorityAuthorIdentity.address);

console.log(
'Alice (AuthorIdentity for this run): ',
authorityAuthorIdentity.address
)

// Step 2: Setup Identities
console.log(`\n❄️ Demo Identities (KeyRing)`)

Expand Down Expand Up @@ -244,27 +249,6 @@ async function main() {
} else {
console.log('✅ Verification failed! 🚫')
}

console.log(`\n❄️ Messaging `)
const schemaId = Cord.Schema.idToChain(schema.$id)
console.log(' Generating the message - Sender -> Receiver')
const message = await generateRequestCredentialMessage(
holderDid.uri,
verifierDid.uri,
schemaId
)

console.log(' Encrypting the message - Sender -> Receiver')
const encryptedMessage = await encryptMessage(
message,
holderDid.uri,
verifierDid.uri,
holderKeys.keyAgreement
)

console.log(' Decrypting the message - Receiver')
await decryptMessage(encryptedMessage, verifierKeys.keyAgreement)

// Step 7: Revoke a Credential
console.log(`\n❄️ Revoke credential - ${document.identifier}`)
await revokeCredential(
Expand Down
18 changes: 14 additions & 4 deletions demo/src/utils/generateDid.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as Cord from '@cord.network/sdk'
import { mnemonicGenerate } from '@polkadot/util-crypto'
import { generateKeypairs } from './generateKeypairs'
import { hexToU8a } from '@polkadot/util'
import { cord_api_query } from '@cord.network/config'

/**
* It creates a DID on chain, and returns the mnemonic and DID document
Expand Down Expand Up @@ -48,12 +50,20 @@ export async function createDid(
await Cord.Chain.signAndSubmitTx(didCreationTx, submitterAccount)

const didUri = Cord.Did.getDidUriFromKey(authentication)
const encodedDid = await api.call.didApi.query(Cord.Did.toChain(didUri))
const { document } = Cord.Did.linkedInfoFromChain(encodedDid)

let document: any

document = await cord_api_query('did', 'query', didUri)

if (!document || !document.response) {
const encodedDid = await api.call.didApi.query(Cord.Did.toChain(didUri))
document = Cord.Did.linkedInfoFromChain(encodedDid)
} else {
document = Cord.Did.linkedInfoFromApi(document.response)
}

if (!document) {
throw new Error('DID was not successfully created.')
}

return { mnemonic, document: document }
return { mnemonic, document: document?.document }
}
13 changes: 7 additions & 6 deletions demo/src/utils/queryDidName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ export async function getDidDocFromName(

// Query the owner of the provided didName.
const encodedDidNameOwner = await api.call.didApi.queryByName(didName)
if (encodedDidNameOwner.isSome) {
const {
document: { uri },
} = Cord.Did.linkedInfoFromChain(encodedDidNameOwner)

const {
document: { uri },
} = Cord.Did.linkedInfoFromChain(encodedDidNameOwner)

console.log(` uri: ${uri}`)
console.log('✅ DID name resolved!')
console.log(` uri: ${uri}`)
console.log('✅ DID name resolved!')
}
}
20 changes: 14 additions & 6 deletions demo/src/utils/verifyPresentation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as Cord from '@cord.network/sdk'
import { cord_api_query } from '@cord.network/config'

/**
* It verifies a presentation by checking the stream on the blockchain and verifying the presentation
Expand All @@ -18,25 +19,32 @@ export async function verifyPresentation(
} = {}
): Promise<boolean> {
try {
let stream: any
// Verify the presentation with the provided challenge.
await Cord.Document.verifyPresentation(presentation, { challenge })

// Verify the credential by checking the stream on the blockchain.

const api = Cord.ConfigService.get('api')
const chainIdentifier = Cord.Stream.idToChain(presentation.identifier)
const streamOnChain = await api.query.stream.streams(chainIdentifier)
const stream = Cord.Stream.fromChain(streamOnChain, chainIdentifier)
if (stream.streamHash !== presentation.documentHash) {

stream = await cord_api_query('stream', 'streams', chainIdentifier)

if (!stream) {
const streamOnChain = await api.query.stream.streams(chainIdentifier)
stream = Cord.Stream.fromChain(streamOnChain, chainIdentifier)
}
if (stream.revoked) {
return false
}
const attestationOnChain = await api.query.stream.attestations(chainIdentifier, presentation.documentHash)
const attest = Cord.Stream.fromChainAttest(attestationOnChain, chainIdentifier)
if (attest.revoked) {
return false
}

return trustedIssuerUris.includes(attest.creator)
} catch {
return trustedIssuerUris.includes(stream.issuer)
} catch (err: any) {
console.log(err);
return false
}
}
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@
"typedoc": "^0.23.0",
"typescript": "^4.8.3"
},
"version": "0.8.0-7",
"packageManager": "[email protected]"
"version": "0.9.0-1",
"packageManager": "[email protected]",
"dependencies": {
"node-fetch": "^3.3.1"
}
}
2 changes: 1 addition & 1 deletion packages/augment-api/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cord.network/augment-api",
"version": "0.8.0-3",
"version": "0.8.1-beta.6",
"description": "",
"types": "./lib/index.d.ts",
"type": "module",
Expand Down
2 changes: 1 addition & 1 deletion packages/config/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cord.network/config",
"version": "0.8.0-3",
"version": "0.8.1-beta.6",
"description": "",
"type": "commonjs",
"main": "./lib/index.js",
Expand Down
8 changes: 8 additions & 0 deletions packages/config/src/ConfigService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
import { SDKErrors } from '@cord.network/utils'
import { SubscriptionPromise } from '@cord.network/types'

const { CORD_WSS_URL, CORD_API_URL, CORD_API_TOKEN } = process.env

const DEFAULT_DEBUG_LEVEL =
typeof process !== 'undefined' &&
process.env?.DEBUG &&
Expand All @@ -30,6 +32,9 @@ export type configOpts = {
api: ApiPromise
logLevel: LogLevel
submitTxResolveOn: SubscriptionPromise.ResultEvaluator
apiUrl: string | null
wssUrl: string | null
token: string | null
} & { [key: string]: any }

/**
Expand All @@ -52,6 +57,9 @@ export function modifyLogLevel(level: LogLevel): LogLevel {

const defaultConfig: Partial<configOpts> = {
logLevel: DEFAULT_DEBUG_LEVEL,
apiUrl: CORD_API_URL ?? null,
wssUrl: CORD_WSS_URL ?? null,
token: CORD_API_TOKEN ?? null,
}

let configuration: Partial<configOpts> = { ...defaultConfig }
Expand Down
76 changes: 76 additions & 0 deletions packages/config/src/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import fetch from 'node-fetch'
import * as ConfigService from './ConfigService'
import type { SubmittableExtrinsic } from '@cord.network/types'

export async function cord_api_query(
modules: any,
section: any,
identifier: any
) {
const url = ConfigService.get('apiUrl')
const token = ConfigService.get('token')

if (!url || !token) {
throw Error('Missing token')
}

try {
const cordApiUrl = `${url}/api/v1/query/${modules}/${section}/${identifier}`

const resp = await fetch(cordApiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
})

if (resp.status === 403) {
throw Error('Invalid token')
}
// if (resp.status !== 200) {
// throw Error('missing resp')
// }

const data = await resp.json()
return data
} catch (error) {
throw Error('Invalid response ')
}
}

export async function cordApiTx(tx: SubmittableExtrinsic, modules: any) {
const url = ConfigService.get('apiUrl')
const token = ConfigService.get('token')

if (!url || !token) {
throw Error('Missing token')
}

try {
const cordApiUrl = `${url}/api/v1/${modules}/extrinsic`

const submit = await fetch(cordApiUrl, {
body: JSON.stringify({
extrinsic: tx.toHex(),
}),
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
})

if (submit.status === 403) {
throw Error('Invalid token')
}
// if (submit.status !== 200) {
// throw Error('missing resp')
// }

const data = await submit.json()
return data
} catch (error) {
throw Error('Invalid response ')
}
}
1 change: 1 addition & 0 deletions packages/config/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * as ConfigService from './ConfigService.js'
export { cord_api_query, cordApiTx } from './helper.js'
2 changes: 1 addition & 1 deletion packages/did/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cord.network/did",
"version": "0.8.0-3",
"version": "0.8.1-beta.6",
"description": "",
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
Expand Down
18 changes: 15 additions & 3 deletions packages/did/src/Did.chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ import type {
VerificationKeyRelationship,
} from '@cord.network/types'
import { verificationKeyTypes } from '@cord.network/types'
import { Crypto, SDKErrors, ss58Format } from '@cord.network/utils'
import { ConfigService } from '@cord.network/config'
import {
Crypto,
SDKErrors,
ss58Format,
} from '@cord.network/utils'
import { ConfigService, cord_api_query } from '@cord.network/config'
import type {
PalletDidDidDetails,
PalletDidDidDetailsDidAuthorizedCallOperation,
Expand Down Expand Up @@ -433,6 +437,14 @@ export async function generateDidAuthenticatedTx({
blockNumber,
}: AuthorizeCallInput & SigningOptions): Promise<SubmittableExtrinsic> {
const api = ConfigService.get('api')
let number: any

number = await cord_api_query('system', 'section', 'number')

if (!number) {
number = await api.query.system.number()
}

const signableCall =
api.registry.createType<PalletDidDidDetailsDidAuthorizedCallOperation>(
api.tx.did.submitDidCall.meta.args[0].type.toString(),
Expand All @@ -441,7 +453,7 @@ export async function generateDidAuthenticatedTx({
did: toChain(did),
call,
submitter,
blockNumber: blockNumber ?? (await api.query.system.number()),
blockNumber: blockNumber ?? number,
}
)
const signature = await sign({
Expand Down
Loading
Loading