我建议您使用 web3js 之类的库以编程方式执行此操作,web3js 允许您通过 RPC 网络服务与以太坊网络(帐户、智能合约)进行交互。
在以下示例中,我使用 Truffle 和 Ganache(以太坊的工具和框架)在本地区块链上部署了一个名为 SimpleStorage 的合约。
pragma solidity ^0.4.2;
contract SimpleStorage {
uint public value;
function SimpleStorage() {
value = 1;
}
function setValue(uint val) {
value = val;
}
function getValue() returns(uint) {
return value;
}
}
部署在以太坊区块链上的每个合约都有一个用于您的智能合约的 ABI(应用程序二进制接口)类型的 Swagger。程序使用 ABI 通过 RPC 与智能合约进行交互。
每个合约都部署在一个唯一的地址,例如0x3450226a2fccb0d3668e7c3a730c43ef50ec8a06
1.启动一个nodeJS项目并添加web3js库
$ npm init
$ npm install web3@0.20.6 -s
2。创建一个 JavaScrit 文件index.js
注入依赖
const Web3 = require('web3');
声明节点的 rpc 端点。我使用的是本地区块链,但您可以使用 Infura 轻松连接到 Ropsten 公共节点(取决于您部署的合同网络)
const RPC_ENDPOINT = "http://localhost:8545" //https://ropsten.infura.io
连接到以太坊节点
var web3 = new Web3(new Web3.providers.HttpProvider(RPC_ENDPOINT));
设置默认帐号
web3.eth.defaultAccount = web3.eth.accounts[0]
把你的ABI和智能合约部署的地址放在这里
var abi = [...];
var address = "0x3450226a2fccb0d3668e7c3a730c43ef50ec8a06";
从 abi 加载合约模式
var SimpleStorageContract = web3.eth.contract(abi);
通过地址实例化合约
var simpleStorageContractInstance = SimpleStorageContract.at(address);
调用其中一个 ABI 函数
var value = simpleStorageContractInstance.getValue.call();
console.log("value="+value);
结果:
当我调用 SimpleStorage 合约实例的函数 getValue 时,函数返回 1。
value=1
完整代码:
const Web3 = require('web3');
const RPC_ENDPOINT = "http://localhost:8545"
// Connection to a Ethereum node
var web3 = new Web3(new Web3.providers.HttpProvider(RPC_ENDPOINT));
// Set default account
web3.eth.defaultAccount = web3.eth.accounts[0]
// ABI describes a smart contract interface developped in Solidity
var abi = [
{
"constant": true,
"inputs": [],
"name": "value",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"constant": false,
"inputs": [
{
"name": "val",
"type": "uint256"
}
],
"name": "setValue",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "getValue",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
];
// Address where the smart contract is deployed
var address = "0x3450226a2fccb0d3668e7c3a730c43ef50ec8a06";
// Load the contract schema from the abi
var SimpleStorageContract = web3.eth.contract(abi);
// Instanciate by address
var simpleStorageContractInstance = SimpleStorageContract.at(address);
// Call one of the ABI function
var value = simpleStorageContractInstance.getValue.call();
console.log("value="+value);
项目的 GitHub:
https://github.com/gjeanmart/stackexchange/tree/master/51809356-create-smart-contract-and-use-abi-functions
以太坊 StackExchange
以太坊问题有专门的 StackExchange 社区here