Call each other between Solidity contracts

Take calling MetaCoin as an example

Deploy MetaCoin Contract

1. Download MetaCoin

mkdir MetaCoin
cd MetaCoin
truffle unbox metacoin

2. Migrate MetaCoin to the local ganache network

truffle migrate --reset

3. Get the address of the contract

4. MetaCoin contract code

pragma solidity >=0.4.25 <0.7.0;

import "./ConvertLib.sol";

contract MetaCoin {
	mapping (address => uint) balances;

	event Transfer(address indexed _from, address indexed _to, uint256 _value);

	constructor() public {
		balances[tx.origin] = 10000;
	}

	function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
		if (balances[msg.sender] < amount) return false;
		balances[msg.sender] -= amount;
		balances[receiver] += amount;
		emit Transfer(msg.sender, receiver, amount);
		return true;
	}

	function getBalanceInEth(address addr) public view returns(uint){
		return ConvertLib.convert(getBalance(addr),2);
	}

	function getBalance(address addr) public view returns(uint) {
		return balances[addr];
	}
}

The following creates a test project to call the getBalance method of the MetaCoin contract. 

Create a test project

1. Create an empty project

mkdir testDemo
cd testDemo
truffle init

2. Create contract demo.sol

pragma solidity >=0.6.0 <0.9.0;

interface MetaCoinInterface {
	function getBalance(address addr) external view returns(uint);
}

contract Demo {    
    address private immutable reserveAddress;
    MetaCoinInterface metacoinContract;

    constructor(address _reserveAddress) {
        reserveAddress = _reserveAddress;
    }
    
    modifier onlyOwner() {
        require(msg.sender == reserveAddress, "only owner can call this");
        
        _;
    }

    function setMetaCoin(address _metacoinAddress) public onlyOwner {
        metacoinContract = MetaCoinInterface(_metacoinAddress);
    }

    function getMetaCoinBalance(address addr) public view returns(uint) {
        return metacoinContract.getBalance(addr);
    }
}

3. Create a deployment file 2_deploy_contracts.js

const Demo = artifacts.require("Demo");

module.exports = function(deployer) {
  deployer.deploy(Demo, "发布者的钱包地址");
};

4. Enter the console

truffle console

5. Execute the script

let accounts = await web3.eth.getAccounts()
let instance = await Demo.deployed()

await instance.setMetaCoin("MetaCoin合约地址")
let balance = await instance.getMetaCoinBalance(accounts[0])
balance.toString()

Guess you like

Origin blog.csdn.net/watson2017/article/details/122434244