docs: moving contract methods to main docs

This commit is contained in:
asiaziola
2022-05-25 16:15:50 +02:00
parent 5dbb811599
commit 4f61313328
5 changed files with 232 additions and 219 deletions

View File

@@ -1,4 +1,5 @@
# RedStone SmartContracts SDK
RedStone SmartContracts SDK is the new, written from scratch, implementation of
the SmartWeave [Protocol](./docs/SMARTWEAVE_PROTOCOL.md).
@@ -23,8 +24,11 @@ To further improve contract state evaluation time, one can additionally use AWS
- [Performance - best practices](#performance---best-practices)
- [Examples](#examples)
- [Migration guide](#migration-guide)
- [Documentation](#documentation)
- [Missing features](#missing-features)
## Architecture
RedStone SmartContracts SDK consists of main 3 layers:
<img src="https://smartweave.redstone.finance/assets/img/illustrations/architecture.svg" height='50%' width='50%'>
@@ -46,39 +50,46 @@ RedStone SmartContracts SDK consists of main 3 layers:
so called "dry-runs" (i.e. actions that allow to quickly verify the result of given contract interaction - without writing anything on Arweave).
This modular architecture has several advantages:
1. Each module can be separately tested and developed.
2. The SmartWeave client can be customized depending on user needs (e.g. different type of caches for web and node environment)
3. It makes it easier to add new features on top of the core protocol - without the risk of breaking the functionality of the core layer.
## State evaluation diagram
![readState](docs/img/readstate.png)
In order to perform contract state evaluation (at given block height), SDK performs certain operations.
The diagram above and description assume the most basic “mem-cached” SDK client.
1. Users who are interacting with the contract, call the “readState” method.
2. Interactions Loader and Contract Definition Loader modules are then called in parallel - to load all the data required for state evaluation. Both Interactions Loader and Contract Definition Loader first check its corresponding cache whether data is already loaded - and load from Arweave only the missing part.
3. With interactions and contract definition loaded - Executor Factory creates a handle to the SmartWeave contract main function (or loads it from its own cache)
4. With all the interactions and a contract handle - the State Evaluator evaluates the state from the lastly cached value - and returns the result to User.
## Development
PRs are welcome! :-) Also, feel free to submit [issues](https://github.com/redstone-finance/redstone-smartcontracts/issues) - with both bugs and feature proposals.
In case of creating a PR - please use [semantic commit messages](https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716).
### Installation
SDK requires node.js version 16.5+.
#### Using npm
`npm install redstone-smartweave`
#### Using yarn
`yarn add redstone-smartweave`
### Import
You can import the full API or individual modules.
```typescript
import * as SmartWeaveSdk from 'redstone-smartweave'
import * as SmartWeaveSdk from 'redstone-smartweave';
```
```typescript
@@ -104,7 +115,6 @@ Bundle files are possible to use in web environment only. Use minified version f
<!-- Specific version, minified -->
<script src="https://unpkg.com/redstone-smartweave@0.4.41/bundles/web.bundle.min.js"></script>
```
All exports are stored under `rsdk` global variable.
@@ -118,42 +128,42 @@ All exports are stored under `rsdk` global variable.
### Using the RedStone Gateway
#### SDK version >= `0.5.0`
From version `0.5.0`, the RedStone Gateway is the default gateway used by the SDK.
By default, the `{notCorrupted: true}` mode is used (as describe below).
If you want to use the Arweave gateway in version >= `0.5.0`:
```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave)
.useArweaveGateway()
.build();
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useArweaveGateway().build();
```
#### SDK version < `0.5.0`
In order to use the [Redstone Gateway](https://github.com/redstone-finance/redstone-sw-gateway) for loading the contract interactions,
configure the smartweave instance in the following way:
```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave)
.useRedStoneGateway()
.build();
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useRedStoneGateway().build();
```
The gateway is currently available under [https://gateway.redstone.finance](https://gateway.redstone.finance) url.
Full API reference is available [here](https://github.com/redstone-finance/redstone-sw-gateway#http-api-reference).
Optionally - you can pass the second argument to the `useRedStoneGateway` method that will determine which transactions will be loaded:
1. no parameter - default mode, compatible with how the Arweave Gateway GQL endpoint works - returns
all the interactions. There is a risk of returning [corrupted transactions](https://github.com/redstone-finance/redstone-sw-gateway#corrupted-transactions).
2. `{confirmed: true}` - returns only confirmed transactions - the most safe mode, eg:
```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave)
.useRedStoneGateway( {confirmed: true} )
.build();
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useRedStoneGateway({ confirmed: true }).build();
```
3. `{notCorrupted: true}` - returns both confirmed and not yet verified interactions (i.e. the latest ones).
Not as safe as previous mode, but good if you want combine high level of safety with the most recent data.
```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave)
.useRedStoneGateway( {notCorrupted: true} )
.build();
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useRedStoneGateway({ notCorrupted: true }).build();
```
More examples can be found [here](https://github.com/redstone-finance/redstone-smartcontracts-examples/blob/main/src/redstone-gateway-example.ts).
@@ -185,37 +195,45 @@ contract = smartweave.contract(contractTxId).setEvaluationOptions({
```
### Internal writes
SmartWeave protocol currently natively does not support writes between contract - contracts can only read each others' state. This lack of interoperability is a big limitation for real-life applications - especially if you want to implement features like staking/vesting, disputes - or even a standard approve/transferFrom flow from ERC-20 tokens.
We proposed a new solution
### Performance - best practices
In order to get the best performance on production environment (or while performing benchmarks ;-)), please follow these simple rules:
1. Do NOT use the `TsLoggerFactory` - it is good for development, as it formats the logs nicely, but might slow down the state evaluation
by a factor of 2 or 3 (depending on the logging level).
2. Use `fatal` or `error` log level, e.g.:
```ts
// configure the logging first
LoggerFactory.INST.logLevel("fatal");
LoggerFactory.INST.logLevel('fatal');
// or
LoggerFactory.INST.logLevel("error");
LoggerFactory.INST.logLevel('error');
// then create an instance of smartweave sdk
const smartweave = SmartWeaveWebFactory.memCached(arweave);
```
Logging on `info` or `debug` level is good for development, but turning it on globally might slow down the evaluation by a factor of 2.
Keep in mind that you can fine tune the log level of each module separately. For example you can switch the `fatal` globally, but `debug`
for the `ArweaveGatewayInteractionsLoader` (in order to verify the load times from Arweave GQL endpoint). The names of the modules are derived from the
names of TypeScript classes, e.g.:
```ts
// configure the logging first
LoggerFactory.INST.logLevel("fatal");
LoggerFactory.INST.logLevel("debug", "ArweaveGatewayInteractionsLoader");
LoggerFactory.INST.logLevel('fatal');
LoggerFactory.INST.logLevel('debug', 'ArweaveGatewayInteractionsLoader');
// then create an instance of smartweave sdk
const smartweave = SmartWeaveWebFactory.memCached(arweave);
```
### Examples
Usage examples can be found in
a dedicated [repository](https://github.com/redstone-finance/redstone-smartcontracts-examples).
Please follow instructions in its README.md (and detail-ish comments in the examples files) to learn more.
@@ -225,14 +243,18 @@ We've also created a [tutorial](https://github.com/redstone-finance/smartweave-l
and describes how to interact with it using RedStone SmartContracts SDK.
### Migration Guide
If you're already using Arweave smartweave.js SDK and would like to smoothly migrate to RedStone SmartContracts SDK -
check out the [migration guide](https://github.com/redstone-finance/redstone-smartweave/blob/main/docs/MIGRATION_GUIDE.md).
### Documentation
TSDocs can be found [here](https://smartweave.docs.redstone.finance/).
### Missing features
Some features from the original Arweave's smartweave.js are not yet implemented. They will be either added soon to the core SDK, or as
a separate libraries, built on top of the SDK:
- CLI (though not sure if that is a necessary - even if, it should be
probably a separate lib built on top of the base SDK).

172
README.md
View File

@@ -21,14 +21,13 @@ To further improve contract state evaluation time, one can additionally use AWS
- [Installation](#installation)
- [Import](#import)
- [Using the Warp Gateway](#using-the-warp-gateway)
- [Contract methods](#contract-methods)
- [WASM](#wasm)
- [VM2](#vm2)
- [Internal writes](#internal-writes)
- [Performance - best practices](#performance---best-practices)
- [Examples](#examples)
- [Migration guide](#migration-guide)
- [Documentation](#documentation)
- [Missing features](#missing-features)
## Architecture
@@ -188,6 +187,173 @@ const warp = WarpNodeFactory.memCachedBased(arweave).useWarpGateway({ notCorrupt
More examples can be found [here](https://github.com/redstone-finance/redstone-smartcontracts-examples/blob/main/src/redstone-gateway-example.ts).
### Contract methods
- [`connect`](#connect)
- [`setEvaluationOptions`](#setevaluationoptions)
- [`readState`](#readstate)
- [`viewState`](#viewstate)
- [`writeInteraction`](#writeinteraction)
- [`bundleInteraction`](#bundleInteraction)
#### `connect`
```typescript
async function connect(wallet: ArWallet): Contract<State>;
```
Allows to connect wallet to a contract. Connecting a wallet MAY be done before "viewState" (depending on contract implementation, ie. whether called contract's function required "caller" info) Connecting a wallet MUST be done before "writeInteraction".
- `wallet` a JWK object with private key or 'use_wallet' string.
<details>
<summary>Example</summary>
```typescript
const contract = smartweave.contract('YOUR_CONTRACT_TX_ID').connect(jwk);
```
</details>
---
#### `setEvaluationOptions`
```typescript
function setEvaluationOptions(options: Partial<EvaluationOptions>): Contract<State>;
```
Allows to set (EvaluationOptions)
- `options` the interaction input
- `options.ignoreExceptions` enables exceptions ignoring
- `options.waitForConfirmation` enables waiting for transaction confirmation
<details>
<summary>Example</summary>
```typescript
const contract = smartweave.contract('YOUR_CONTRACT_TX_ID').setEvaluationOptions({
waitForConfirmation: true,
ignoreExceptions: false
});
```
</details>
---
#### `readState`
```typescript
async function readState(
blockHeight?: number,
currentTx?: { contractTxId: string; interactionTxId: string }[]
): Promise<EvalStateResult<State>>;
```
Returns state of the contract at required blockHeight. Similar to the `readContract` from the version 1.
- `blockHeight` Block height for state
- `currentTx` If specified, will be used as a current transaction
<details>
<summary>Example</summary>
```typescript
const { state, validity } = await contract.readState();
```
</details>
---
#### `viewState`
```typescript
async function viewState<Input, View>(
input: Input,
blockHeight?: number,
tags?: Tags,
transfer?: ArTransfer
): Promise<InteractionResult<State, View>>;
```
Returns the "view" of the state, computed by the SWC - ie. object that is a derivative of a current state and some specific smart contract business logic. Similar to the `interactRead` from the current SDK version.
- `input` the interaction input
- `blockHeight` if specified the contract will be replayed only to this block height
- `tags` an array of tags with name/value as objects
- `transfer` target and winstonQty for transfer
<details>
<summary>Example</summary>
```typescript
const { result } = await contract.viewState<any, any>({
function: "NAME_OF_YOUR_FUNCTION",
data: { ... }
});
```
</details>
---
#### `viewStateForTx`
```typescript
async function viewStateForTx<Input, View>(
input: Input,
transaction: InteractionTx
): Promise<InteractionResult<State, View>>;
```
A version of the viewState method to be used from within the contract's source code. The transaction passed as an argument is the currently processed interaction transaction. The "caller" will be se to the owner of the interaction transaction, that requires to call this method.
💡 Note! calling "interactRead" from withing contract's source code was not previously possible - this is a new feature.
- `input` the interaction input
- `transaction` interaction transaction
<details>
<summary>Example</summary>
```typescript
const { result } = await contract.viewStateForTx<any, any>({
function: "NAME_OF_YOUR_FUNCTION",
data: { ... }
}, transaction);
```
</details>
---
#### `writeInteraction`
```typescript
async function writeInteraction<Input>(input: Input, tags?: Tags, transfer?: ArTransfer): Promise<string>;
```
Writes a new "interaction" transaction - ie. such transaction that stores input for the contract.
- `input` the interaction input
- `tags` an array of tags with name/value as objects
- `transfer` target and winstonQty for transfer
<details>
<summary>Example</summary>
```typescript
const result = await contract.writeInteraction({
function: "NAME_OF_YOUR_FUNCTION",
data: { ... }
});
```
</details>
### WASM
WASM provides proper sandboxing ensuring execution environment isolation which guarantees security to the contracts execution. As for now - **Assemblyscript**, **Rust** and **Go** languages are supported. WASM contracts templates containing example PST contract implementation within tools for compiling contracts to WASM, testing, deploying (locally, on testnet and mainnet) and writing interactions are available in a [dedicated repository](https://github.com/redstone-finance/redstone-smartcontracts-wasm-templates).
@@ -234,7 +400,7 @@ await SmartWeave.contracts.write(contractTxId, { function: 'add' });
In order for internal calls to work you need to set `evaluationOptions` to `true`:
```
```ts
const callingContract = smartweave
.contract<ExampleContractState>(calleeTxId)
.setEvaluationOptions({

View File

@@ -1,175 +0,0 @@
# Warp - Contract methods
- [Contract Methods](#contract-methods)
- [`connect`](#connect)
- [`setEvaluationOptions`](#setevaluationoptions)
- [`readState`](#readstate)
- [`viewState`](#viewstate)
- [`writeInteraction`](#writeinteraction)
- [`bundleInteraction`](#bundleInteraction)
## Contract Methods
### `connect`
```typescript
async function connect(wallet: ArWallet): Contract<State>;
```
Allows to connect wallet to a contract. Connecting a wallet MAY be done before "viewState" (depending on contract implementation, ie. whether called contract's function required "caller" info) Connecting a wallet MUST be done before "writeInteraction".
- `wallet` a JWK object with private key or 'use_wallet' string.
<details>
<summary>Example</summary>
```typescript
const contract = smartweave.contract('YOUR_CONTRACT_TX_ID').connect(jwk);
```
</details>
---
### `setEvaluationOptions`
```typescript
function setEvaluationOptions(options: Partial<EvaluationOptions>): Contract<State>;
```
Allows to set (EvaluationOptions)
- `options` the interaction input
- `options.ignoreExceptions` enables exceptions ignoring
- `options.waitForConfirmation` enables waiting for transaction confirmation
<details>
<summary>Example</summary>
```typescript
const contract = smartweave.contract('YOUR_CONTRACT_TX_ID').setEvaluationOptions({
waitForConfirmation: true,
ignoreExceptions: false
});
```
</details>
---
### `readState`
```typescript
async function readState(
blockHeight?: number,
currentTx?: { contractTxId: string; interactionTxId: string }[]
): Promise<EvalStateResult<State>>;
```
Returns state of the contract at required blockHeight. Similar to the `readContract` from the version 1.
- `blockHeight` Block height for state
- `currentTx` If specified, will be used as a current transaction
<details>
<summary>Example</summary>
```typescript
const { state, validity } = await contract.readState();
```
</details>
---
### `viewState`
```typescript
async function viewState<Input, View>(
input: Input,
blockHeight?: number,
tags?: Tags,
transfer?: ArTransfer
): Promise<InteractionResult<State, View>>;
```
Returns the "view" of the state, computed by the SWC - ie. object that is a derivative of a current state and some specific smart contract business logic. Similar to the `interactRead` from the current SDK version.
- `input` the interaction input
- `blockHeight` if specified the contract will be replayed only to this block height
- `tags` an array of tags with name/value as objects
- `transfer` target and winstonQty for transfer
<details>
<summary>Example</summary>
```typescript
const { result } = await contract.viewState<any, any>({
function: "NAME_OF_YOUR_FUNCTION",
data: { ... }
});
```
</details>
---
### `viewStateForTx`
```typescript
async function viewStateForTx<Input, View>(
input: Input,
transaction: InteractionTx
): Promise<InteractionResult<State, View>>;
```
A version of the viewState method to be used from within the contract's source code. The transaction passed as an argument is the currently processed interaction transaction. The "caller" will be se to the owner of the interaction transaction, that requires to call this method.
💡 Note! calling "interactRead" from withing contract's source code was not previously possible - this is a new feature.
- `input` the interaction input
- `transaction` interaction transaction
<details>
<summary>Example</summary>
```typescript
const { result } = await contract.viewStateForTx<any, any>({
function: "NAME_OF_YOUR_FUNCTION",
data: { ... }
}, transaction);
```
</details>
---
### `writeInteraction`
```typescript
async function writeInteraction<Input>(input: Input, tags?: Tags, transfer?: ArTransfer): Promise<string>;
```
Writes a new "interaction" transaction - ie. such transaction that stores input for the contract.
- `input` the interaction input
- `tags` an array of tags with name/value as objects
- `transfer` target and winstonQty for transfer
<details>
<summary>Example</summary>
```typescript
const result = await contract.writeInteraction({
function: "NAME_OF_YOUR_FUNCTION",
data: { ... }
});
```
</details>
---
### Need help? 🙋‍♂️
Please feel free to contact us [on Discord](https://redstone.finance/discord) if you face any problems.

View File

@@ -7,7 +7,7 @@ import Transaction from 'arweave/node/lib/transaction';
/**
* An extension to {@link ContractDefinitionLoader} that makes use of
* Warp Gateway ({@link https://github.com/redstone-finance/warp-gateway})
* Warp Gateway ({@link https://github.com/redstone-finance/redstone-sw-gateway})
* to load Contract Data.
*
* If the contract data is not available on Warp Gateway - it fallbacks to default implementation

View File

@@ -60,7 +60,7 @@ export const enum SourceType {
*
* Passing no flag is the "backwards compatible" mode (ie. it will behave like the original Arweave GQL gateway endpoint).
* Note that this may result in returning corrupted and/or forked interactions
* - read more {@link https://github.com/redstone-finance/warp-gateway#corrupted-transactions}.
* - read more {@link https://github.com/redstone-finance/redstone-sw-gateway#corrupted-transactions}.
*
* Please note that currently caching (ie. {@link CacheableContractInteractionsLoader} is switched off
* for WarpGatewayInteractionsLoader due to the issue mentioned in the