Skip to content

Commit

Permalink
Fix examples
Browse files Browse the repository at this point in the history
  • Loading branch information
limemloh committed Sep 28, 2023
1 parent f939478 commit a1edc78
Show file tree
Hide file tree
Showing 12 changed files with 153 additions and 103 deletions.
34 changes: 33 additions & 1 deletion docs/pages/misc-pages/upgrade-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,39 @@ converting the type:
- To construct the type use `ContractAddress.create(index, subindex)`.
- `CredentialRegistrationId` is now a module with functions related to credential registration IDs:
- To refer to `CredentialRegistrationId` as a type use `CredentialRegistrationId.Type`.
- Constructing `new CredentialRegistrationId("<hex-string>")` is now `CredentialRegistrationId.fromHexString("<hex-string>")`.
- Constructing `new CredentialRegistrationId("<hex-string>")` is now
`CredentialRegistrationId.fromHexString("<hex-string>")`.
- `Duration` is now a module with functions related to durations of time.
- To refer to `Duration` as a type use `Duration.Type`.
- `Timestamp` is now a module with functions related to timestamps.
- To refer to `Timestamp` as a type use `Timestamp.Type`.

The API now uses dedicated types instead of language primitives:

- Uses `AccountAddress` instead of a string with base58 encoding.
Can be constructed using `AccountAddress.fromBase58('<base58>')`.
- Uses `BlockHash` instead of a string with hex encoding.
Can be constructed using `BlockHash.fromHexString('<hex>')`.
- Uses `TranactionHash` instead of a string with hex encoding.
Can be constructed using `TransactionHash.fromHexString('<hex>')`.
- Uses `Energy` instead of a bigint.
Can be constructed using `Energy.create(<integer>)`.
- Uses `ReceiveName` instead of a string.
Can be constructed using `ReceiveName.fromString('<contract>.<function>')`.
- Uses `InitName` instead of a string.
Can be constructed using `Init.fromString('init_<contract>')`.
- Uses `ContractName` instead of a string.
Can be constructed using `ContractName.fromString('<contract>')`.
- Uses `EntrypointName` instead of a string.
Can be constructed using `EntrypointName.fromString('<function>')`.
- Uses `Parameter` instead of a string with hex encoding.
Can be constructed using `Parameter.fromHexString('<hex>')`.
- Uses `SequenceNumber` (formerly called nonce) instead of a bigint.
Can be constructed using `SequenceNumber.create(<integer>)`.
- Uses `Timestamp` instead of a bigint.
Can be constructed using `Timestamp.fromMillis(<integer>)`.
- Uses `Duration` instead of a bigint.
Can be constructed using `Duration.fromMillis(<integer>)`.

### Web

Expand Down
11 changes: 8 additions & 3 deletions examples/client/invokeContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
ContractTraceEvent,
Energy,
Parameter,
ReceiveName,
ReturnValue,
createConcordiumClient,
} from '@concordium/node-sdk';
import { credentials } from '@grpc/grpc-js';
Expand Down Expand Up @@ -110,7 +112,7 @@ const client = createConcordiumClient(
const contract = ContractAddress.create(cli.flags.contract);
const context: ContractContext = {
// Required
method: cli.flags.receive,
method: ReceiveName.fromString(cli.flags.receive),
contract,
// Optional
invoker,
Expand All @@ -132,9 +134,12 @@ const client = createConcordiumClient(
} else if (result.tag === 'success') {
console.log('Invoke was succesful');

const returnValue: string | undefined = result.returnValue; // If the invoked method has return value
const returnValue = result.returnValue; // If the invoked method has return value
if (returnValue) {
console.log('The return value of the invoked method:', returnValue);
console.log(
'The return value of the invoked method:',
ReturnValue.toHexString(returnValue)
);
}

const events: ContractTraceEvent[] = result.events;
Expand Down
2 changes: 1 addition & 1 deletion examples/composed-examples/findAccountCreationBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ const client = createConcordiumClient(
for await (const summary of summaries) {
if (
summary.type === 'accountCreation' &&
summary.address === account.address
AccountAddress.equals(summary.address, account)
) {
console.log(
'Hash of transaction that created the account:',
Expand Down
26 changes: 14 additions & 12 deletions examples/composed-examples/initAndUpdateContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ import {
parseWallet,
buildAccountSigner,
affectedContracts,
ContractName,
ReceiveName,
Energy,
EntrypointName,
ReturnValue,
} from '@concordium/node-sdk';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
Expand Down Expand Up @@ -78,9 +83,9 @@ const client = createConcordiumClient(
const moduleRef = new ModuleReference(
'44434352ddba724930d6b1b09cd58bd1fba6ad9714cf519566d5fe72d80da0d1'
);
const maxCost = 30000n;
const contractName = 'weather';
const receiveName = 'weather.set';
const maxCost = Energy.create(30000);
const contractName = ContractName.fromStringUnchecked('weather');
const receiveName = ReceiveName.fromStringUnchecked('weather.set');
const schema = await client.getEmbeddedSchema(moduleRef);

// --- Initialize Contract --- //
Expand Down Expand Up @@ -148,7 +153,7 @@ const client = createConcordiumClient(

const updateParams = serializeUpdateContractParameters(
contractName,
'set',
EntrypointName.fromString('set'),
rainyWeather,
schema
);
Expand Down Expand Up @@ -191,21 +196,18 @@ const client = createConcordiumClient(
const contextPostInit: ContractContext = {
contract: unwrap(contractAddress),
invoker: sender,
method: 'weather.get',
method: ReceiveName.fromString('weather.get'),
};

const invokedPostInit = await client.invokeContract(contextPostInit);

if (invokedPostInit.tag === 'success') {
const rawReturnValue = Buffer.from(
unwrap(invokedPostInit.returnValue),
'hex'
);
const rawReturnValue = unwrap(invokedPostInit.returnValue);
const returnValue = deserializeReceiveReturnValue(
rawReturnValue,
ReturnValue.toBuffer(rawReturnValue),
schema,
'weather',
'get'
contractName,
EntrypointName.fromString('get')
);
console.log('\nThe weather is now:');
console.dir(returnValue, { depth: null, colors: true });
Expand Down
4 changes: 2 additions & 2 deletions examples/composed-examples/listNumberAccountTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const client = createConcordiumClient(
// For each transaction in the block:
trxLoop: for await (const trx of trxStream) {
if (isTransferLikeSummary(trx)) {
const trxAcc = AccountAddress.fromBase58(trx.sender);
const trxAcc = trx.sender;

// Loop over account dictionary entries to check if account
// is already in dictionary:
Expand All @@ -102,7 +102,7 @@ const client = createConcordiumClient(
}

// If account is not in dictionary, then add it:
dict[trx.sender] = 1;
dict[AccountAddress.toBase58(trx.sender)] = 1;
}
}
}
Expand Down
67 changes: 35 additions & 32 deletions packages/common/src/schema.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import * as wasm from '@concordium/rust-bindings';
import { Buffer } from 'buffer/index.js';
import JSONbig from 'json-bigint';
import * as ContractName from './types/ContractName.js';
import * as EntrypointName from './types/EntrypointName.js';
import * as Parameter from './types/Parameter.js';
import { SchemaVersion, SmartContractTypeValues } from './types.js';

/**
Expand All @@ -11,12 +14,12 @@ import { SchemaVersion, SmartContractTypeValues } from './types.js';
*/
export function getInitContractParameterSchema(
moduleSchema: ArrayBuffer,
contractName: string,
contractName: ContractName.Type,
schemaVersion?: SchemaVersion
): Buffer {
): Uint8Array {
const parameterSchema = wasm.getInitContractParameterSchema(
Buffer.from(moduleSchema).toString('hex'),
contractName,
ContractName.toString(contractName),
schemaVersion
);
return Buffer.from(parameterSchema, 'hex');
Expand All @@ -31,14 +34,14 @@ export function getInitContractParameterSchema(
*/
export function getUpdateContractParameterSchema(
moduleSchema: ArrayBuffer,
contractName: string,
receiveFunctionName: string,
contractName: ContractName.Type,
receiveFunctionName: EntrypointName.Type,
schemaVersion?: SchemaVersion
): Buffer {
): Uint8Array {
const parameterSchema = wasm.getReceiveContractParameterSchema(
Buffer.from(moduleSchema).toString('hex'),
contractName,
receiveFunctionName,
ContractName.toString(contractName),
EntrypointName.toString(receiveFunctionName),
schemaVersion
);
return Buffer.from(parameterSchema, 'hex');
Expand All @@ -63,21 +66,21 @@ export function displayTypeSchemaTemplate(rawSchema: ArrayBuffer): string {
* @returns serialized buffer of init contract parameters
*/
export function serializeInitContractParameters(
contractName: string,
contractName: ContractName.Type,
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
parameters: any,
rawSchema: ArrayBuffer,
schemaVersion?: SchemaVersion,
verboseErrorMessage = false
): Buffer {
): Parameter.Type {
const serializedParameters = wasm.serializeInitContractParameters(
JSONbig.stringify(parameters),
Buffer.from(rawSchema).toString('hex'),
contractName,
ContractName.toString(contractName),
schemaVersion,
verboseErrorMessage
);
return Buffer.from(serializedParameters, 'hex');
return Parameter.fromBuffer(Buffer.from(serializedParameters, 'hex'));
}

/**
Expand All @@ -90,23 +93,23 @@ export function serializeInitContractParameters(
* @returns serialized buffer of update contract parameters
*/
export function serializeUpdateContractParameters(
contractName: string,
receiveFunctionName: string,
contractName: ContractName.Type,
receiveFunctionName: EntrypointName.Type,
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
parameters: any,
rawSchema: ArrayBuffer,
schemaVersion?: SchemaVersion,
verboseErrorMessage = false
): Buffer {
): Parameter.Type {
const serializedParameters = wasm.serializeReceiveContractParameters(
JSONbig.stringify(parameters),
Buffer.from(rawSchema).toString('hex'),
contractName,
receiveFunctionName,
ContractName.toString(contractName),
EntrypointName.toString(receiveFunctionName),
schemaVersion,
verboseErrorMessage
);
return Buffer.from(serializedParameters, 'hex');
return Parameter.fromBuffer(Buffer.from(serializedParameters, 'hex'));
}

/**
Expand All @@ -121,28 +124,28 @@ export function serializeTypeValue(
value: any,
rawSchema: ArrayBuffer,
verboseErrorMessage = false
): Buffer {
): Parameter.Type {
const serializedValue = wasm.serializeTypeValue(
JSONbig.stringify(value),
Buffer.from(rawSchema).toString('hex'),
verboseErrorMessage
);
return Buffer.from(serializedValue, 'hex');
return Parameter.fromBuffer(Buffer.from(serializedValue, 'hex'));
}

/**
* Given a contract's raw state, its name and its schema, return the state as a JSON object.
* The return type is any, and the actual type should be determined by using the schema.
*/
export function deserializeContractState(
contractName: string,
contractName: ContractName.Type,
schema: ArrayBuffer,
state: ArrayBuffer,
verboseErrorMessage = false
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any {
const serializedState = wasm.deserializeState(
contractName,
ContractName.toString(contractName),
Buffer.from(state).toString('hex'),
Buffer.from(schema).toString('hex'),
verboseErrorMessage
Expand Down Expand Up @@ -171,17 +174,17 @@ export function deserializeContractState(
export function deserializeReceiveReturnValue(
returnValueBytes: ArrayBuffer,
moduleSchema: ArrayBuffer,
contractName: string,
functionName: string,
contractName: ContractName.Type,
functionName: EntrypointName.Type,
schemaVersion?: number,
verboseErrorMessage = false
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any {
const deserializedReturnValue = wasm.deserializeReceiveReturnValue(
Buffer.from(returnValueBytes).toString('hex'),
Buffer.from(moduleSchema).toString('hex'),
contractName,
functionName,
ContractName.toString(contractName),
EntrypointName.toString(functionName),
schemaVersion,
verboseErrorMessage
);
Expand Down Expand Up @@ -209,16 +212,16 @@ export function deserializeReceiveReturnValue(
export function deserializeReceiveError(
errorBytes: ArrayBuffer,
moduleSchema: ArrayBuffer,
contractName: string,
functionName: string,
contractName: ContractName.Type,
functionName: EntrypointName.Type,
verboseErrorMessage = false
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any {
const deserializedError = wasm.deserializeReceiveError(
Buffer.from(errorBytes).toString('hex'),
Buffer.from(moduleSchema).toString('hex'),
contractName,
functionName,
ContractName.toString(contractName),
EntrypointName.toString(functionName),
verboseErrorMessage
);
try {
Expand All @@ -244,14 +247,14 @@ export function deserializeReceiveError(
export function deserializeInitError(
errorBytes: ArrayBuffer,
moduleSchema: ArrayBuffer,
contractName: string,
contractName: ContractName.Type,
verboseErrorMessage = false
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any {
const deserializedError = wasm.deserializeInitError(
Buffer.from(errorBytes).toString('hex'),
Buffer.from(moduleSchema).toString('hex'),
contractName,
ContractName.toString(contractName),
verboseErrorMessage
);
try {
Expand Down
4 changes: 2 additions & 2 deletions packages/common/src/types/Parameter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function fromSchemaType(
value: unknown
): Parameter {
const schemaBytes = serializeSchemaType(schemaType);
return fromBuffer(serializeTypeValue(value, schemaBytes));
return serializeTypeValue(value, schemaBytes);
}

/**
Expand All @@ -101,7 +101,7 @@ export function fromBase64SchemaType(
value: unknown
): Parameter {
const schemaBytes = Buffer.from(schemaBase64, 'base64');
return fromBuffer(serializeTypeValue(value, schemaBytes));
return serializeTypeValue(value, schemaBytes);
}

/**
Expand Down
Loading

0 comments on commit a1edc78

Please sign in to comment.