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,5 +1,6 @@
# RedStone SmartContracts SDK # RedStone SmartContracts SDK
RedStone SmartContracts SDK is the new, written from scratch, implementation of
RedStone SmartContracts SDK is the new, written from scratch, implementation of
the SmartWeave [Protocol](./docs/SMARTWEAVE_PROTOCOL.md). the SmartWeave [Protocol](./docs/SMARTWEAVE_PROTOCOL.md).
It works in both web and Node.js environment (requires Node.js 16.5+). It works in both web and Node.js environment (requires Node.js 16.5+).
@@ -23,15 +24,18 @@ To further improve contract state evaluation time, one can additionally use AWS
- [Performance - best practices](#performance---best-practices) - [Performance - best practices](#performance---best-practices)
- [Examples](#examples) - [Examples](#examples)
- [Migration guide](#migration-guide) - [Migration guide](#migration-guide)
- [Documentation](#documentation)
- [Missing features](#missing-features)
## Architecture ## Architecture
RedStone SmartContracts SDK consists of main 3 layers: RedStone SmartContracts SDK consists of main 3 layers:
<img src="https://smartweave.redstone.finance/assets/img/illustrations/architecture.svg" height='50%' width='50%'> <img src="https://smartweave.redstone.finance/assets/img/illustrations/architecture.svg" height='50%' width='50%'>
1. The `Core Protocol` layer is the implementation of the original SmartWeave protocol and is responsible for communication with the SmartWeave smart contracts deployed on Arweave. It consists of 5 modules: 1. The `Core Protocol` layer is the implementation of the original SmartWeave protocol and is responsible for communication with the SmartWeave smart contracts deployed on Arweave. It consists of 5 modules:
1. `Interactions Loader` - this module is responsible for loading from Arweave all the interaction transactions registered 1. `Interactions Loader` - this module is responsible for loading from Arweave all the interaction transactions registered
for given contract. for given contract.
2. `Interactions Sorter` - responsible for sorting the interactions according to the protocol specification. This is crucial operation for the deterministic contract state evaluation. 2. `Interactions Sorter` - responsible for sorting the interactions according to the protocol specification. This is crucial operation for the deterministic contract state evaluation.
3. `Definition Loader` - this module loads all the data related to the given SmartWeave contract - its source code, initial state, etc. 3. `Definition Loader` - this module loads all the data related to the given SmartWeave contract - its source code, initial state, etc.
4. `Executor Factory` - this module is responsible for creating "handles" to the SmartWeave contract. These handles are then used by the SDK to call SmartWeave contract methods. 4. `Executor Factory` - this module is responsible for creating "handles" to the SmartWeave contract. These handles are then used by the SDK to call SmartWeave contract methods.
@@ -40,45 +44,52 @@ RedStone SmartContracts SDK consists of main 3 layers:
The main interfaces of this layer are the: The main interfaces of this layer are the:
1. `SwCache` - simple key-value cache, useful for modules like `Definition Loader` 1. `SwCache` - simple key-value cache, useful for modules like `Definition Loader`
2. `BlockHeightSwCache` - a block height aware cache, crucial for modules like `Interactions Loader` and `State Evaluator`. 2. `BlockHeightSwCache` - a block height aware cache, crucial for modules like `Interactions Loader` and `State Evaluator`.
These interfaces - used in conjunction with cache-aware versions of the core modules (like `CacheableContractInteractionsLoader` or `CacheableStateEvaluator`) These interfaces - used in conjunction with cache-aware versions of the core modules (like `CacheableContractInteractionsLoader` or `CacheableStateEvaluator`)
allow to greatly improve performance and SmartWeave contract's state evaluation time - especially for contracts that heavily interact with other contracts. allow to greatly improve performance and SmartWeave contract's state evaluation time - especially for contracts that heavily interact with other contracts.
3. The `Extensions` layer - includes everything that can be built on top of the core SDK - including Command Line Interface, Debugging tools, different logging implementations, 3. The `Extensions` layer - includes everything that can be built on top of the core SDK - including Command Line Interface, Debugging tools, different logging implementations,
so called "dry-runs" (i.e. actions that allow to quickly verify the result of given contract interaction - without writing anything on Arweave). 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: This modular architecture has several advantages:
1. Each module can be separately tested and developed. 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) 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. 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 ## State evaluation diagram
![readState](docs/img/readstate.png) ![readState](docs/img/readstate.png)
In order to perform contract state evaluation (at given block height), SDK performs certain operations. 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. 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. 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. 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) 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. 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 ## Development
PRs are welcome! :-) Also, feel free to submit [issues](https://github.com/redstone-finance/redstone-smartcontracts/issues) - with both bugs and feature proposals. 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). In case of creating a PR - please use [semantic commit messages](https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716).
### Installation ### Installation
SDK requires node.js version 16.5+. SDK requires node.js version 16.5+.
#### Using npm #### Using npm
`npm install redstone-smartweave` `npm install redstone-smartweave`
#### Using yarn #### Using yarn
`yarn add redstone-smartweave` `yarn add redstone-smartweave`
### Import ### Import
You can import the full API or individual modules. You can import the full API or individual modules.
```typescript ```typescript
import * as SmartWeaveSdk from 'redstone-smartweave' import * as SmartWeaveSdk from 'redstone-smartweave';
``` ```
```typescript ```typescript
@@ -104,7 +115,6 @@ Bundle files are possible to use in web environment only. Use minified version f
<!-- Specific version, minified --> <!-- Specific version, minified -->
<script src="https://unpkg.com/redstone-smartweave@0.4.41/bundles/web.bundle.min.js"></script> <script src="https://unpkg.com/redstone-smartweave@0.4.41/bundles/web.bundle.min.js"></script>
``` ```
All exports are stored under `rsdk` global variable. All exports are stored under `rsdk` global variable.
@@ -118,49 +128,49 @@ All exports are stored under `rsdk` global variable.
### Using the RedStone Gateway ### Using the RedStone Gateway
#### SDK version >= `0.5.0` #### SDK version >= `0.5.0`
From version `0.5.0`, the RedStone Gateway is the default gateway used by the SDK. 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). By default, the `{notCorrupted: true}` mode is used (as describe below).
If you want to use the Arweave gateway in version >= `0.5.0`: If you want to use the Arweave gateway in version >= `0.5.0`:
```ts ```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave) const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useArweaveGateway().build();
.useArweaveGateway()
.build();
``` ```
#### SDK version < `0.5.0` #### 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, 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: configure the smartweave instance in the following way:
```ts ```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave) const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useRedStoneGateway().build();
.useRedStoneGateway()
.build();
``` ```
The gateway is currently available under [https://gateway.redstone.finance](https://gateway.redstone.finance) url.
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). 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: 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 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). 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: 2. `{confirmed: true}` - returns only confirmed transactions - the most safe mode, eg:
```ts ```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave) const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useRedStoneGateway({ confirmed: true }).build();
.useRedStoneGateway( {confirmed: true} )
.build();
``` ```
3. `{notCorrupted: true}` - returns both confirmed and not yet verified interactions (i.e. the latest ones). 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. Not as safe as previous mode, but good if you want combine high level of safety with the most recent data.
```ts ```ts
const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave) const smartweave = SmartWeaveNodeFactory.memCachedBased(arweave).useRedStoneGateway({ notCorrupted: true }).build();
.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). More examples can be found [here](https://github.com/redstone-finance/redstone-smartcontracts-examples/blob/main/src/redstone-gateway-example.ts).
### WASM ### 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). 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).
Using SDKs' methods works exactly the same as in case of a regular JS contract. Using SDKs' methods works exactly the same as in case of a regular JS contract.
@@ -168,54 +178,62 @@ Additionally, it is possible to set gas limit for interaction execution in order
```js ```js
contract = smartweave.contract(contractTxId).setEvaluationOptions({ contract = smartweave.contract(contractTxId).setEvaluationOptions({
gasLimit: 14000000 gasLimit: 14000000
}); });
``` ```
### VM2 ### VM2
It is possible to provide an isolated execution environment also in the JavaScript implementation thanks to [VM2](https://github.com/patriksimek/vm2) - a sandbox that can run untrusted code with whitelisted Node's built-in modules. It works only in a NodeJS environment and it enhances security at a (slight) cost of performance, so it should be used it for contracts one cannot trust. It is possible to provide an isolated execution environment also in the JavaScript implementation thanks to [VM2](https://github.com/patriksimek/vm2) - a sandbox that can run untrusted code with whitelisted Node's built-in modules. It works only in a NodeJS environment and it enhances security at a (slight) cost of performance, so it should be used it for contracts one cannot trust.
In order to use VM2, set `useVM2` evaluation option to `true` (defaults to `false`). In order to use VM2, set `useVM2` evaluation option to `true` (defaults to `false`).
```js ```js
contract = smartweave.contract(contractTxId).setEvaluationOptions({ contract = smartweave.contract(contractTxId).setEvaluationOptions({
useVM2: true useVM2: true
}); });
``` ```
### Internal writes ### 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. 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 We proposed a new solution
### Performance - best practices ### Performance - best practices
In order to get the best performance on production environment (or while performing benchmarks ;-)), please follow these simple rules: 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 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). by a factor of 2 or 3 (depending on the logging level).
2. Use `fatal` or `error` log level, e.g.: 2. Use `fatal` or `error` log level, e.g.:
```ts ```ts
// configure the logging first // configure the logging first
LoggerFactory.INST.logLevel("fatal"); LoggerFactory.INST.logLevel('fatal');
// or // or
LoggerFactory.INST.logLevel("error"); LoggerFactory.INST.logLevel('error');
// then create an instance of smartweave sdk // then create an instance of smartweave sdk
const smartweave = SmartWeaveWebFactory.memCached(arweave); 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. 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` 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 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.: names of TypeScript classes, e.g.:
```ts ```ts
// configure the logging first // configure the logging first
LoggerFactory.INST.logLevel("fatal"); LoggerFactory.INST.logLevel('fatal');
LoggerFactory.INST.logLevel("debug", "ArweaveGatewayInteractionsLoader"); LoggerFactory.INST.logLevel('debug', 'ArweaveGatewayInteractionsLoader');
// then create an instance of smartweave sdk // then create an instance of smartweave sdk
const smartweave = SmartWeaveWebFactory.memCached(arweave); const smartweave = SmartWeaveWebFactory.memCached(arweave);
``` ```
### Examples ### Examples
Usage examples can be found in Usage examples can be found in
a dedicated [repository](https://github.com/redstone-finance/redstone-smartcontracts-examples). 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. 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. and describes how to interact with it using RedStone SmartContracts SDK.
### Migration Guide ### Migration Guide
If you're already using Arweave smartweave.js SDK and would like to smoothly migrate to RedStone SmartContracts SDK - 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). check out the [migration guide](https://github.com/redstone-finance/redstone-smartweave/blob/main/docs/MIGRATION_GUIDE.md).
### Documentation ### Documentation
TSDocs can be found [here](https://smartweave.docs.redstone.finance/). TSDocs can be found [here](https://smartweave.docs.redstone.finance/).
### Missing features ### 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 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: a separate libraries, built on top of the SDK:
- CLI (though not sure if that is a necessary - even if, it should be - 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). probably a separate lib built on top of the base SDK).

182
README.md
View File

@@ -21,14 +21,13 @@ To further improve contract state evaluation time, one can additionally use AWS
- [Installation](#installation) - [Installation](#installation)
- [Import](#import) - [Import](#import)
- [Using the Warp Gateway](#using-the-warp-gateway) - [Using the Warp Gateway](#using-the-warp-gateway)
- [Contract methods](#contract-methods)
- [WASM](#wasm) - [WASM](#wasm)
- [VM2](#vm2) - [VM2](#vm2)
- [Internal writes](#internal-writes) - [Internal writes](#internal-writes)
- [Performance - best practices](#performance---best-practices) - [Performance - best practices](#performance---best-practices)
- [Examples](#examples) - [Examples](#examples)
- [Migration guide](#migration-guide) - [Migration guide](#migration-guide)
- [Documentation](#documentation)
- [Missing features](#missing-features)
## Architecture ## 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). 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
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). 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,13 +400,13 @@ await SmartWeave.contracts.write(contractTxId, { function: 'add' });
In order for internal calls to work you need to set `evaluationOptions` to `true`: In order for internal calls to work you need to set `evaluationOptions` to `true`:
``` ```ts
const callingContract = smartweave const callingContract = smartweave
.contract<ExampleContractState>(calleeTxId) .contract<ExampleContractState>(calleeTxId)
.setEvaluationOptions({ .setEvaluationOptions({
internalWrites: true internalWrites: true
}) })
.connect(wallet); .connect(wallet);
``` ```
You can also perform internal read to the contract (originally introduced by the protocol): You can also perform internal read to the contract (originally introduced by the protocol):

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 * 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. * to load Contract Data.
* *
* If the contract data is not available on Warp Gateway - it fallbacks to default implementation * 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). * 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 * 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 * Please note that currently caching (ie. {@link CacheableContractInteractionsLoader} is switched off
* for WarpGatewayInteractionsLoader due to the issue mentioned in the * for WarpGatewayInteractionsLoader due to the issue mentioned in the