diff --git a/src/content/docs/How To/How to build smart contracts outline.md b/src/content/docs/How To/How to build smart contracts outline.md deleted file mode 100644 index e8eb4f9..0000000 --- a/src/content/docs/How To/How to build smart contracts outline.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: How to Write, Test, and Deploy a Smart Contract on VSC (OUTLINE) -sidebar: - order: 11 ---- - - -## 1. Setting Up Your Environment - -### 1.1 Prerequisites -- Node.js -- Git - -### 1.2 Install Dependencies - -### 1.3 Setup `.env` - ---- - -## 2. Writing Your First Contract - -### 2.1 Project Structure - -### 2.2 Example: Counter or Token Contract - ---- - -## 3. Compiling the Contract - -### 3.1 Compile Command - -### 3.2 Output in `build/` Folder - ---- - -## 4. Testing the Contract - -### 4.1 Run Tests - -### 4.2 Sample Test File - ---- - -## 5. Deploying - -### 5.1 Deploy Script - -### 5.2 On-Chain Result - ---- - -## 6. Calling Your Contract - -### 6.1 JSON Structure - -### 6.2 Hive Tools (e.g. PeakD Broadcast) diff --git a/src/content/docs/How To/How to use vsc api outline.md b/src/content/docs/How To/How to use vsc api outline.md index 643ab5b..edb24ac 100644 --- a/src/content/docs/How To/How to use vsc api outline.md +++ b/src/content/docs/How To/How to use vsc api outline.md @@ -1,7 +1,7 @@ --- title: How to use the VSC API (OUTLINE) sidebar: - order: 12 + order: 20 --- diff --git a/src/content/docs/How To/create a token.mdx b/src/content/docs/How To/create a token.mdx new file mode 100644 index 0000000..d5c931a --- /dev/null +++ b/src/content/docs/How To/create a token.mdx @@ -0,0 +1,84 @@ +--- +title: Create a token +sidebar: + order: 12 +--- + +import { Aside } from '@astrojs/starlight/components' + +This tutorial describes the process of creating a basic fungible token on VSC. + + + +## Setup + +Clone the Go contract template: + +```sh +git clone https://github.com/vsc-eco/go-contract-template your-token +cd your-token +``` + +## Write Your Token Contract + + + +An example token contract has been included in [`examples/token/main.go`](https://github.com/vsc-eco/go-contract-template/blob/main/examples/token/main.go) file. You may copy this file into `contract/main.go` to use as a starting point. + +```sh +cp examples/token/main.go contract +``` + +The token contract features mint/burn with supply cap, transfer and change ownership functions. Update the following constants at the top of the file to your desired values: + +```go title="main.go" +const MaxSupply = 1000000 +const Precision = 3 +const Symbol = "TOKEN" +const Creator = "hive:vaultec.vsc" +``` + + + +## Deploy Token + +Compile your token contract: + +```sh +tinygo build -gc=custom -scheduler=none -panic=trap -no-debug -target=wasm-unknown -o build/main.wasm contract/main.go +wasm-tools strip -o build/main-striped.wasm build/main.wasm +``` + +Then deploy the contract: + +```sh +# If not done already, init config and fill in deployer active key +vsc-contract-deploy -init + +# Deploy token +vsc-contract-deploy -wasmPath build/main-striped.wasm -name "your token name" +``` + +## Initialize Token + +Call the `init` function from your token contract owner address as specified in the `Creator` constant. The contract call payload does not matter here. + +## Mint Tokens + +Call the `mint` function where payload is the amount to mint. The tokens minted will be sent to your address. + +## Burn Tokens + +Call the `burn` function where payload is the amount to burn. The tokens will be burnt from the caller address. + +## Transfer Tokens + +Call the `transfer` function where payload is a comma-separated string of destination address and amount. + +For example, to transfer 10 coins to `did:pkh:eip155:1:0xtoaddresshere`, the payload shall be `did:pkh:eip155:1:0xtoaddresshere,10`. \ No newline at end of file diff --git a/src/content/docs/How To/smart contract development.mdx b/src/content/docs/How To/smart contract development.mdx new file mode 100644 index 0000000..84e828a --- /dev/null +++ b/src/content/docs/How To/smart contract development.mdx @@ -0,0 +1,291 @@ +--- +title: Write, Test and Deploy a Smart Contract +sidebar: + order: 11 +--- + +import { Aside, FileTree, Tabs, TabItem } from '@astrojs/starlight/components' + +This is a brief overview of VSC smart contract development with Go. + +## Environment Setup + +### Prerequisites +- [Golang](https://go.dev/dl) +- [Git](https://git-scm.com/downloads) +- [TinyGo](https://tinygo.org/getting-started/install) +- [Wasm Edge](https://wasmedge.org/docs/start/install) +- [Wabt](https://github.com/WebAssembly/wabt) or [Wasm Tools](https://github.com/bytecodealliance/wasm-tools) + +### Install Dependencies + + + +```sh +git clone https://github.com/vsc-eco/go-vsc-node +cd go-vsc-node +go mod download +go build -buildvcs=false -o vsc-contract-deploy vsc-node/cmd/contract-deployer +``` + +This will generate an executable named `vsc-contract-deploy`. You may move it to your `PATH` directory (i.e. `/usr/bin` for Linux or `/usr/local/bin` for macOS). + +--- + +## Writing Your First Contract + +### Setup + +Clone the Go contract template: + +```sh +git clone https://github.com/vsc-eco/go-contract-template +``` + +### Project Structure + + +- contract your contract code goes here + - main.go +- runtime + - gc_leaking_exported.go +- sdk + - address.go + - env.go + - sdk.go +- test + - contract_test.go +- .gitignore +- go.mod +- go.sum + + +### Hello World Contract + +The below contract demonstrates calling SDK methods to interact with the contract database and defining WASM exports to mark a function as callable by VSC accounts or other contracts. + +Find out more about the Go contract SDK methods [here](/references/sdk). + +```go title="main.go" +package main + +import "contract-template/sdk" + +//go:wasmexport hello_world +func HelloWorld(a *string) *string { + ret := "Hello world" + return &ret +} + +//go:wasmexport setString +func SetString(a *string) *string { + sdk.StateSetObject("myString", *a) + return a +} + +//go:wasmexport getString +func GetString(a *string) *string { + return sdk.StateGetObject("myString") +} +``` + +--- + +## Compile Contract + +To compile your contract: + +```sh +tinygo build -gc=custom -scheduler=none -panic=trap -no-debug -target=wasm-unknown -o artifacts/main.wasm contract/main.go +``` + + + +To remove metadata from the output WASM binary to reduce file size: + + + + ```sh + wasm-strip -o artifacts/main-striped.wasm artifacts/main.wasm + ``` + + + ```sh + wasm-tools strip -o artifacts/main-striped.wasm artifacts/main.wasm + ``` + + + +To inspect the output WASM assembly: + + + + ```sh + wasm2wat artifacts/main.wasm + ``` + + + ```sh + wasm-tools print artifacts/main.wasm + ``` + + + +--- + +## Test and Debug Contract + +We provide a contract test environment for you to execute contract calls on a state engine that resembles the live network. Your contract test code will look something like this: + +```go +package contract_test + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/vsc-eco/go-vsc-node/lib/test_utils" + "github.com/vsc-eco/go-vsc-node/modules/db/vsc/contracts" + ledgerDb "github.com/vsc-eco/go-vsc-node/modules/db/vsc/ledger" + stateEngine "github.com/vsc-eco/go-vsc-node/modules/state-processing" +) + +//go:embed artifacts/main.wasm +var ContractWasm []byte + +func TestContract(t *testing.T) { + ct := test_utils.NewContractTest() + ct.RegisterContract("vsccontractid", ContractWasm) + ct.Deposit("hive:someone", 1000, ledgerDb.AssetHive) // deposit 1 HIVE + ct.Deposit("hive:someone", 1000, ledgerDb.AssetHbd) // deposit 1 HBD + + result, gasUsed, logs := ct.Call(stateEngine.TxVscCallContract{ + Self: stateEngine.TxSelf{ + TxId: "sometxid", + BlockId: "abcdef", + Index: 69, + OpIndex: 0, + Timestamp: "2025-09-03T00:00:00", + RequiredAuths: []string{"hive:someone"}, + RequiredPostingAuths: []string{}, + }, + ContractId: contractId, + Action: "yourMethodName", + Payload: json.RawMessage([]byte("1000")), + RcLimit: 1000, + Intents: []contracts.Intent{{ + Type: "transfer.allow", + Args: map[string]string{ + "limit": "1.000", + "token": "hive", + }, + }}, + }) + assert.True(t, result.Success) // assert contract execution success + assert.LessOrEqual(t, gasUsed, uint(10000000)) // assert this call uses no more than 10M WASM gas + assert.GreaterOrEqual(t, len(logs), 1) // assert at least 1 log emitted +} +``` + +Find out more about methods provided by the contract test utils [here](/references/sdk/#contract-test-utils). + +--- + +## Deploy Contract + + + +Firstly, initialize the deployer configuration: + +```sh +vsc-contract-deploy -init +``` + +This will generate some config files in `data/config` folder in your current directory. Insert your Hive username and active key of the deployer account in `identityConfig.json`: + +```json title="identityConfig.json" +{ + "BlsPrivKeySeed": "9e264692ced37...", + "HiveActiveKey": "ADD_YOUR_PRIVATE_WIF", + "HiveUsername": "ADD_YOUR_USERNAME", + "Libp2pPrivKey": "125cd98aed75d..." +} +``` + +Then deploy your contract to VSC: + +```sh +vsc-contract-deploy -wasmPath artifacts/main-striped.wasm -name "my first contract" +``` + +You should see an output similar to this: + +``` +WASM_CODE: 1130 [0 97 115 109 1 0 0 0 1 9] ... +peer ID: 12D3KooWS7N7zmrkMHxGX9ibNXbKk4byfkx8ckEhfgXM8eQcgBtK +NAT Status {Private} +12D3KooWS7N7zmrkMHxGX9ibNXbKk4byfkx8ckEhfgXM8eQcgBtK pubsub /vsc/mainnet/data-availability/v1 peers: 20 +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +{bafkreibwwj3fypek5uz6l3scacy47yw3b2adgbxmfab2ybmkarljaggbey {i_TLUMJVJb6n6X-5_lKvBibiLvP0RUVz2tn20KJTw5Q_lQ-tcVt9jrZr4s1WVga1CR7q0Ldnrc-EjNpqgaY7GpnhE2d3pC3nfNhUKkmN1za6h9SwCEUuo3CByNnmnqYE __f9}} +{"__v":"0.1","code":"bafkreibwwj3fypek5uz6l3scacy47yw3b2adgbxmfab2ybmkarljaggbey","description":"","name":"go test","net_id":"vsc-mainnet","owner":"techcoderx.vsc","runtime":"go","storage_proof":{"hash":"bafkreibwwj3fypek5uz6l3scacy47yw3b2adgbxmfab2ybmkarljaggbey","signature":{"sig":"i_TLUMJVJb6n6X-5_lKvBibiLvP0RUVz2tn20KJTw5Q_lQ-tcVt9jrZr4s1WVga1CR7q0Ldnrc-EjNpqgaY7GpnhE2d3pC3nfNhUKkmN1za6h9SwCEUuo3CByNnmnqYE","bv":"__f9"}}} +pubsub handling error: message did not add any signatures +pubsub handling error: message did not add any signatures +tx id: bef70add6d21cd812cf68da2caee72da05de48b4 +contract id: vsc1Bem8RnoLgGPP7E2MBN52ekrdVqy2LNpSqF +Error in subscription: subscription cancelled +``` + +--- + +## Call Contract + +Contracts may be called from L1 using Hive accounts or on VSC using offchain accounts. + +### Call From L1 + +Contract invokation from L1 involves sending a `custom_json_operation` with `vsc.call` as its ID and the following JSON format: + +```json +{ + "net_id": "vsc-mainnet", + "contract_id": "vsc1...", + "action": "methodName", + "payload": "your payload string here", + "rc_limit": 2000, + "intents": [] +} +``` + +An example transaction may be seen [here](https://hivehub.dev/tx/8e384c116bdc6c585340a36ba29bdd67652358c2). + +### Intents + +A contract call transaction may include a list of `intents` which authorizes the contract to spend up to a specific amount of assets from your account. For example, an intent of 1 HIVE allowance may be specified as follows: + +```json +{ + "type": "transfer.allow", + "args": { + "limit": "1.000", + "token": "hive" + } +} +``` \ No newline at end of file diff --git a/src/content/docs/References/Smart Contract Template.md b/src/content/docs/References/Smart Contract Template.md deleted file mode 100644 index e96b728..0000000 --- a/src/content/docs/References/Smart Contract Template.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Smart Contract Template -sidebar: - order: 14 ---- - - -Smart contracts on VSC are compiled using AssemblyScript. This is a template project to get started writing smart contracts. - -### General Tips - -For smart contract specific functionality, use the `@vsc.eco/sdk/assembly` module. For more general functionality, use the `assemblyscript/std/assembly` module. It contains useful data structures and functions that are usable in the smart contract. - -**Note:** If you see a missing module error during testing, it is likely that that part of the AssemblyScript standard library is not yet supported by VSC contracts. - -## Scripts - -- `deploy`: Compiles & deploys a release build of the smart contract. - **Note:** Ensure both `HIVE_ACCOUNT_USERNAME` and `HIVE_ACCOUNT_ACTIVE_PRIVATE_KEY` are set in your environment or in the `.env` file in the root of this project. They are both used to deploy the smart contract via a `custom-json` operation on Hive. - -- `asbuild:debug`: Compiles a debug build of the smart contract. This is used in both test environments. Used to manually compile this for the code changes to be reflected in the tests. - -- `asbuild:debug-live`: Observes the changes in the smart contract and compiles a debug build on changes. This is best used in conjunction with `test:debug` for a small feedback loop. - -- `test`: Runs the tests using `jest`. This is good for CI or running individual tests without debugging support. - -- `test:debug`: Runs the tests using `mocha` & `vite`. This runs tests in the browser with sourcemap support allowing breakpoint debugging your smart contract with the original AssemblyScript source code. - -## Folder Structure - -- `assembly`: Where your smart contract source code lives. -- `build`: Where the build artifacts are placed. -- `scripts`: Where scripts live. -- `tests`: Where your tests live. - -## Libraries - -The following libraries are supported by VSC smart contracts: - -- `@vsc.eco/sdk/assembly`: The VSC smart contract SDK. This library serves general purposes and provides various smart contract specific functionality. -- `as-bigint`: A very handy [library for simple arithmetic](https://github.com/polywrap/as-bigint) with large numbers. Also useful when an operation like taking the power of a number is required (`**` operator), as AssemblyScript does not natively support this. diff --git a/src/content/docs/References/sdk.md b/src/content/docs/References/sdk.md deleted file mode 100644 index 6a3a179..0000000 --- a/src/content/docs/References/sdk.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: SDK -sidebar: - order: 13 ---- - - -## NOTE: THIS SECTION HAS NOT BEEN UPDATED FOR MAINNET VSC (PROCEED WITH CAUTION) - -# SDK - -The VSC sdks are libraries that abstract away various functionalities that are useful in the context of coding a VSC smart contract. - -> Nice to know: They also serve access to e.g. the smart contract's database layer by exposing namespaces and interfaces. At the stage of the contract execution, invocations of such interfaces are translated to generalized calls of the VSC node. Thereby ensuring that those functionalities are equal regardless of the language implementation of the SDK. - -## VSC javascript (assemblyscript) sdk - -The [VSC javascript sdk](https://github.com/vsc-eco/sdk) is a library that is compatible with assemblyscript projects, thereby it can be used directly in the [contract template](git@github.com:vsc-eco/contract-template.git). It is included in the project by default. - -The API documentation can be found [here](https://vsc-eco.github.io/sdk/). - -### Example usage - -Import the library. - -```typescript -import { db, console } from "@vsc.eco/sdk/assembly"; -``` - -Execute a function. - -```typescript -export function mySampleMethod(payload: String): string { - ... - db.setObject("key-1", payload); - const val = db.getObject("key-1"); - console.log(val) - ... -} -``` - -### Frequently used - -**namespace db** -- db.setObject -- db.getObject - -**namespace arrays** -- Arrays.toHexString -- Arrays.fromHexString - -**namespace console** -- console.log - -**no namespace** -- getEnv \ No newline at end of file diff --git a/src/content/docs/References/sdk.mdx b/src/content/docs/References/sdk.mdx new file mode 100644 index 0000000..02d0372 --- /dev/null +++ b/src/content/docs/References/sdk.mdx @@ -0,0 +1,430 @@ +--- +title: SDK +sidebar: + order: 13 +--- + +import { Aside } from '@astrojs/starlight/components' + +The VSC SDK is a library that abstract away various functionalities that are useful in the context of writing a VSC smart contract. + + + +## Go Contract SDK + +The [Go contract SDK](https://github.com/vsc-eco/go-contract-template) implements the necessary runtime and SDK functions for the VSC smart contract environment. + +### Example Usage + +```go +package main + +import ( + "contract-template/sdk" +) + +//go:wasmexport entrypoint +func Entrypoint(a *string) *string { + sdk.Log(*a) + sdk.Log("Entrypoint logged") + return a +} +``` + +### SDK Methods + +The below methods are within the `sdk` namespace. All parameters and return types are `*string`. + +#### Log + +Log a string for debugging purposes. Logs emitted will also be appended to the contract output which may be useful for external applications (i.e. indexers). + +```go +//go:wasmexport entrypoint +func Entrypoint(a *string) *string { + // ... + sdk.Log(*a) + sdk.Log("hello world") + // ... +} +``` + +#### SetObject + +Set the value of a key in the contract database. + +```go +//go:wasmexport setString +func SetString(a *string) *string { + // ... + sdk.StateSetObject("myString", *a) + // ... +} +``` + +#### GetObject + +Retrieve the value of a key from the contract database. + +```go +//go:wasmexport getString +func GetString(a *string) *string { + // ... + value := sdk.StateGetObject("myString") + // ... +} +``` + +#### DelObject + +Delete the value of a key in the contract database. + +```go +//go:wasmexport clearString +func ClearString(a *string) *string { + // ... + sdk.StateDeleteObject("myString") + // ... +} +``` + +#### GetEnv + +Retrieve the current runtime environment variables, returning an object of [`Env` struct](https://github.com/vsc-eco/go-contract-template/blob/main/sdk/env.go). + +```go +//go:wasmexport dumpEnv +func DumpEnv(a *string) *string { + // ... + envs := sdk.GetEnv() + // ... +} +``` + +#### GetEnvKey + +Retrieve an environment variable by key. List of variable names are listed [below](#env-vars). + +```go +//go:wasmexport dumpEnvKey +func DumpEnvKey(a *string) *string { + // ... + contract_id := sdk.GetEnvKey("contract.id") + // ... +} +``` + +#### GetBalance + +Retrieve the balance of any VSC account or contract. + +```go +//go:wasmexport getBalance +func GetBalance(a *string) *string { + // ... + bal := sdk.GetBalance("hive:vaultec.vsc", sdk.AssetHive) // result in terms of mHIVE/mHBD + // ... +} +``` + +#### Draw + +Transfer assets from caller account to the contract up to the limit specified in `intents`. The transaction must be signed using active authority for Hive accounts. + +```go +//go:wasmexport drawBalance +func DrawBalance(a *string) *string { + // ... + sdk.HiveDraw(1000, sdk.AssetHive) // Draw 1 HIVE from caller + // ... +} +``` + +#### Transfer + +Transfer assets from the contract to another account. + +```go +//go:wasmexport transferBalance +func TransferBalance(a *string) *string { + // ... + sdk.HiveTransfer("hive:vaultec.vsc", 1000, sdk.AssetHive) // Transfer 1 HIVE from contract + // ... +} +``` + +#### Withdraw + +Unmap assets from the contract to a specified Hive account. + +```go +//go:wasmexport unmapBalance +func UnmapBalance(a *string) *string { + // ... + sdk.HiveWithdraw("hive:vaultec.vsc", 1000, sdk.AssetHive) // Withdraw 1 HIVE from contract + // ... +} +``` + +#### Contract State Get + +Read the value of a key from the state of another contract. + +```go +//go:wasmexport contractGetString +func ContractGetString(a *string) *string { + // ... + value := sdk.ContractStateGet("anotherContractId", "myString") + // ... +} +``` + +#### Contract Call + +Call another contract, returning the resulting value to the caller. + + + +```go +//go:wasmexport contractCall +func ContractCall(a *string) *string { + // ... + // Call another contract with 1 HIVE allowance, allowing the other contract to draw up to 1 HIVE from this contract. + ret := sdk.ContractCall("anotherContractId", "methodName", "payload", &sdk.ContractCallOptions{ + Intents: []sdk.Intent{{ + Type: "transfer.allow", + Args: map[string]string{ + "token": "hive", + "limit": "1.000", + }, + }}, + }) + + // Call another contract without options. + ret2 := sdk.ContractCall("anotherContractId", "methodName2", "payload", nil) + // ... +} +``` + +#### Abort + +Abort contract execution and revert transaction. + +```go +//go:wasmexport abortMe +func AbortMe(a *string) *string { + // ... + sdk.Abort("something went wrong") + // ... +} +``` + +#### Revert + +Abort contract execution and revert transaction in the same way as `sdk.Abort()` but with error symbol. + +```go +//go:wasmexport revertMe +func RevertMe(a *string) *string { + // ... + sdk.Revert("something went wrong", "some_error_code") + // ... +} +``` + +## Env Vars + +|Variable|Description| +|-|-| +|`contract.id`|ID of the current contract| +|`contract.owner`|Owner of the current contract| +|`tx.id`|ID of the transaction| +|`tx.index`|Transaction position in block| +|`tx.op_index`|Operation position in transaction| +|`block.id`|L1 block ID in which the transaction is included in. For offchain transactions, this refers to the L1 block ID of the VSC block in which the transaction was included in.| +|`block.height`|L1 block number in which the transaction is included in. For offchain transactions, this refers to the L1 block number of the VSC block in which the transaction was included in.| +|`block.timestamp`|Timestamp of when the transaction was included in (i.e. `2025-07-26T14:10:42`).| +|`msg.sender`|Address of the transaction sender. This must be a user address. If there are multiple, the first account specified in `required_auths` or `required_posting_auths` is returned.| +|`msg.required_auths`|The `required_auths` field of the transaction.| +|`msg.required_posting_auths`|The `required_posting_auths` field of the transaction.| +|`msg.caller`|The address that is calling the contract. It can be a contract ID or user address.| +|`intents`|List of intents passed into the transaction (i.e. token allowance).| + +## Error Symbols + +|Symbol|Description| +|-|-| +|`runtime_error`|Generic WASM runtime error.| +|`runtime_abort`|Transaction execution aborted at runtime.| +|`ic_invalid_payload`|Invalid intercontract call payload.| +|`ic_contract_not_found`|Contract being called by another contract does not exist.| +|`ic_contract_get_error`|Error occured when fetching contract info during intercontract call.| +|`ic_code_fetch_error`|Error occured when fetching contract code during intercontract call.| +|`ic_cid_decode_error`|Error occured when decoding contract code CID during intercontract call.| +|`ic_recursion_limit_hit`|Intercontract call recursion depth limit hit.| +|`gas_limit_hit`|WASM gas limit exceeded due to insufficient RC limit.| +|`sdk_error`|Generic SDK call error.| +|`missing_required_auth`|Missing required authority.| +|`env_var_error`|Failed to serialize or parse environment variables.| +|`ledger_error`|Failed to execute token transfer (i.e. due to insufficient balance).| +|`ledger_intent_error`|Missing intents or attempting to draw balances above the specified limit.| +|`wasm_init_error`|Failed to initialize WASM execution context.| +|`wasm_ret_error`|Contract call did not return exactly one value.| +|`wasm_function_not_found`|Attempting to call a non-existent method.| +|`unknown_error`|Errors raised at runtime without any specified error symbol.| + +## Contract Test Utils + +The contract test utils provides a testing environment that lets you execute your contracts. + +### Instantiation + +Create a new contract test environment. + +```go +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/vsc-eco/go-vsc-node/lib/test_utils" + "github.com/vsc-eco/go-vsc-node/modules/db/vsc/contracts" + ledgerDb "github.com/vsc-eco/go-vsc-node/modules/db/vsc/ledger" + stateEngine "github.com/vsc-eco/go-vsc-node/modules/state-processing" +) + +func TestContract(t *testing.T) { + ct := test_utils.NewContractTest() +} +``` + +### Increment Blocks + +Increment a specified number of L1 blocks in the contract testing environment. The block height starts from 0 during instantiation. + +```go +func TestContract(t *testing.T) { + // ... + ct.IncrementBlocks(20) + // ... +} +``` + +### Register Contract + +Bind a WASM bytecode to a contract ID with a specified owner. + +```go +//go:embed artifacts/main.wasm +var ContractWasm []byte + +func TestContract(t *testing.T) { + // ... + ct.RegisterContract("vsccontractid", "hive:someone", ContractWasm) + // ... +} +``` + +### Call Contract + +Executes a contract call transaction. Returns the call result, gas used and logs emitted. + +```go +func TestContract(t *testing.T) { + // ... + result, gasUsed, logs := ct.Call(stateEngine.TxVscCallContract{ + Self: stateEngine.TxSelf{ + TxId: "sometxid", + BlockId: "abcdef", + Index: 69, + OpIndex: 0, + Timestamp: "2025-09-03T00:00:00", + RequiredAuths: []string{"hive:someone"}, + RequiredPostingAuths: []string{}, + }, + ContractId: contractId, + Action: "yourMethodName", + Payload: json.RawMessage([]byte("1000")), + RcLimit: 1000, + Intents: []contracts.Intent{{ + Type: "transfer.allow", + Args: map[string]string{ + "limit": "1.000", + "token": "hive", + }, + }}, + }) + assert.True(t, result.Success) + assert.LessOrEqual(t, gasUsed, uint(10000000)) + assert.GreaterOrEqual(t, len(logs), 1) + // ... +} +``` + +### Deposit + +Add funds to an account in the ledger. + +```go +func TestContract(t *testing.T) { + // ... + ct.Deposit("hive:someone", 1000, ledgerDb.AssetHive) // deposit 1 HIVE + ct.Deposit("hive:someone", 1000, ledgerDb.AssetHbd) // deposit 1 HBD + // ... +} +``` + +### Get Balance + +Retrieve the current balance of an account. + +```go +func TestContract(t *testing.T) { + // ... + bal := ct.GetBalance("hive:someone", ledgerDb.AssetHive) + assert.Equal(t, int64(1000), bal) + // ... +} +``` + +### State Set + +Set the value of a key in the contract state storage. + +```go +func TestContract(t *testing.T) { + // ... + ct.StateSet("vsccontractid", "someKey", "hi") + // ... +} +``` + +### State Get + +Retrieve the value of a key from the contract state storage. + +```go +func TestContract(t *testing.T) { + // ... + val := ct.StateGet("vsccontractid", "someKey") + assert.Equal(t, "hi", val) + // ... +} +``` + +### State Delete + +Unset the value of a key in the contract state storage. + +```go +func TestContract(t *testing.T) { + // ... + ct.StateDelete("vsccontractid", "someKey") + assert.Equal(t, "", ct.StateGet("vsccontractid", "someKey")) + // ... +} +``` \ No newline at end of file diff --git a/src/content/docs/Technology/Execution Environment.md b/src/content/docs/Technology/Execution Environment.md index fbccf04..e25cf00 100644 --- a/src/content/docs/Technology/Execution Environment.md +++ b/src/content/docs/Technology/Execution Environment.md @@ -43,7 +43,7 @@ VSC supports smart contracts compiled to **WebAssembly (WASM)**, enabling develo VSC currently supports contract development in: - **Golang** – Suitable for lower-level or system-focused contracts -- **AssemblyScript** – A TypeScript-like language with a lightweight footprint and WebAssembly compatibility +- ~~**AssemblyScript** – A TypeScript-like language with a lightweight footprint and WebAssembly compatibility~~ Contracts can be compiled to WASM and deployed to the VSC network using SDKs or developer tooling provided by the protocol. Supporting familiar and performant languages lowers the barrier to entry and reduces time-to-deploy for new applications.