<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexander Xing on Medium]]></title>
        <description><![CDATA[Stories by Alexander Xing on Medium]]></description>
        <link>https://medium.com/@alexanderxing?source=rss-b06ebfbcc7ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N1QmTWFWxGtfxApjzHxr9Q.jpeg</url>
            <title>Stories by Alexander Xing on Medium</title>
            <link>https://medium.com/@alexanderxing?source=rss-b06ebfbcc7ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:10:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexanderxing/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Go | 监听ERC20转账消息]]></title>
            <link>https://medium.com/@alexanderxing/go-%E7%9B%91%E5%90%ACerc20%E8%BD%AC%E8%B4%A6%E6%B6%88%E6%81%AF-a19e579ad47c?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19e579ad47c</guid>
            <category><![CDATA[erc20]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 08:10:45 GMT</pubDate>
            <atom:updated>2023-12-13T08:10:45.170Z</atom:updated>
            <content:encoded><![CDATA[<p>上一节顺利读取了ERC20合约的余额，也就是知道了合约地址和账户地址，就可以查到某用户的某代币余额。这一节我们玩点更高级的，监控一下代币转账信息。</p><p>在开始之前，需要更改一下远程节点的链接URL。之前使用的远程节点是HTTPS协议，要订阅必须使用WSS版本，具体来说，就是URL从 `<a href="https://sepolia.infura.io/ws/v3/%60%E6%94%B9%E4%B8%BA%60wss://sepolia.infura.io/ws/v3/%60%E3%80%82">https://sepolia.infura.io/ws/v3/`改为`wss://sepolia.infura.io/ws/v3/`。</a></p><p>订阅有专门的函数来完成，传入chan即可。</p><pre>sink := make(chan *erc20.ERC20Transfer)<br>sub, err := link.WatchTransfer(nil, sink, nil, nil)</pre><p>解析好的结构ERC20Transfer里，包含了from、to、value，与标准中的参数一一对应。</p><pre>event Transfer(address indexed _from, address indexed _to, uint256 _value)</pre><h3>完整代码</h3><pre>package main<br><br>import (<br>  &quot;github.com/ethereum/go-ethereum/common&quot;<br>  &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br>  &quot;github.com/xingyongtao/ethereum-development-with-go/10_erc20/erc20&quot;<br>  &quot;log&quot;<br>  &quot;os&quot;<br>)<br><br>func main() {<br>  apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br>  url := &quot;wss://sepolia.infura.io/ws/v3/&quot; + apiKey<br>  ec, err := ethclient.Dial(url)<br>  if err != nil {<br>    log.Fatalf(&quot;could not connect to Infura with ethclient: %s&quot;, err)<br>  }<br><br>  address := common.HexToAddress(&quot;0x779877A7B0D9E8603169DdbD7836e478b4624789&quot;)<br>  link, err := erc20.NewERC20(address, ec)<br>  if err != nil {<br>    log.Fatalf(&quot;new erc20 error: %s&quot;, err)<br>  }<br>  sink := make(chan *erc20.ERC20Transfer)<br>  sub, err := link.WatchTransfer(nil, sink, nil, nil)<br>  if err != nil {<br>    log.Fatalf(&quot;subscribe transfer event error: %s&quot;, err)<br>  }<br>  for {<br>    select {<br>    case &lt;-sub.Err():<br>      return<br>    case event := &lt;-sink:<br>      log.Printf(&quot;%s send to %s: %s&quot;, event.From, event.To, event.Value)<br>    }<br>  }<br>}</pre><p>自动生成的Go代码里，做了很好的封装，可以直接使用，非常方便。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19e579ad47c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go | 和ERC20智能合约交互]]></title>
            <link>https://medium.com/@alexanderxing/go-%E5%92%8Cerc20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6%E4%BA%A4%E4%BA%92-9a30d26a0896?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a30d26a0896</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[erc20]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 08:32:47 GMT</pubDate>
            <atom:updated>2023-12-12T08:32:47.743Z</atom:updated>
            <content:encoded><![CDATA[<p>这一节终于来到了同质化代币ERC20，有些场合也会被叫做Token，即令牌。</p><p>关于ERC20代币标准的资料已经非常多，这里不展开了。这一节主要看一下Go语言如何和ERC20代币交互。 我们先从订阅转账消息开始。</p><p>Go和以太坊智能合约交互，是使用了以太坊的JSON-RPC接口，即把所有读取写入请求转换成RPC请求，发送给以太坊节点，并等待回应。这和之前转账是完全一致的，只不过交互的地址从EOA变成了合约而已。</p><p>但是，合约交互不比简单转账，它是有参数的，而且参数的编码也要严格遵守规范。如果不借助工具，这个编码过程是非常繁琐的。幸运的是，有工具。</p><p>go-ethereum自带的abigen可以根据ABI文件，自动生成对应的Go文件。有了这些文件，我们不用费功夫编解码了，可以直接使用所有函数，跟本地函数类似。</p><p>获得ABI文件的方法有很多，可以从etherscan网站拷贝，可以从源码编译等。我随便举例其中的一种。</p><p>我先从OpenZeppelin库<a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v5.0.1/contracts/token/ERC20/IERC20.sol">https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v5.0.1/contracts/token/ERC20/IERC20.sol</a>下载接口文件，然后放到Remix里编译，拷贝出ABI文件。</p><p>假设保存的ABI文件名是IERC20.json。运行命令</p><pre>abigen --abi IERC20.json --type ERC20 --pkg er<br>c20 --out erc20.go</pre><p>可以得到Go文件erc20.go，里边自动生成的类名是ERC20。</p><p>有了这个文件，我们可以找一个符合ERC20标准的测试网代币试一试了。我选中了sepolia网络的LINK代币，因为这个代币的水龙头容易找 <a href="https://faucets.chain.link/sepolia">https://faucets.chain.link/sepolia</a>。它的合约地址是0x779877A7B0D9E8603169DdbD7836e478b4624789。</p><p>使用之前的*ethclient.Client，新建一个ERC20对象</p><pre>address := common.HexToAddress(&quot;0x779877A7B0D9E8603169DdbD7836e478b4624789&quot;)<br>link, err := erc20.NewERC20(address, ec)</pre><p>查询某个账户持有的代币余额</p><pre>account := common.HexToAddress(&quot;0xAc25D7217FCCff38Ba52d3a7F453506522428713&quot;)<br>balance, err := link.BalanceOf(nil, account)</pre><h3>完整代码</h3><pre>package main<br><br>import (<br>  &quot;github.com/ethereum/go-ethereum/common&quot;<br>  &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br>  &quot;github.com/xingyongtao/ethereum-development-with-go/10_erc20/erc20&quot;<br>  &quot;log&quot;<br>  &quot;os&quot;<br>)<br><br>func main() {<br>  apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br>  url := &quot;https://sepolia.infura.io/v3/&quot; + apiKey<br>  ec, err := ethclient.Dial(url)<br>  if err != nil {<br>    log.Fatalf(&quot;could not connect to Infura with ethclient: %s&quot;, err)<br>  }<br><br>  address := common.HexToAddress(&quot;0x779877A7B0D9E8603169DdbD7836e478b4624789&quot;)<br>  link, err := erc20.NewERC20(address, ec)<br>  if err != nil {<br>    log.Fatalf(&quot;new erc20 error: %s&quot;, err)<br>  }<br>  account := common.HexToAddress(&quot;0xAc25D7217FCCff38Ba52d3a7F453506522428713&quot;)<br>  balance, err := link.BalanceOf(nil, account)<br>  if err != nil {<br>    log.Fatalf(&quot;get balance error: %s&quot;, err)<br>  }<br>  log.Printf(&quot;account %s has balance %s&quot;, account, balance)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a30d26a0896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go｜确认以太坊交易]]></title>
            <link>https://medium.com/@alexanderxing/go-%E7%A1%AE%E8%AE%A4%E4%BB%A5%E5%A4%AA%E5%9D%8A%E4%BA%A4%E6%98%93-2b1e513b3b81?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b1e513b3b81</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 09:25:01 GMT</pubDate>
            <atom:updated>2023-11-14T09:25:01.479Z</atom:updated>
            <content:encoded><![CDATA[<p>在上一节中，发送完交易，程序就直接退出了，至于交易是否确认，需要我们去区块浏览器里查看才知道。这显然不够好，我们应该等待交易确认，然后检查实际结果是成功还是失败。</p><p>以太坊网络每15秒才能出一个块，我们可以使用</p><pre>_, isPending, err := ec.TransactionByHash(ctx, txHash)</pre><p>来检查交易的状态。</p><p>如果isPending变成了false，那么交易要么是成功了，要么是失败了，都结束了Pending状态。</p><p>然后我们再次查询交易详细信息，检查一下具体的状态是成功还是失败即可</p><pre>receipt, err := ec.TransactionReceipt(ctx, txHash)</pre><p>返回的对象receipt包含Status，0表示失败，1表示成功。这与Etherscan浏览器上面的显示一致。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ED4K0tmrxm9lavpL35PneA.png" /><figcaption>Etherscan</figcaption></figure><p>不过，由于区块链网络的特殊性，有时候交易会很长时间得不到确认，所以我们最好设置一定的超时时间，比如最多等10分钟就不等了（当然，这是示例教程，实际项目中必须谨慎处理）。</p><p>至此，我们把所有功能集合到一起，封装起来作为一个功能函数，每秒钟检查一次，直到超时或者用户主动停止，看交易是否还在Pending。如果结束Pending了，就查询具体的Status看看到底成功失败。</p><pre>func waitConfirm(ctx context.Context, ec *ethclient.Client, txHash common.Hash, timeout time.Duration) error {<br>	pending := true<br>	for pending {<br>		select {<br>		case &lt;-ctx.Done():<br>			return ctx.Err()<br>		case &lt;-time.After(timeout):<br>			return errors.New(&quot;timeout&quot;)<br>		case &lt;-time.After(time.Second):<br>			_, isPending, err := ec.TransactionByHash(ctx, txHash)<br>			if err != nil {<br>				return err<br>			}<br>			if !isPending {<br>				pending = false // break `for`<br>			}<br>		}<br>	}<br>	receipt, err := ec.TransactionReceipt(ctx, txHash)<br>	if err != nil {<br>		return err<br>	}<br>	if receipt.Status == 0 {<br>		msg := fmt.Sprintf(&quot;transaction reverted, hash %s&quot;, receipt.TxHash.String())<br>		return errors.New(msg)<br>	}<br>	return nil<br>}</pre><p>除了等待的代码，其他代码和上一节一样，只是也顺便封装到一个函数里了。</p><h3>完整代码</h3><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;crypto/ecdsa&quot;<br> &quot;errors&quot;<br> &quot;fmt&quot;<br> &quot;github.com/ethereum/go-ethereum/common&quot;<br> &quot;github.com/ethereum/go-ethereum/core/types&quot;<br> &quot;github.com/ethereum/go-ethereum/crypto&quot;<br> &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br> &quot;log&quot;<br> &quot;math/big&quot;<br> &quot;os&quot;<br> &quot;time&quot;<br>)<br>func main() {<br> apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br> url := &quot;https://sepolia.infura.io/v3/&quot; + apiKey<br> ec, err := ethclient.Dial(url)<br> if err != nil {<br>  log.Fatalf(&quot;could not connect to Infura with ethclient: %s&quot;, err)<br> }<br> ctx := context.Background()<br> pk, err := crypto.HexToECDSA(os.Getenv(&quot;PRIVATE_KEY&quot;))<br> if err != nil {<br>  log.Fatalf(&quot;load private key error: %s&quot;, err)<br> }<br> to := common.HexToAddress(&quot;0x26a1DDA0E911Ea245Fc3Fb7C5C10d18490942a60&quot;)<br> amount := big.NewInt(100_000_000_000_000_000) // 0.1 ether<br> hash, err := sendEth(ctx, ec, pk, to, amount)<br> if err != nil {<br>  log.Fatalf(&quot;send Ether error: %s&quot;, err)<br> }<br> log.Printf(&quot;tx sent, hash: %s&quot;, hash)<br> if err = waitConfirm(ctx, ec, *hash, time.Minute*10); err != nil {<br>  log.Fatalf(&quot;wait confirmation error, please check the tx by yourself: %s&quot;, err)<br> }<br> log.Printf(&quot;tx %s confirmed&quot;, hash)<br>}<br>func sendEth(ctx context.Context, ec *ethclient.Client, pk *ecdsa.PrivateKey, to common.Address, amount *big.Int) (*common.Hash, error) {<br> chainId, err := ec.ChainID(ctx)<br> if err != nil {<br>  return nil, err<br> }<br> address := crypto.PubkeyToAddress(pk.PublicKey)<br> log.Printf(&quot;account: %s&quot;, address)<br> nonce, err := ec.NonceAt(ctx, address, nil)<br> if err != nil {<br>  return nil, err<br> }<br> log.Printf(&quot;nonce: %d&quot;, nonce)<br> header, err := ec.HeaderByNumber(ctx, nil)<br> if err != nil {<br>  return nil, err<br> }<br> log.Printf(&quot;base fee: %s&quot;, header.BaseFee)<br> gasTipCap, err := ec.SuggestGasTipCap(ctx)<br> if err != nil {<br>  return nil, err<br> }<br> log.Printf(&quot;Suggested GasTipCap(maxPriorityFeePerGas): %s&quot;, gasTipCap)<br> txData := &amp;types.DynamicFeeTx{<br>  ChainID: chainId,<br>  Nonce:   nonce,<br>  To:      &amp;to,<br>  Value:   amount,<br>  Gas:     21000,<br>  GasFeeCap: header.BaseFee,<br>  GasTipCap: gasTipCap,<br> }<br> signedTx, err := types.SignNewTx(pk, types.LatestSignerForChainID(chainId), txData)<br> if err != nil {<br>  return nil, err<br> }<br> err = ec.SendTransaction(ctx, signedTx)<br> if err != nil {<br>  return nil, err<br> }<br> hash := signedTx.Hash()<br> return &amp;hash, nil<br>}<br>func waitConfirm(ctx context.Context, ec *ethclient.Client, txHash common.Hash, timeout time.Duration) error {<br> pending := true<br> for pending {<br>  select {<br>  case &lt;-ctx.Done():<br>   return ctx.Err()<br>  case &lt;-time.After(timeout):<br>   return errors.New(&quot;timeout&quot;)<br>  case &lt;-time.After(time.Second):<br>   _, isPending, err := ec.TransactionByHash(ctx, txHash)<br>   if err != nil {<br>    return err<br>   }<br>   if !isPending {<br>    pending = false // break `for`<br>   }<br>  }<br> }<br> receipt, err := ec.TransactionReceipt(ctx, txHash)<br> if err != nil {<br>  return err<br> }<br> if receipt.Status == 0 {<br>  msg := fmt.Sprintf(&quot;transaction reverted, hash %s&quot;, receipt.TxHash.String())<br>  return errors.New(msg)<br> }<br> return nil<br>}</pre><p>祝朋友们玩得开心～</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b1e513b3b81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go｜发送ETH（提交交易）]]></title>
            <link>https://medium.com/@alexanderxing/go-%E5%8F%91%E9%80%81eth-%E6%8F%90%E4%BA%A4%E4%BA%A4%E6%98%93-893b76a80797?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/893b76a80797</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[eip-1559]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 09:09:52 GMT</pubDate>
            <atom:updated>2023-10-27T09:09:52.406Z</atom:updated>
            <content:encoded><![CDATA[<p>从这一节开始，因为涉及到提交交易，我们不再使用正式网，而是使用测试网Sepolia。</p><p>测试网开发也需要花费一些Gas，不过不用担心，可以免费领取。我推荐使用<a href="https://sepoliafaucet.com/">https://sepoliafaucet.com/</a>水龙头领取。</p><p>确保账户里有一定的测试币后，就可以开始了。（本示例中发送的是0.1 ether，你可以根据账户余额情况随意调整。）</p><p>每笔交易都需要设置Nonce，所以先获取账户的Nonce，</p><pre>nonce, err := client.NonceAt(ctx, address, nil)</pre><p>在从Header里读取现在整个网络的baseFee</p><pre>header, err := client.HeaderByNumber(ctx, nil)<br>// ...<br>log.Printf(&quot;base fee: %s&quot;, header.BaseFee)</pre><p>后面我们直接用baseFee来设置GasFeeCap。</p><p>这么做的可能后果是，如果接下来的几个区块baseFee都比较高，我们的交易将会长时间等待，甚至被丢弃。不过因为是测试网，一般不会太繁忙，这么做问题不大。如果是实际开发，需要根据实际情况精心处理GasFeeCap。</p><p>同样的，我们获取网络推荐的GasTipCap</p><pre>gasTipCap, err := client.SuggestGasTipCap(ctx)</pre><p>发送以太的交易，网络费用固定为21000，选择一个其他地址发送0.1 ether给他。</p><pre>to := common.HexToAddress(&quot;0x26a1DDA0E911Ea245Fc3Fb7C5C10d18490942a60&quot;)<br>amount := big.NewInt(100_000_000_000_000_000) // 0.1 ether<br>txData := &amp;types.DynamicFeeTx{<br>    ChainID: chainId,<br>    Nonce:   nonce,<br>    To:      &amp;to,<br>    Value:   amount,<br>    Gas:     21000,</pre><pre>    GasFeeCap: header.BaseFee,<br>    GasTipCap: gasTipCap,<br>}</pre><p>然后对交易进行签名，注意这里使用了前面从环境变量加载进来的私钥</p><pre>signedTx, err := types.SignNewTx(pk, types.LatestSignerForChainID(chainId), txData)</pre><p>签完名后的交易，就可以直接发送出去了。</p><pre>err = client.SendTransaction(ctx, signedTx)</pre><h3>完整代码</h3><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;github.com/ethereum/go-ethereum/common&quot;<br> &quot;github.com/ethereum/go-ethereum/core/types&quot;<br> &quot;github.com/ethereum/go-ethereum/crypto&quot;<br> &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br> &quot;log&quot;<br> &quot;math/big&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br> url := &quot;https://sepolia.infura.io/v3/&quot; + apiKey<br> client, err := ethclient.Dial(url)<br> if err != nil {<br>  log.Fatalf(&quot;could not connect to Infura with ethclient: %s&quot;, err)<br> }<br> ctx := context.Background()<br> chainId, err := client.ChainID(ctx)<br> if err != nil {<br>  log.Fatalf(&quot;get chainID error: %s&quot;, err)<br> }<br><br> pk, err := crypto.HexToECDSA(os.Getenv(&quot;PRIVATE_KEY&quot;))<br> if err != nil {<br>  log.Fatalf(&quot;load private key error: %s&quot;, err)<br> }<br> address := crypto.PubkeyToAddress(pk.PublicKey)<br> log.Printf(&quot;account load success, address: %s&quot;, crypto.PubkeyToAddress(pk.PublicKey))<br><br> nonce, err := client.NonceAt(ctx, address, nil)<br> if err != nil {<br>  log.Fatalf(&quot;get nonce error: %v&quot;, err)<br> }<br> log.Printf(&quot;nonce: %d&quot;, nonce)<br> header, err := client.HeaderByNumber(ctx, nil)<br> if err != nil {<br>  log.Fatalf(&quot;get header error: %v&quot;, err)<br> }<br> log.Printf(&quot;base fee: %s&quot;, header.BaseFee)<br> gasTipCap, err := client.SuggestGasTipCap(ctx)<br> if err != nil {<br>  log.Fatalf(&quot;get SuggestGasTipCap error: %v&quot;, err)<br> }<br> log.Printf(&quot;Suggested GasTipCap(maxPriorityFeePerGas): %s&quot;, gasTipCap)<br><br> to := common.HexToAddress(&quot;0x26a1DDA0E911Ea245Fc3Fb7C5C10d18490942a60&quot;)<br> amount := big.NewInt(100_000_000_000_000_000) // 0.1 ether<br> txData := &amp;types.DynamicFeeTx{<br>  ChainID: chainId,<br>  Nonce:   nonce,<br>  To:      &amp;to,<br>  Value:   amount,<br>  Gas:     21000,<br><br>  GasFeeCap: header.BaseFee,<br>  GasTipCap: gasTipCap,<br> }<br> signedTx, err := types.SignNewTx(pk, types.LatestSignerForChainID(chainId), txData)<br> if err != nil {<br>  log.Fatalf(&quot;sign tx error: %v&quot;, err)<br> }<br> err = client.SendTransaction(ctx, signedTx)<br> if err != nil {<br>  log.Fatalf(&quot;sign tx error: %v&quot;, err)<br> }<br>}</pre><p>欢迎大家鼓掌点赞、留言评论、收藏和分享，也欢迎一起交流。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=893b76a80797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go | 导入Keystore文件]]></title>
            <link>https://medium.com/@alexanderxing/go-%E5%AF%BC%E5%85%A5keystore%E6%96%87%E4%BB%B6-56e067924ce5?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/56e067924ce5</guid>
            <category><![CDATA[keystore]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 01:27:25 GMT</pubDate>
            <atom:updated>2023-10-26T01:27:25.579Z</atom:updated>
            <content:encoded><![CDATA[<p>导入Keystore文件的教程网络上较少，但它其实更安全，而且Go处理起来也非常方便。</p><p>具体的步骤和导入私钥差不多，只是多了个密码而已。为了模拟更真实的使用场景，我们这次直接从文件中读入。</p><p>假设Keystore文件用环境变量KEYSTORE_FILE指定，先打开文件。</p><pre>f, err := os.Open(os.Getenv(&quot;KEYSTORE_FILE&quot;))<br>if err != nil {<br>    log.Fatalf(&quot;open keystore file error: %s&quot;, err)<br>}<br>defer f.Close()</pre><p>然后使用密码解锁文件，并生成可签名发送交易的transactor对象，这次使用的是NewTransactorWithChainID函数</p><pre>auth, err := bind.NewTransactorWithChainID(f, os.Getenv(&quot;PASSWORD&quot;), chainId)<br>if err != nil {<br>    log.Fatalf(&quot;failed to create authorized transactor: %v&quot;, err)<br>}</pre><h3>完整代码</h3><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;github.com/ethereum/go-ethereum/accounts/abi/bind&quot;<br> &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br> url := &quot;https://mainnet.infura.io/v3/&quot; + apiKey<br> client, err := ethclient.Dial(url)<br> if err != nil {<br>  log.Fatalf(&quot;could not connect to Infura with ethclient: %s&quot;, err)<br> }<br> ctx := context.Background()<br> chainId, err := client.ChainID(ctx)<br> if err != nil {<br>  log.Fatalf(&quot;get chainID error: %s&quot;, err)<br> }<br><br> f, err := os.Open(os.Getenv(&quot;KEYSTORE_FILE&quot;))<br> if err != nil {<br>  log.Fatalf(&quot;open keystore file error: %s&quot;, err)<br> }<br> defer f.Close()<br><br> auth, err := bind.NewTransactorWithChainID(f, os.Getenv(&quot;PASSWORD&quot;), chainId)<br> if err != nil {<br>  log.Fatalf(&quot;failed to create authorized transactor: %v&quot;, err)<br> }<br> log.Printf(&quot;account load success, address: %s&quot;, auth.From)<br><br> _ = auth<br>}</pre><p>Keystore文件因为不明文存储私钥，所以更安全。没有密码光有文件解锁不了，而光有密码没有文件也不可能拿到私钥，所以给了我们<strong>分开存储</strong>的便利性。</p><p>如果有一天你怀疑密码或者Keystore文件可能被盗或者泄露了，还可以通过老密码和老文件，导入后重新生成新的Keystore文件和新密码，然后把老文件老密码彻底废弃不用。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56e067924ce5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go｜导入钱包私钥]]></title>
            <link>https://medium.com/@alexanderxing/go-%E5%AF%BC%E5%85%A5%E9%92%B1%E5%8C%85%E7%A7%81%E9%92%A5-092dc8062385?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/092dc8062385</guid>
            <category><![CDATA[private-key]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 01:23:30 GMT</pubDate>
            <atom:updated>2023-10-26T01:23:30.404Z</atom:updated>
            <content:encoded><![CDATA[<p>现在钱包管理的教程一般都是环境变量设置助记词或者私钥，程序导入使用。我这里也用这种方法来演示。</p><p><strong>注意：生产环境中，请根据实际情况，选择更稳妥的处理方式。这里的教程仅作技术演示，不是最佳方案。</strong></p><p>使用go-ethereum crypto包的HexToECDSA函数可以直接把16进制格式的私钥导入。</p><pre>pk, err := crypto.HexToECDSA(os.Getenv(&quot;PRIVATE_KEY&quot;))</pre><p>需要注意，Go语言导入私钥与其他语言略有不同，不需要私钥之前的0x前缀。</p><p>比如anvil测试账户0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266的私钥是0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80，环境变量设置时只需要去掉0x的部分，即&#39;ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80即可。</p><p><strong>注意：该私钥是测试工具</strong>anvil<strong>自动生成的，全网公开，任何人都能知道，账户里没有任何资产，也千万不要在任何正式网上尝试操作该账户。</strong></p><p>私钥读取成功后，可以使用NewKeyedTransactorWithChainID获得一个可写入的transactor，用于向区块链网络发起交易。</p><pre>auth, err := bind.NewKeyedTransactorWithChainID(pk, chainId)</pre><h3>完整代码</h3><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;github.com/ethereum/go-ethereum/accounts/abi/bind&quot;<br> &quot;github.com/ethereum/go-ethereum/crypto&quot;<br> &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br> url := &quot;https://mainnet.infura.io/v3/&quot; + apiKey<br> client, err := ethclient.Dial(url)<br> if err != nil {<br>  log.Fatalf(&quot;could not connect to Infura with ethclient: %s&quot;, err)<br> }<br> ctx := context.Background()<br> chainId, err := client.ChainID(ctx)<br> if err != nil {<br>  log.Fatalf(&quot;get chainID error: %s&quot;, err)<br> }<br><br> pk, err := crypto.HexToECDSA(os.Getenv(&quot;PRIVATE_KEY&quot;))<br> if err != nil {<br>  log.Fatalf(&quot;load private key error: %s&quot;, err)<br> }<br> log.Printf(&quot;account load success, address: %s&quot;, crypto.PubkeyToAddress(pk.PublicKey))<br><br> auth, err := bind.NewKeyedTransactorWithChainID(pk, chainId)<br> if err != nil {<br>  log.Fatalf(&quot;failed to create authorized transactor: %v&quot;, err)<br> }<br><br> _ = auth<br>}</pre><p>以上就是导入私钥的方法，如果觉得有用，欢迎给我鼓个掌，谢谢🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=092dc8062385" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go | 查询以太坊交易]]></title>
            <link>https://medium.com/@alexanderxing/go-%E6%9F%A5%E8%AF%A2%E4%BB%A5%E5%A4%AA%E5%9D%8A%E4%BA%A4%E6%98%93-7938e34c645d?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/7938e34c645d</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 08:47:00 GMT</pubDate>
            <atom:updated>2023-10-24T08:47:00.016Z</atom:updated>
            <content:encoded><![CDATA[<p>比查询区块信息更常见的，是查询个别交易，这时候需要TransactionByHash。</p><p>查询时只需要知道Hash即可。</p><pre>tx, _, err := client.TransactionByHash(ctx, hash)</pre><p>交易查询有时候用在确认自己的交易是否确认，有时候用在跟踪链上发生的事情，通过解析别人的交易知道发生了某些事。</p><h3>完整代码</h3><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;github.com/ethereum/go-ethereum/common&quot;<br> &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br> url := &quot;https://mainnet.infura.io/v3/&quot; + apiKey<br> client, err := ethclient.Dial(url)<br> if err != nil {<br>  log.Fatalf(&quot;Could not connect to Infura with ethclient: %s&quot;, err)<br> }<br> ctx := context.Background()<br><br> tx, _, err := client.TransactionByHash(ctx, common.HexToHash(&quot;0x468f17f20488fa6011aae26fb59f9e14256ccf4a3835b28d5309b8d11b30656a&quot;))<br> if err != nil {<br>  log.Fatalf(&quot;get tx error: %s&quot;, err)<br> }<br> log.Printf(&quot;tx hash: %s&quot;, tx.Hash())<br> log.Printf(&quot;chainID: %s&quot;, tx.ChainId())<br> log.Printf(&quot;type: %d&quot;, tx.Type())<br> log.Printf(&quot;gas limit: %d&quot;, tx.Gas())<br> log.Printf(&quot;gas price: %d&quot;, tx.GasPrice())<br> log.Printf(&quot;gas fee cap: %s&quot;, tx.GasFeeCap())<br> log.Printf(&quot;gas tip cap: %s&quot;, tx.GasTipCap())<br>}</pre><p>如果你觉得文章有用，欢迎点赞关注，一起交流。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7938e34c645d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go｜查询以太坊区块]]></title>
            <link>https://medium.com/@alexanderxing/go-%E6%9F%A5%E8%AF%A2%E4%BB%A5%E5%A4%AA%E5%9D%8A%E5%8C%BA%E5%9D%97-9c48219761d3?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c48219761d3</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 07:26:57 GMT</pubDate>
            <atom:updated>2023-10-20T07:32:15.346Z</atom:updated>
            <content:encoded><![CDATA[<p>对区块链数据的查询，除了之前提到的ChainID和当前的BlockNumber之外，对区块头（Header）的查询也比较常见，甚至有时候需要查询整个区块（Block）。</p><p>查询区块头和完整区块信息都有两种方法，按Number或者按Hash。</p><pre>bn := big.NewInt(18382246)<br>header, err := client.HeaderByNumber(ctx, bn)<br>if err != nil {<br>    log.Fatalf(&quot;get header error: %s&quot;, err)<br>}<br>log.Printf(&quot;block %s, hash: %s, gas used: %d, base fee: %s&quot;, bn.String(), header.Hash(), header.GasUsed, header.BaseFee.String())</pre><p>一般情况下，重要的信息在Header里都已经有了，比如BaseFee等，不太需要检索整个区块。如果请求整个区块的话，数据量比较大，尽量要少用。</p><pre>block, err := client.BlockByHash(ctx, header.Hash())<br>if err != nil {<br>    log.Fatalf(&quot;get block error: %s&quot;, err)<br>}<br>log.Printf(&quot;block %s, time: %d, txs: %d&quot;, block.Hash(), block.Time(), len(block.Transactions()))</pre><h3>完整代码</h3><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br>    &quot;log&quot;<br>    &quot;math/big&quot;<br>    &quot;os&quot;<br>)<br><br>func main() {<br>    apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br>    url := &quot;https://mainnet.infura.io/v3/&quot; + apiKey<br>    client, err := ethclient.Dial(url)<br>    if err != nil {<br>       log.Fatalf(&quot;Could not connect to Infura with ethclient: %s&quot;, err)<br>    }<br>    ctx := context.Background()<br><br>    bn := big.NewInt(18382246)<br>    header, err := client.HeaderByNumber(ctx, bn)<br>    if err != nil {<br>       log.Fatalf(&quot;get header error: %s&quot;, err)<br>    }<br>    log.Printf(&quot;block %s, hash: %s, gas used: %d, base fee: %s&quot;, bn.String(), header.Hash(), header.GasUsed, header.BaseFee.String())<br><br>    block, err := client.BlockByHash(ctx, header.Hash())<br>    if err != nil {<br>       log.Fatalf(&quot;get block error: %s&quot;, err)<br>    }<br>    log.Printf(&quot;block %s, time: %d, txs: %d&quot;, block.Hash(), block.Time(), len(block.Transactions()))<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c48219761d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go获取以太坊账户余额]]></title>
            <link>https://medium.com/@alexanderxing/go%E8%8E%B7%E5%8F%96%E4%BB%A5%E5%A4%AA%E5%9D%8A%E8%B4%A6%E6%88%B7%E4%BD%99%E9%A2%9D-bf4fe9f2f4ac?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf4fe9f2f4ac</guid>
            <category><![CDATA[decimal]]></category>
            <category><![CDATA[big]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 06:02:13 GMT</pubDate>
            <atom:updated>2023-10-19T06:14:37.546Z</atom:updated>
            <content:encoded><![CDATA[<p>上一节已经获取到了以太坊公链的信息，这一节尝试获取某个账户的余额信息。（这里的余额指的是ETH余额，不是ERC-20代币余额。）</p><p>查询账户信息不需要私钥，只需要地址即可。地址的类型是common.Address，可以是普通的账户（EOA），也可以是智能合约地址（代币、金库、AA钱包、各种Pool等）。</p><p>接口除了接收地址参数以外，还有一个可选参数blockNumber，如果想查询指定区块上的余额，则传入区块号，查询最新余额的话，传入nil。</p><pre>ctx := context.Background()<br>addr := common.HexToAddress(&quot;0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045&quot;) // vitalik.eth<br>bn := big.NewInt(18382246)<br>balance, err := client.BalanceAt(ctx, addr, bn) // 935143001746486974073</pre><p>返回值balance的单位是Wei，要转换成Ether需要除以1e18，详见<a href="https://etherscan.io/unitconverter">https://etherscan.io/unitconverter</a>。</p><p>需要特别注意的是，账户余额可能是非常大的整数（uint256），<strong>极易出现精度损失</strong>，所以<strong>非必要不转换，在本地最好存储成</strong>Wei，以便和链上保持一致。</p><p>如果使用标准库的big.Float转换，可以这么做</p><pre>bf := big.NewFloat(0).SetInt(balance)<br>bf.Quo(bf, big.NewFloat(1e18)) // 935.1430017</pre><p>如果使用另一个常用库decimal转换，可以这么做</p><pre>bd := decimal.RequireFromString(balance.String())<br>bd = bd.Div(decimal.NewFromFloat(1e18)) // 935.1430017464869741</pre><p>上述示例中，V神在区块18382246的余额是935143001746486974073 Wei，即935.143001746486974073 Ether，而使用Float转换得到的是935.1430017 Ether，使用Decimal转换后得到的是935.1430017464869741 Ether，都不准确。</p><h3>完整代码</h3><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;github.com/ethereum/go-ethereum/common&quot;<br>    &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br>    &quot;github.com/shopspring/decimal&quot;<br>    &quot;log&quot;<br>    &quot;math/big&quot;<br>    &quot;os&quot;<br>)<br><br>func main() {<br>    apiKey := os.Getenv(&quot;INFURA_API_KEY&quot;)<br>    url := &quot;https://mainnet.infura.io/v3/&quot; + apiKey<br>    client, err := ethclient.Dial(url)<br>    if err != nil {<br>        log.Fatalf(&quot;Could not connect to Infura with ethclient: %s&quot;, err)<br>    }<br><br>    ctx := context.Background()<br>    addr := common.HexToAddress(&quot;0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045&quot;) // vitalik.eth<br>    bn := big.NewInt(18382246)<br>    balance, err := client.BalanceAt(ctx, addr, bn) // 935143001746486974073<br>    if err != nil {<br>        log.Fatalf(&quot;get chainId error: %s&quot;, err)<br>    }<br>    log.Printf(&quot;balance in Wei: %s&quot;, balance)<br>    bf := big.NewFloat(0).SetInt(balance)<br>    bf.Quo(bf, big.NewFloat(1e18)) // 935.1430017<br>    log.Printf(&quot;balance in Ether (converted by big.Float): %s&quot;, bf.String())<br><br>    bd := decimal.RequireFromString(balance.String())<br>    bd = bd.Div(decimal.NewFromFloat(1e18)) // 935.1430017464869741<br>    log.Printf(&quot;balance in Ether (converted decimal.Decimal): %s&quot;, bd.String())<br>}</pre><p>如果有任何疑问，欢迎留言交流。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf4fe9f2f4ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go读取以太坊ChainID和BlockNumber]]></title>
            <link>https://medium.com/@alexanderxing/go%E8%AF%BB%E5%8F%96%E4%BB%A5%E5%A4%AA%E5%9D%8Achainid%E5%92%8Cblocknumber-0bd0f36c633a?source=rss-b06ebfbcc7ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd0f36c633a</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Alexander Xing]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 04:41:04 GMT</pubDate>
            <atom:updated>2023-10-19T04:42:20.249Z</atom:updated>
            <content:encoded><![CDATA[<p>以太坊节点提供JSON-RPC服务，如果开启了，就可以通过HTTP/HTTPS协议访问节点。</p><p>该服务是可选的，有一些自用节点不一定会开启。远程节点是专门提供该服务的，自然是开着的。本地调试节点（Hardhat、anvil等）默认都是开启的。</p><p>从本节开始后的章节，基本都使用远程节点，不再特殊说明。</p><p>在<a href="https://medium.com/@alexanderxing/go%E8%BF%9E%E6%8E%A5%E4%BB%A5%E5%A4%AA%E5%9D%8A-21879059a9c1">连接到以太坊</a>之后，我们就可以开始发起请求了。 常见请求有：</p><ol><li>获取ChainID用于核实网络是否匹配</li><li>获取网络信息，如BlockNumber、账户余额等</li><li>与智能合约交互</li><li>监听网络事件</li></ol><p>我们先从获取ChainID和BlockNumber开始讲起。</p><p>在EVM兼容网络之间，ChainID是区分网络的重要手段，每一个网络都有唯一的ID与其对应。 比如，以太坊的ID是1，Polygon的ID是137，而BSC的ID是56。想知道一个网络的具体ID，可以参考<a href="https://chainlist.org/">https://chainlist.org/</a>。</p><p>获取ChainID比较简单，传入ctx即可，返回值是*big.Int类型。</p><pre>chainId, err := client.ChainID(ctx)</pre><p>获取BlockNumber也类似，都不复杂，返回值是uint64。</p><pre>bn, err := client.BlockNumber(ctx)</pre><p>完整的代码见上一节<a href="https://medium.com/@alexanderxing/go%E8%BF%9E%E6%8E%A5%E4%BB%A5%E5%A4%AA%E5%9D%8A-21879059a9c1">连接以太坊</a>。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd0f36c633a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>