【前言】
今天來介紹 we3.eth.contract
和 web3.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 的合約物件中,成功呼叫擁有同樣名子卻不同參數的函數。
myContract.methods.myMethod(123)
myContract.methods['myMethod(uint256)'](123)
myContract.methods['0x58cf5f10'](123)
myContract.methods.myMethod([param1[, param2[, ...]]])
Parameters
需要什麼參數由智能合約裡面的方法而定,而其方法被定義在 JSON 介面物件裡。
ReturnsObject
: 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
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).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.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.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 的筆記,不知道是不是一樣香呢!
【參考資料】
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?