showing results for - "web3 js example"
Nicolas
24 Nov 2018
1// Here's how we would access our contract:
2var abi = /* abi generated by the compiler */
3var ZombieFactoryContract = web3.eth.contract(abi)
4var contractAddress = /* our contract address on Ethereum after deploying */
5var ZombieFactory = ZombieFactoryContract.at(contractAddress)
6// `ZombieFactory` has access to our contract's public functions and events
7
8// some sort of event listener to take the text input:
9$("#ourButton").click(function(e) {
10  var name = $("#nameInput").val()
11  // Call our contract's `createRandomZombie` function:
12  ZombieFactory.createRandomZombie(name)
13})
14
15// Listen for the `NewZombie` event, and update the UI
16var event = ZombieFactory.NewZombie(function(error, result) {
17  if (error) return
18  generateZombie(result.zombieId, result.name, result.dna)
19})
20
21// take the Zombie dna, and update our image
22function generateZombie(id, name, dna) {
23  let dnaStr = String(dna)
24  // pad DNA with leading zeroes if it's less than 16 characters
25  while (dnaStr.length < 16)
26    dnaStr = "0" + dnaStr
27
28  let zombieDetails = {
29    // first 2 digits make up the head. We have 7 possible heads, so % 7
30    // to get a number 0 - 6, then add 1 to make it 1 - 7. Then we have 7
31    // image files named "head1.png" through "head7.png" we load based on
32    // this number:
33    headChoice: dnaStr.substring(0, 2) % 7 + 1,
34    // 2nd 2 digits make up the eyes, 11 variations:
35    eyeChoice: dnaStr.substring(2, 4) % 11 + 1,
36    // 6 variations of shirts:
37    shirtChoice: dnaStr.substring(4, 6) % 6 + 1,
38    // last 6 digits control color. Updated using CSS filter: hue-rotate
39    // which has 360 degrees:
40    skinColorChoice: parseInt(dnaStr.substring(6, 8) / 100 * 360),
41    eyeColorChoice: parseInt(dnaStr.substring(8, 10) / 100 * 360),
42    clothesColorChoice: parseInt(dnaStr.substring(10, 12) / 100 * 360),
43    zombieName: name,
44    zombieDescription: "A Level 1 CryptoZombie",
45  }
46  return zombieDetails
47}
48