Source code WeChat:kaifa873
ABI对象实例
函数(functions) type:函数类型。默认为 function ,也可能是 constructorstateMutability:状态可变性。 payablenonpayable viewpure inputs,outputs:函数输入输出的参数列表name:函数名称 事件(events)type:event inputs:输入对象列表,包括 name , type , indexedanonymous:是否为匿名的
创建合约
在一个合约中,我们可以编写的内容:函数,结构体,构造函数,状态变量,事件,枚举类型等。一个合约想要部署到区块链,需要编译为字节码文件;一个合约想要被外部的应用程序(如DApp)访问,则需要编译为ABI文件,供应用程序调用。
部署合约 区块链上已经部署了智能合约,通过代码将JS中的合约与链上合约进行关联与交互。直接通过JS代码在区块链上部署一个新合约。
💡 部署新合约
new web3.eth.Contract(abi[, address]) 创建一个合约对象。* [contract].deploy() 部署合约:// 该过程等价于在Remix上部署合约const abi = [ { “inputs”: [ { “internalType”: “uint256”, “name”: “_number”, “type”: “uint256” } ], “name”: “setNumber”, “outputs”: [], “stateMutability”: “nonpayable”, “type”: “function” }, { “inputs”: [], “name”: “getNumber”, “outputs”: [ { “internalType”: “uint256”, “name”: “”, “type”: “uint256” } ], “stateMutability”: “view”, “type”: “function” }]const contract = new web3.eth.Contract(abi, address)const data = ‘608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80633fb5c1cb1461003b578063f2c9ecd814610057575b600080fd5b6100556004803603810190610050919061009d565b610075565b005b61005f61007f565b60405161006c91906100d9565b60405180910390f35b8060008190555050565b60008054905090565b60008135905061009781610103565b92915050565b6000602082840312156100b3576100b26100fe565b5b60006100c184828501610088565b91505092915050565b6100d3816100f4565b82525050565b60006020820190506100ee60008301846100ca565b92915050565b6000819050919050565b600080fd5b61010c816100f4565b811461011757600080fd5b5056fea26469706673582212206d42283bc640e62ba9095ff6f78d7e4a75272960a2332eff853e9968295e534664736f6c63430008070033’ // The data field must be HEX encoded data.contract.deploy({data,}).send({from: ‘0x539CDB50CC507bF167e205d10Df87cd8c1827Af6’,gas: 1000000, // GAS LIMITgasPrice: ‘120000’}, (err, res) => {console.log(‘res’, err, res) // 返回transaction的hash}) #### 💡 与链上合约进行关联与交互
const address = ‘0x8B48aF1b46eFE178014CdD6c90f3DdfbDABC6d67’ // 合约部署地址
const myContract = new web3.eth.Contract(abi, address)
console.log(myContract)
1
2
3