Bitcoin Computer
Search…
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.
1
class Chat {
2
constructor() {
3
this.messages = []
4
}
5
6
invite(pubKey) {
7
this._owners.push(pubKey)
8
}
9
10
post(messages) {
11
this.messages.push(message)
12
}
13
}
Copied!

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.
1
class Token {
2
constructor(state) {
3
this.state = state
4
}
5
6
setState(state) {
7
this.state = state
8
}
9
10
send(to) {
11
this._owners = [to]
12
}
13
}
Copied!

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.
1
class Coin {
2
constructor(supply, to) {
3
this.tokens = supply
4
this._owners = [to]
5
}
6
7
send(amount, to) {
8
if(this.tokens < amount) throw new Error()
9
this.tokens -= amount
10
return new Coin(amount, to)
11
}
12
}
Copied!
Last modified 1yr ago