Examples

This page contains examples of smart contracts

Chat

A chat is an object with a property messages that is initially empty. It has a function invite that adds another user to the _owners array thereby giving them write access (only the creator has write access initially). Once invited a user can call post to send a message to the chat and invite other users.

class Chat {
constructor() {
this.messages = []
}
invite(pubKey) {
this._owners.push(pubKey)
}
post(messages) {
this.messages.push(message)
}
}

Non-Fungible tokens

A non-fungible token is an object that has some state. In the example below the entire state is stores in a property state. The token has a function setState to update the state and a functionsendto assign a new owner.

class Token {
constructor(state) {
this.state = state
}
setState(state) {
this.state = state
}
send(to) {
this._owners = [to]
}
}

Fungible Token

The example below shows how a fungible token, similar to an ERC20 token, can be implemented. The constructor creates a new coin that stores a number of tokens. When a user sends a token to another user a new coin is created.

class Coin {
constructor(supply, to) {
this.tokens = supply
this._owners = [to]
}
send(amount, to) {
if(this.tokens < amount) throw new Error()
this.tokens -= amount
return new Coin(amount, to)
}
}