Skip to content

Commit

Permalink
AUTO: Sync ScalarDL docs in English to docs site repo
Browse files Browse the repository at this point in the history
  • Loading branch information
josh-wong committed Oct 30, 2024
1 parent e0edb9f commit b0ff773
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions versioned_docs/version-3.8/how-to-write-contract.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ setContext(context);

## Write a complex contract

This section describes how to write a complex contract.

### Call contracts in a nested way

If your contract is more than 100 lines of code, it is a good sign that you are probably doing more than one thing with your contract.
It is a good practice to write modularized contracts, where each contract is doing only one thing, and to combine contracts to express more complex business logic.

Expand Down Expand Up @@ -153,6 +157,38 @@ The `StateUpdaterReader` updates the Ledger just like `StateUpdater` and additio

It's to be noted that all the contracts in the nested invocation are executed transactionally (in an ACID manner) in ScalarDL so that they are executed entirely successfully or they are entirely failed.

### Manage who can access assets

You can get identity information, which indicates who is executing the contract, by calling `getClientIdentityKey()` in a contract. This functionality helps to control who can access a certain asset. The following example shows `StateUpdater`, which has been modified so that it can only update a restricted asset with the name `state-xxx`, where `xxx` is an entity ID of the certificate or secret holder.

For details, see the base contract page and the `ClientIdentityKey` page in the [Javadoc](https://javadoc.io/doc/com.scalar-labs/scalardl-java-client-sdk/latest/index.html) of the version of ScalarDL that you are using.

```java
public class StateUpdater extends JacksonBasedContract {

@Nullable
@Override
public JsonNode invoke(Ledger<JsonNode> ledger, JsonNode argument, @Nullable JsonNode properties) {
if (!argument.has("state")) {
throw new ContractContextException("please set state in the argument");
}

ClientIdentityKey clientIdentityKey = getClientIdentityKey();
String entityId = clientIdentityKey.getEntityId();
String assetId = "state-" + entityId;
int state = argument.get("state").asInt();

Optional<Asset<JsonNode>> asset = ledger.get(assetId);

if (!asset.isPresent() || asset.get().data().get("state").asInt() != state) {
ledger.put(assetId, getObjectMapper().createObjectNode().put("state", state));
}

return null;
}
}
```

## Summary

Here are the best practices for writing good contracts for ScalarDL.
Expand Down

0 comments on commit b0ff773

Please sign in to comment.