Skip to content Search Apps Documentation Source Content File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

contract.gno

1.08 Kb · 45 lines
 1// based on Wikipedia's Solidity example: https://en.wikipedia.org/wiki/Solidity
 2package wikicoin
 3
 4import (
 5	"chain/runtime/unsafe"
 6
 7	"gno.land/p/nt/avl/v0"
 8	"gno.land/p/nt/ufmt/v0"
 9)
10
11var balances = avl.NewTree() // addr -> balance
12var minter address
13
14// Constructor code is only run when the contract is created
15func init() {
16	minter = unsafe.OriginCaller()
17}
18
19func Mint(cur realm, receiver address, amount uint) {
20	if unsafe.OriginCaller() != minter {
21		panic("restricted")
22	}
23	curBalance := BalanceOf(receiver)
24	newBalance := curBalance + amount
25	balances.Set(receiver.String(), newBalance)
26}
27
28func Send(cur realm, receiver address, amount uint) {
29	sender := unsafe.OriginCaller()
30	senderBalance := BalanceOf(sender)
31	if amount > senderBalance {
32		panic(ufmt.Sprintf("insufficient balance: %d", senderBalance))
33	}
34	receiverBalance := BalanceOf(receiver)
35	balances.Set(sender.String(), senderBalance-amount)
36	balances.Set(receiver.String(), receiverBalance+amount)
37}
38
39func BalanceOf(addr address) uint {
40	balance := balances.Get(addr.String())
41	if balance == nil {
42		return 0
43	}
44	return balance.(uint)
45}