Skip to content

智能合约

智能合约是运行在链上的程序。 它是位于区块链上一个特定地址的一系列代码(函数)和数据(状态)。

智能合约也是一个帐户,我们称之为合约帐户。它们有余额,可以成为交易的对象。他们是被部署在网络上作为程序运行着。 个人用户可以通过提交交易执行智能合约的某一个函数来与智能合约进行交互。 智能合约能像常规合约一样定义规则,并通过代码自动强制执行。 默认情况下,你无法删除智能合约,与它们的交互是不可逆的。

ABI

应用程序二进制接口,简单来说就是以太坊调用合约时的接口说明;不同的合约使用不同的 ABI,调用合约时需要先拿到合约的 ABI。

以太坊上 USDT 合约地址及对应 ABI 如下:

json
[
  {
    "constant": true,
    "inputs": [],
    "name": "name",
    "outputs": [{ "name": "", "type": "string" }],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "_totalSupply",
    "outputs": [{ "name": "", "type": "uint256" }],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  ...
  { "anonymous": false, "inputs": [], "name": "Unpause", "type": "event" }
]
[
  {
    "constant": true,
    "inputs": [],
    "name": "name",
    "outputs": [{ "name": "", "type": "string" }],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "_totalSupply",
    "outputs": [{ "name": "", "type": "uint256" }],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  },
  ...
  { "anonymous": false, "inputs": [], "name": "Unpause", "type": "event" }
]

合约初始化

你可以使用多种库与智能合约交互,如 web3.js

初始化合约如下

js
import Web3 from 'web3'

const web3 = new Web3(provider);

const abi = [{"constant":true,"inputs":[],...}];

const contractAddress = '0xdAC17F958D2ee523a2206206994597C13D831ec7';//usdt contract address

const contract = new web3.eth.Contract(abi, contractAddress);
import Web3 from 'web3'

const web3 = new Web3(provider);

const abi = [{"constant":true,"inputs":[],...}];

const contractAddress = '0xdAC17F958D2ee523a2206206994597C13D831ec7';//usdt contract address

const contract = new web3.eth.Contract(abi, contractAddress);

注意:provider 必须对应所选钱包

合约方法调用

数据读取 methods.myMethod.call

js
contract.methods.myMethod(...args).call(); //返回 promise 对象

await usdtContract.methods.name().call(); // => Tether USD

await usdtContract.methods.totalSupply().call(); // => 51998545629548753

await usdtContract.methods.balances("your address").call(); // your balances
contract.methods.myMethod(...args).call(); //返回 promise 对象

await usdtContract.methods.name().call(); // => Tether USD

await usdtContract.methods.totalSupply().call(); // => 51998545629548753

await usdtContract.methods.balances("your address").call(); // your balances

gas 费预估

js
contract.methods.myMethod(...args).estimateGas({
  from: "your address",
});
contract.methods.myMethod(...args).estimateGas({
  from: "your address",
});

数据上链

js
contract.methods.myMethod(...args).send({
  from: "your address",
});
contract.methods.myMethod(...args).send({
  from: "your address",
});

等等其他合约方法。

相关阅读