Day 16【web3.js】I KNOW BINARY AND HEXADECIMAL

i-know-binary-and-hexadecimal.jpg

【前言】
今天来介绍 we3.eth.contractweb3.utis,有一些概念还不太熟悉所以需要一点时间消化一下啊!话说铁人赛的进度超过一半了,可喜可贺我还活着!

不过大家知道吗其实我大一才知道二进位怎麽得到,然後此时此刻才知道十六进位怎麽换算,呵呵。

【we3.eth.Contract】
web3.eth.Contract 可以轻易地和以太坊区块链上的智能合约互动。如果他们属於 JavaScript 的物件。

var Contract = require('web3-eth-contract');

// set provider for all later instances to use
Contract.setProvider('ws://localhost:8546');

var contract = new Contract(jsonInterface, address);

contract.methods.somFunc().send({from: ....})
.on('receipt', function(){
    ...
});

创建一个新的合约,其方法和事件会被定义在 JSON 介面物件里。

new web3.eth.Contract(jsonInterface[, address][, options])

// Example
var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', {
    from: '0x1234567890123456789012345678901234567891', // default from address
    gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
});

【we3.eth.Contract.method】

we3.eth.Contract.method 创建一个可以被 called, send, estimated 以及 ABI encoded 的交易物件。

透过以下方法都可以从 JavaScript 的合约物件中,成功呼叫拥有同样名子却不同参数的函数。

  • The name: myContract.methods.myMethod(123)
  • The name with parameters: myContract.methods['myMethod(uint256)'](123)
  • The signature: myContract.methods['0x58cf5f10'](123)
myContract.methods.myMethod([param1[, param2[, ...]]])

Parameters
需要什麽参数由智能合约里面的方法而定,而其方法被定义在 JSON 介面物件里。
Returns
Object: The transaction object:

  • Array - arguments: The arguments passed to the method before. They can be changed.
  • Function - call: Will call the “constant” method and execute its smart contract method in the EVM without sending a transaction (Can’t alter the smart contract state).
  • Function - send: Will send a transaction to the smart contract and execute its method (Can alter the smart contract state).
  • Function - estimateGas: Will estimate the gas used when the method would be executed on chain. Note: You must specify a from address otherwise you may experience odd behavior.
  • Function - encodeABI: Encodes the ABI for this method. This can be send using a transaction, call the method or passing into another smart contracts method as argument.

其中 encodeABI 是一个相当重要的函式,因为我们要透过 encodeABI 来取得某些智能合约的方法。

methods.myMethod.call 将会呼叫一个在智能合约中的函数於 EVM 上,并且不会执行任何交易动作也不会改变当前智能合约的任何状态。

myContract.methods.myMethod([param1[, param2[, ...]]]).call(options [, defaultBlock] [, callback])

// Example

// Solidity
contract MyContract {
    function myFunction() returns(uint256 myNumber, string myString) {
        return (23456, "Hello!%");
    }
}

// web3.js
var MyContract = new web3.eth.Contract(abi, address);
MyContract.methods.myFunction().call()
.then(console.log);
> Result {
    myNumber: '23456',
    myString: 'Hello!%',
    0: '23456', // these are here as fallbacks if the name is not know or given
    1: 'Hello!%'
}

Parameters

  1. options - Object (optional): The options used for calling.
    from - String (optional): The address the call “transaction” should be made from. For calls the from property is optional however it is highly recommended to explicitly set it or it may default to address(0) depending on your node or provider.
    gasPrice - String (optional): The gas price in wei to use for this call “transaction”.
    gas - Number (optional): The maximum gas provided for this call “transaction” (gas limit).
  2. defaultBlock - Number|String|BN|BigNumber (optional): If you pass this parameter it will not use the default block set with contract.defaultBlock. Pre-defined block numbers as "earliest""latest", and "pending" can also be used. Useful for requesting data from or replaying transactions in past blocks.
  3. callback - Function (optional): This callback will be fired with the result of the smart contract method execution as the second argument, or with an error object as the first argument.
    Returns
    Promise returns Mixed: The return value(s) of the smart contract method. If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices:

【web3.utis】
web3.utis ****提供以太坊 Dapp 开发者可能会需要用到的功能函数。

十六进位(Hex, 下标16)一般用数字 0 到 9 和字母 A 到 F 表示,其中 A~F 相当於十进位的 10~15,以下 web3.utis 提供几个有用的十六进位工具。

// Hex
web3.utils.randomHex(size)
web3.utils.isHex(hex) 
// web3.utils.isHex(345) -> true
// web3.utils.isHex('0xZ1912') -> false
web3.utils.toHex(mixed)
// web3.utils.toHex('234') -> "0xea"
web3.utils.hexToNumber(hex)
// web3.utils.hexToNumber('0xea') -> 234
web3.utils.utf8ToHex(string)
// web3.utils.utf8ToHex('I have 100€') -> "0x49206861766520313030e282ac"
web3.utils.asciiToHex(string)
// web3.utils.asciiToHex('I have 100!') -> "0x4920686176652031303021"
web3.utils.bytesToHex(byteArray)
// web3.utils.bytesToHex([ 72, 101, 108, 108, 111, 33, 36 ]) -> "0x48656c6c6f2125"

关於 Ethereum address 的 checksum 我们可以从 EIP-55 这个文件中找到端倪!这里就不多加叙述了,里面有程序码告诉大家怎麽转成 checksum 和转回来!

// Address
web3.utils.isAddress(address)
// Checks if a given string is a valid Ethereum address by checksum
web3.utils.toChecksumAddress(address) 
// Will convert an upper or lowercase Ethereum address to a checksum address.
web3.utils.checkAddressChecksum(address)
// true when the checksum of the address is valid, false if its not a checksum address, or the checksum is invalid.

EIPs/eip-55.md at master · ethereum/EIPs

这个跟 BigNumber.js 这个套件有异曲同工之妙!

//BN
web3.utils.toBN(number)
web3.utils.BN(mixed)

// Example
var BN = web3.utils.BN;
new BN(1234).toString();
> "1234"
new BN('1234').add(new BN('1')).toString();
> "1235"
new BN('0xea').toString();
> "234"

SHA-3 为第三代安全杂凑演算法(Secure Hash Algorithm 3)。这边要注意的是 Solidity 使用的是 KECCAK-256 演算法,而非 FIPS-202 based standard (a.k.a SHA-3)。详情可以看参考资料里面的解释。

// SHA3
web3.utils.sha3(string)
web3.utils.soliditySha3(param1 [, param2, ...])
// Will calculate the sha3 of given input parameters in the same way solidity would. 
// This means arguments will be ABI converted and tightly packed before being hashed.
// This method poses a security risk where multiple inputs can compute to the same hash.

// Example
web3.utils.soliditySha3({type: 'string', value: 'hell'},{type: 'string', value: 'oworld'},{type: 'uint16', value: 0x3031})
// "0xfb0a9d38c4dc568cbd105866540986fabf3c08c1bfb78299ce21aa0e5c0c586b"
web3.utils.soliditySha3({type: 'uint96', value: '32309054545061485574011236401'})
// "0xfb0a9d38c4dc568cbd105866540986fabf3c08c1bfb78299ce21aa0e5c0c586b"

【小结】
大概简单整理了一下之後在 web3.js 里面可能会用到的函数,看起来非常的实用阿,明天要进到 ethers.js 的笔记,不知道是不是一样香呢!
5ZQpwhxh3RdENlimZ0LV5mdctiU2KfK2-rZjifq2Y4k.jfif

【参考资料】
web3.js - Ethereum JavaScript API - web3.js 1.0.0 documentation
Why aren't Solidity sha3 hashes not matching what other sha3 libraries produce?
Which cryptographic hash function does Ethereum use?


<<:  [Day28]Hashmat the brave warrior

>>:  【在 iOS 开发路上的大小事-Day16】透过 Firebase 来管理使用者 (Sign in with E-mail 篇) Part2

12 | WordPress 图库区块 Gallery Block

这次讨论的《图库区块》应用,图库区块可让你轻松地新增多张相片,并以引人入胜的方式自动排列相片。是《...

Day 26 阿里云上运行Kubernetes 2 - ACK

接续昨天,我们建立完集群,也连上集群了来创立ngin服务吧 我们先查看一下丛集讯息 查看集群 kub...

day7 来管理 firewall 吧 (雷)没人知道答案的问题

来部落格看图文并茂文章 补觉鸣诗 firewall 跟 switch 一样,也是存在各种厂牌 好在没...

[Day18] 箭头函式

Arrow Function 这个从 ES6 开始新增的一种写法,叫做 Arrow Function...

企划实现(21)

接续上篇继续提到关於有限公司以及股份有限公司的差别。 有限公司以及股份有限公司除了制度会有差别外,责...