创建智能合约并使用ABI功能

问题描述 投票:0回答:2

对于最近的测试,要求我使用 Ethernum 生成智能合约,并使用通过 ABI json 提供的一些函数来提取一些信息。 我按照建议使用 https://ropsten.etherscan.io

过去 2 天我研究了 Ethernum,并尝试使用 Solidity Remix 来提取这些信息,但我不明白如何将 ABI 函数与 Solidity Remix 一起使用。

我只有一份地址合约和一份ABI合约。 有人可以向我提供一些信息吗? 谢谢

ethereum solidity smartcontracts
2个回答
0
投票

我建议您使用像 web3js 这样的库以编程方式完成此操作,web3js 允许您通过 RPC Web 服务与以太坊网络(帐户、智能合约)进行交互。

在下面的示例中,我使用 TruffleGanache(以太坊工具和框架)在本地区块链上部署了一个名为 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 [email protected] -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 社区这里


0
投票

正如其他答案所述,有很多方法可以生成智能合约的 ABI 和字节码。但没有办法让 ABI 知道智能合约地址。

但是,我建议使用这个 web3.js 插件来生成 ABI 和字节码。您可以编译智能合约并保存ABI和字节码。或者,您甚至可以直接从 Solidity 代码初始化 web3.js 智能合约实例并开始与其交互。

这是 npm 包: https://www.npmjs.com/package/web3-plugin-craftsman 描述了功能并包含 README.md 文件中提到的示例代码。

这是一步一步的教程:https://medium.com/dapps-decentralized-apps-development/interacting-with-ethereum-smart-contracts-directly-from-solidity-source-code-9caf55457eb8

这是一个完整的示例:

import { ExtendedWeb3 } from 'web3-plugin-craftsman';

const web3 = new Web3('http://localhost:8545'); // your Web3 object

// Using ExtendedWeb3 as a plugin
web3.registerPlugin(new ExtendedWeb3());

const contract = new web3.craftsman.ExtendedContract('./test/smart_contracts/simple-contract.sol');

// now the `contract` instance can be used like any web3.js contract


// Wait for the contract compilation and handle compilation errors if any
try {
  const compilationResult = await contract.compilationResult;
  // the compilationResult will consists of:
  // {
  //     abi: ContractAbi,
  //     bytecodeString: string,
  //     contractName: string,
  // }
} catch (e) {
  console.log(e);
}

// Deploying and interacting with your Contract

// get the accounts provided by your Ethereum node (like Ganache). 
const accounts = await web3.eth.getAccounts();
fromAccount = accounts[0];

// Deploy contract
const deployed = await contract
  .deploy({ arguments: [1000] })
  .send({ from: fromAccount });

// Call a method
const myNumber = await deployed.methods.myNumber().call();

// Send a transaction
await deployed.methods.setMyNumber(100).send({ from: fromAccount });
// If you are using TypeScript you need to ask similar to the following:
//  await(deployed.methods.setMyNumber(100) as any)
//    .send({ from: fromAccount });

// Call a method
const myNumberUpdated = await deployed.methods.myNumber().call();
© www.soinside.com 2019 - 2024. All rights reserved.