Simple Example of DAPP

Use truffle to init Project

Contract of Adoption

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// contracts/Adoption.sol
pragma solidity ^0.4.4;


constract Adoption {
address[16] public adopters;

function adopt (uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}

function getAdopters () public returns (addresss[16]) {
return adopters;
}
}

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// test/TestAdoption.sol
pragma solidity ^0.4.4;

import "truffle/Assert.sol";
import "truffle/DeployedAddress.sol";
import "../contracts/Adoption.sol";


contract TestAdoption {
Adoption adoption = Adoption(DeployedAddress.Adoption());
function testUserCanAdoptPet () {
uint returnedPetId = adoption.adopt(8);
uint expected = 8;
Assert.equal(returenedPetId, expected, "Adoption of Pet Id 8 should be recorded");
}

function testGetAdopterAddressByPetId () {
address expected = this;
address adopter = adoption.adopters(8);
Assert.equal(adopter, expected, "Owner of Pet Id 8 should be recorded");
}

function testGetAdopterAddressByPetIdInArray () {
address expected = this;
address[16] memory adopters = adoption.getAdopters();
Assert(expected, adopters[8], "Owner of Pet Id 8 should be recoreded");
}
}

Compile

Migrate

TestRPC

MetaMask

UI

initWeb3

1
2
3
4
5
6
7
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider
web3 = new Web3(App.web3Provider)
} else {
App.web3Provider = new web3.providers.HttpProvider('http://localhost:8545')
web3 = new Web3(App.web3Provider)
}

initContract

1
2
3
4
5
$.JSON('Adoption.json', function (data) {
const AdoptionArtifact = data
App.contracts.Adoption = TruffleContract(AdoptionArtifact)
App.contracts.Adoption.setProvider(App.web3Provider)
})

Invoke Contract

1
2
3
4
5
6
7
8
9
let adoptionInstance
App.contracts.Adoption.deployed()
.then(function (instance) {
adoptionInstance = instance
return adoptionInstance.getAdopters.call()
})
.then(function (adopters) {
// ...
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const petId = 8
let adoptionInstance
web3.eth.getAccounts(function (error, accounts) {
if (error) {
console.error(error.message)
}
const account = accounts[0]
App.contracts.Adoption.deployed()
.then(function (instance) {
adoptionInstance = instance
return adoptionInstance.adopt(petId, { from: account })
})
.then(function (result) {
// ...
})
})

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×