FISCO BCOS使用GO SDK设置合约调用者 - 使用私钥加载用户

文章 , 技术分享
298 0

FISCO BCOS使用GO SDK设置合约调用者

设置合约调用者

合约代码:用于实现如set时需要的管理员账户,get可以查询当前管理员地址

pragma solidity ^0.4.25;
contract tranceUser{
    address owner;
    
    constructor(){
        owner = msg.sender;
    }
    
    function set(address _a) public returns(bool) {
        require(owner == msg.sender,"owner can do it");
        owner = _a;
        return true;
    }
    function get() view public returns(string memory){
        return addressToString(owner);
    }
    function addressToString(address _address) internal pure returns (string memory) {
        bytes32 value = bytes32(uint256(uint160(_address)));

        bytes memory alphabet = "0123456789abcdef";

        bytes memory str = new bytes(42);
        str[0] = '0';
        str[1] = 'x';

        for (uint256 i = 0; i < 20; i++) {
            str[2+i*2] = alphabet[uint256((value[i + 12] & 0xF0) >> 4)];
            str[3+i*2] = alphabet[uint256(value[i + 12] & 0x0F)];
        }
        return string(str);
    }

}

案例方法一:在合约部署前进行加载

如果需要设置部署合约调用者的话需要在部署合约时进行加载

    fromAddress := "0x1f2b33660b0fa7ca7f3aec0cb674edeeb9228126" // 输入指定的账户地址
    privateKey := "b5f1563c6f8a9792a065de6da30268ed7ce84e3e505a349de3a1b6846b8e6190" // 替换为正确的私钥
    // 解析私钥
    key, err := crypto.HexToECDSA(privateKey)
    if err != nil {
        fmt.Println("私钥解析错误:", err)
        return
    }
    // 创建新的TransactOpts对象,并设置From属性和签名者
    auth := bind.NewKeyedTransactor(key)
    auth.From = common.HexToAddress(fromAddress)
    //部署合约时传入auth即可
    _, _, instance, err := store.DeployKVTableTest(auth, client)
    session := store.KVTableTestSession{Contract: instance, CallOpts: *client.GetCallOpts(), TransactOpts: *client.GetTransactOpts()}

案例方法二:例如有个单独的功能需要不同的用户调用有不同的效果

只需要在实例化的时候进行传入即可,需要传入账户地址和私钥

func transKey() {

    fromAddress := "0x1f2b33660b0fa7ca7f3aec0cb674edeeb9228126"                      // 输入指定的账户地址
    privateKey := "9e139fba57613ee036c59321788cf52a09ea4271b6982a4a73e2228b522a77c8" // 替换为正确的私钥

    //解析私钥
    key, err := crypto.HexToECDSA(privateKey)
    if err != nil {
        fmt.Println("私钥解析错误:", err)
        return
    }

    //// 创建新的TransactOpts对象,并设置From属性和签名者
    auth := bind.NewKeyedTransactor(key)

    auth.From = common.HexToAddress(fromAddress)

    files, _ := conf.ParseConfigFile("config.toml")
    client, _ := client.Dial(&files[0])

    instance, _ := tranceUser.NewTranceUser(common.HexToAddress("0x57cdd9f703447d59d93f7dca163f4f86a6c3a2b0"), client)
    session := tranceUser.TranceUserSession{Contract: instance, CallOpts: *client.GetCallOpts(), TransactOpts: *auth}

    get, _ := session.Get()
    fmt.Println("修改前:" + get)
    address := common.HexToAddress("0x2a7a07be060902b931754dba742165e27fdfe5b0")
    session.Set(address)
    get, _ = session.Get()
    fmt.Println("修改后:" + get)

}
最后更新 2023-11-02
评论 ( 0 )
OωO
隐私评论