<?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 Tanopwan on Medium]]></title>
        <description><![CDATA[Stories by Tanopwan on Medium]]></description>
        <link>https://medium.com/@tanopwan?source=rss-38aa4c4b25c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o5w6pB0rld51r-DlltVNnQ.jpeg</url>
            <title>Stories by Tanopwan on Medium</title>
            <link>https://medium.com/@tanopwan?source=rss-38aa4c4b25c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:07:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanopwan/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[สายซิ่งต้องรู้ ทำไมเราต้อง unapprove contract]]></title>
            <link>https://tanopwan.medium.com/%E0%B8%AA%E0%B8%B2%E0%B8%A2%E0%B8%8B%E0%B8%B4%E0%B9%88%E0%B8%87%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B9%E0%B9%89-%E0%B8%97%E0%B8%B3%E0%B9%84%E0%B8%A1%E0%B9%80%E0%B8%A3%E0%B8%B2%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87-unapprove-contract-94c45159e383?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/94c45159e383</guid>
            <category><![CDATA[approval]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[bep20]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Mon, 10 May 2021 10:55:31 GMT</pubDate>
            <atom:updated>2021-05-10T12:06:46.654Z</atom:updated>
            <content:encoded><![CDATA[<p>สำหรับชาวนา Defi ที่อยู่บน BSC ที่อยู่ในวงการมานานกว่า 1 เดือน น่าจะผ่าน event หลักๆ ของ BSC อย่างเช่น MKAT Rug pull (ถ้าเขาจะ rug อยู่เฉยๆเขาก็​ rug), Uranium โดนแฮก 2 รอบ หรือ สดๆร้อน ValueDefi ก็ขอ 2 อีกเช่นกัน ถ้าท่านอยู่ใน pool เหล่านี้ นอกจากเงินหมดแล้ว ก็มีคนเตือนบอกอีกว่า ไป unapprove ยัง ❗️ Rovoke สิทธิ์รึยัง ❗️ ว่าแต่ มันคืออะไร เงินจะหายหมดกระเป๋ามั้ยถ้าไม่ revoke</p><blockquote>ปล จริงๆ ไม่ต้องโดนแฮกก็ unapprove ได้นะ เพื่อความสบายใจ</blockquote><p>ขอเกริ่นถึงวิธีการทำ transaction ใน BSC หรือ Ethereum protocol ก่อน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*G0f0YsYL8lCMPy3BlOxUXg.png" /></figure><p>ใน 1 transaction บน blockchain จะมี field หลัก คือ value ซึ่งในการโอนเงินปกติเราสามารถใส่ BNB ในช่อง value ได้เลยจากตัวอย่างข้างต้น แต่ด้วยความที่ BSC เนี่ย สามารถรัน code ได้ (Bitcoin ทำไม่ได้นะจ๊ะ) ทำให้เกิดมาตราฐานใหม่ เรียกว่า BEP20 Token ซึ่งเป็น <strong>Smart Contract </strong>และมี feature สำคัญๆ ในการโอนเงินเช่น transfer, balanceOf เหมือนเหรียญ BNB เลย แต่เป็นความเหมือนในความแตกต่าง</p><h4>ภาพแสดงการ transfer เหรียญ Token ที่ไม่เหมือน BNB Coin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*em3XFh9fRn49zyVBs6sELA.png" /></figure><p>จากรูปด้านบนเวลาทำ transaction เราไม่ได้ส่ง cake เข้าไปใน value แต่ส่ง data เข้าไปเพื่อเรียก function transfer บอกว่าจะส่งกี่ cake แต่ๆ ❗️สังเกตว่า เราไม่ได้ส่ง transaction ไปหาผู้รับโดยตรง เราส่ง transaction ไปที่ smart contract แทน โดยเรียก function ที่ชื่อว่า transfer พร้อมกับ argument ส่งให้ใคร จำนวนเท่าไร ซึ่งสิ่งที่ function transfer ทำก็คือ update balance ของผู้ส่งและผู้รับ เป็นอันจบการทำงาน</p><pre>function _transfer (address sender, address recipient, uint256 amount) internal {<br>    require(sender != address(0), &#39;BEP20: transfer from the zero address&#39;);<br>    require(recipient != address(0), &#39;BEP20: transfer to the zero address&#39;);</pre><pre>    _balances[sender] = _balances[sender].sub(amount, &#39;BEP20: transfer amount exceeds balance&#39;);<br>    _balances[recipient] = _balances[recipient].add(amount);<br>    emit Transfer(sender, recipient, amount);<br>}</pre><p>ถ้าผู้รับอยากรู้ว่า Token นี้มาถึงแล้วหรือยัง ก็ต้องเรียกคำสั่ง balanceOf มาที่ Smart Contract แปลว่าทุกอย่างจะทำผ่าน Smart Contract หมดเลย</p><p>ตัวอย่าง การโอน USDT (BEP-20) 1 Token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7J5J9Pw5mO-8_tjTzA2xw.jpeg" /></figure><p>To จะเป็น contract ของ USDT Value คือ 0 BNB ส่วน Input Data คือการเรียก function transfer</p><p>ทีนี้เราก็เข้าใจมากขึ้นแล้ว ว่าเราไม่สามารถส่ง Token ให้ใครก็ได้เหมือน Coin ที่เป็น protocol หลักของ chain นั้นๆ</p><p>เพราะฉะนั้น flow ที่มีความซับซ้อนมากขึ้นอย่างเช่น การ addLiquidity, deposit ที่ต้องส่ง Token สองรอบ เพื่อ mint เหรียญ LP ทั้งหมดให้อยู่ใน transaction เดียว จำเป็นต้องรวมไปเขียนใน Smart Contract</p><p>ตัวอย่าง การฝากคู่ LP ของเราไปใน MasterChef เพื่อทำการฟาร์มนั้น คือการที่เรา deposit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*KTdTV0a0AZiIzMP_lS3kog.png" /></figure><p>ซึ่ง function นี้ใน MasterChef จะดึงเหรียญของเราออกมาจาก balance ใน BEP-20 contract แต่จริงๆแล้ว ไม่ใช่ว่า ใครก็มีสิทธิ์ดึงเหรียญของเราออกไปได้ ไม่งั้นก็เจ๊งกันหมดสิ 😅 เพราะฉะนั้น อย่างในกรณีนี้ถ้าเราอยากจะฟาร์ม เราก็ต้องอนุญาติให้ MasterChef contract สามารถดึงเหรียญเราออกไปได้ นั่นก็คือการ approve contract นั่นเอง ❣️ อธิบายยืดยาวกว่าจะเฉลย 😄</p><p>ซึ่งเราสามารถบอก <strong>Pancake LP Contract</strong> ข้างบนไว้ได้ว่า ถ้าใครก็ตาม (spender) ที่มี address ดังต่อไปนี้ จะสามารถดึงเหรียญของเราไปได้เท่าไร (amount)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*F7jmQAW9O0k2d0---p-Nsg.png" /></figure><p>สำหรับใน UI ที่เราคุ้นเคย คือปุ่มแบบนี้นี่เอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*AqJa8LcliovGFetVPSmjxA.png" /><figcaption><a href="https://apeswap.finance/farms">https://apeswap.finance/farms</a></figcaption></figure><p>ซึ่งถ้าเราไม่แน่ใจว่าเคยให้สิทธิ์ไปเท่าไร เราก็สามารถเช็คได้ที่ allowance เช่นกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*mPuUqniIjHeU5TQYaAtfCQ.png" /></figure><p>ซึ่งเราต้องทำแบบนี้ทุก contract ที่เป็น BEP-20 เลยหรอ ❓</p><blockquote>ถูกต้องนะค้าบ 🎉</blockquote><p>สรุปแล้ว มันอันตรายไหม ❓ ก็ถ้าเรารู้ว่า MasterChef จะเอาเหรียญเราไปทำอะไรบ้าง อ่านจาก code มันก็จะทำนอกเหนือจากนั้นไม่ได้ แต่มันก็มีโอกาสที่จะมีช่องโหว่ให้คนใช้สิทธิ์ MasterChef โอนออกไปได้ เพราะฉะนั้นเวลามีการ Hack หรือ Rug pull เกิดขึ้น เราก็จะเลิกเชื่อใจ Smart Contract นั้นและ Revoke สิทธิ์นั่นเอง ~~</p><blockquote>ปล การ Revoke สิทธิ์ ก็คือการ approve ใหม่ด้วย 0 amount</blockquote><p>เกริ่นมานานแล้วว่าทำไม มาดูวิธีทำเลยดีกว่า</p><p>ขอโฆษณาให้ JdiYield ละกัน (ไม่ได้ค่าโฆษณา แต่ถือเหรียญเค้าอยู่ 😙) <a href="https://www.jdiyield.com/allowances">https://www.jdiyield.com/allowances</a> เข้าไปเว็บนี้ ก็จะรู้ว่าเราเคย approve ให้ใครดึงเหรียญอะไรของเราไปได้บ้าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NuIQ1gJjSwCb6y_xvC0xg.jpeg" /></figure><p>ทีนี้เราอยากรู้ว่าเราเคยไปให้สิทธิ์ใครดึง Cake-LP 🍰 ออกจากกระเป๋าเราไปนะ ก็เอาไปใส่ URL แบบนี้ <a href="https://bscscan.com/address/0x73feaa1ee314f8c655e354234017be2193c9e24e#code">https://bscscan.com/address/0x73feaa1ee314f8c655e354234017be2193c9e24e#code</a> แล้วก็ไปดูที่ชื่อของ Smart Contract</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*6GwIZy0B4NYjjwQJC-J06g.png" /></figure><p>เราก็พบว่ามันคือ MasterChef ของ Pancake นั่นเอง อย่างกรณีนี้ เรา ณ ตอนนี้ เชื่อใจ PancakeSwap ก็อาจจะเลือกที่จะไม่ revoke ก็ได้ เราสามารถดู​ code ที่หน้านี้ได้เลย ว่ามันมี code ดึง LP เราออกไปเองรึเปล่านั่นเอง</p><blockquote>TIP: อย่างเคส Uranium เราก็ทำการ Revoke Token BUSD, LP ออกเท่านั้นนะ U92 ก็ไม่ได้ Revoke นะเปลืองแก้ส เพราะ revoke ทีก็ 10 บาท อารมณ์อยากได้ก็เอาไป ไม่ค่ามีค่าแล้ว เพราะไม่มี pool ให้ trade 😢</blockquote><blockquote>Happy Farming ค่าทุกคนนนน 👩‍🌾</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94c45159e383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KillSwitch v0.0.1 Incident Report]]></title>
            <link>https://medium.com/killswitchofficial/killswitch-v0-0-1-incident-report-be672a4896a6?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/be672a4896a6</guid>
            <category><![CDATA[incident-reporting]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[killswitch-finance]]></category>
            <category><![CDATA[scb-10x]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 04:55:12 GMT</pubDate>
            <atom:updated>2021-04-03T04:58:32.107Z</atom:updated>
            <content:encoded><![CDATA[<h4>เจาะโค้ด และ วิธีแก้ไข แบบละเอียด</h4><p>หลังจากที่ KillSwitch ได้เปิดให้ Community Test กันไป ในช่วง 2–3 วันแรกก็พบปัญหาดังนี้</p><h3>Issue #1 Web UI Error เมื่อฝาก 0 LP</h3><p>เนื่องจากไม่ได้ดักว่าไม่ให้ทำการ Stake ถ้ามี LP ≤ 0 ในฝั่ง UI และฝั่ง Smart Contract เนื่องจากเป็น early version สุด ทำให้อาจจะมีแต่ MVP จริงๆ ซึ่งไม่ได้มีผลอะไรกับเงินของทุกคน แต่อาจจะเสียค่า gas ที่ฝาก 0 LP ไปฟรีๆ</p><blockquote>Version UI ยังไม่ได้ปั้น ทีมงานต้องขอบคุณ fc ขาซิ่ง ทุกคนจริงๆ ที่มาช่วยกันทดสอบใน version นี้ <a href="https://emojipedia.org/folded-hands/">🙏🙏🙏</a></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeD_9a9309wY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeD_9a9309wY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeD_9a9309wY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cae9c8c76a111bce98ad3a2bb83f0d2c/href">https://medium.com/media/cae9c8c76a111bce98ad3a2bb83f0d2c/href</a></iframe><p>ซึ่งทีมงานจะแก้ใน version 0.0.2 นะคะ 💁</p><h3>Issue #2 เมื่อทำการ Stake LP มากกว่า 1 ครั้ง ทำให้ balance LP ในรอบแรกหายไปอยู่ในหลุม 😵</h3><p>เนื่องจาก KillSwitch Smart Contract ของเราทำหน้าที่เสมือนเป็นตัวแทนในการฝาก LP Token เข้าไปใน 🍰 Smart Contract แปลว่า KillSwitch Smart Contract จะต้องมี map เอาไว้สำหรับเก็บว่าแต่ละคนนั้นฝากมาแล้วเท่าไร</p><pre>stakeBalance[msg.sender] = _amountLP;</pre><p>ซึ่ง Bug ของบรรทัดนี้คือการที่เราจะ เซ็ตค่า _amountLP ใหม่ทับไปเสมอ ทำให้ balance ของเก่าถูก rewrite ไปนั่นเอง ส่วนวิธีแก้คือ การใช้ += แทน เพื่อให้จำนวน LP accummulate เพิ่มทุกครั้งที่ฝากเพิ่มนั่นเอง</p><pre>stakeBalance[msg.sender] += _amountLP;</pre><p>❗️❗️❗️สำหรับคนที่ฝากมาเกิน 1 รอบ จะเกิดอะไรขึ้น จริงๆแล้ว LP Token ที่ KillSwitch ได้นำฝากไปให้ ก็ไม่ได้หายไปไหน ยังคง Lock อยู่ใน Smart Contract และเนื่องด้วยยังอยู่ในขั้นตอน development จึงยังเปิดให้ Dev wallet account (owner) ที่ deploy Smart Contract สามารถถอน LP Token ออกมาแบบ manual ได้ แต่จำเป็นต้องคำนวนจาก transaction logs แทน เพื่อคืน LP ให้กับผู้เข้าร่วมทดสอบแต่ละคน</p><p>เนื่องจากมีผู้เข้าทดสอบ KillSwitch Alpha 0.0.1 จำนวนมาก ทางทีมงานจึงต้องเขียน script ในการดึง transaction history จาก Smart Contract เพื่อหาย้อนหลังว่าใครฝากมาเท่าไรบ้าง</p><h4>วิธีการดู transfer events</h4><p>Binance Smart Chain ได้มีการ provide API ในการดึง transaction events ของ Token ออกมาได้ ตามหลักก็ให้ใส่ startblock <br>เริ่มที่ Smart Contract เราถูก deploy (ใส่ startblock=1 ก็คงไม่บาปมากหรอกมั้ง 😆)</p><p>โดย tokentx (token transaction คือ action ที่เราสนใจ</p><p>ปล. เราสามารถสมัครและขอ API Key ได้ที่เว็บ <a href="https://bscscan.com/apis">https://bscscan.com/apis</a></p><pre><a href="https://api.bscscan.com/api?module=account&amp;action=tokentx&amp;address=0x0576961aAc8eb06F6A6A6975dFB70cE51065880D&amp;startblock=1&amp;endblock=99999999&amp;sort=desc&amp;apikey=481TIWDQFUPQ91WBT8R21XA21I6GUSYYMG">https://api.bscscan.com/api?module=account&amp;action=tokentx&amp;address=0x0576961aAc8eb06F6A6A6975dFB70cE51065880D&amp;startblock=1&amp;endblock=99999999&amp;sort=desc&amp;apikey=</a>API_KEY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XiZ-QdvpEEJdXwa9vzQWjg.png" /><figcaption><a href="https://bscscan.com/apis#accounts">https://bscscan.com/apis#accounts</a></figcaption></figure><p>ซึ่ง API นี้จะดึง transfer events ของ Token ใน address ของ Smart Contract เรามาทั้งหมด ซึ่งเราสนใจเฉพาะคนที่ฝากคู่เหรียญ LP เข้ามา และ ถอนออกไป เพื่อหาคู่เหรียญ LP ที่ค้างสำหรับแต่ละ user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*uqmTf7ymGZKC6o2rMzNcnw.jpeg" /><figcaption>ขั้นตอนการฝากเหรียญ LP เพื่อไปฟาร์มใน pancakeswap เป็นรายการ token transfer event</figcaption></figure><p>ซึ่งเราสามารถไป filter หา transfer event นี้ได้ โดยการหา event ของ Token ที่เราสนใจ ว่าใครโอนเข้ามาหา KillSwitch Contract บ้าง</p><p>โดย from คือ กระเป็า wallet ของ user กับ value ที่โอนเข้ามา</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3A3wAIBV-oLhoexF_mw1fg.jpeg" /></figure><blockquote>ปล เวลา filter อย่าลืมว่า LP ที่เข้า KillSwitch Smart Contract ไม่ได้มีแค่ user wallet เท่านั้น แต่จะมีจาก Masterchef ด้วย เพราะฉะนั้นอย่าลืม filter ออก (อธิบายได้ในรูปถัดไป)</blockquote><p>ในทางกลับกันเวลาเราถอน LP ออกมา flow จะซับซ้อนกว่า เนื่องจากนี่คือสุดยอด feature ของ KillSwitch ที่จะทำการเผาคู่ LP เก็บ cake reward ให้แล้วก็แปลงกลับเป็นเหรียญที่มีมูลค่าให้ user ตามรูปข้างล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*re7r8WMemxm74p2dx8n1uw.jpeg" /><figcaption>ขั้นตอนการถอนเหรียญ LP เป็นรายการ token transfer event หลายๆ รายการ</figcaption></figure><p>ซึ่งในกรณีนี้เราจะสนใจจำนวน LP ที่ถูกถอนออกมาเท่านั้น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EMm1_KD-zoTAZgAP5hu-w.jpeg" /></figure><p>ปล สังเกตุว่า hash นี้จะมีหลาย transfer events มาก เพราะใน 1 liquidate function ของ KillSwitch เราทำหลาย operation เลย จึงต้องดูดีๆ ว่าเราสนใจ transaction ไหน ซึ่งจาก transfer event ด้านบนที่เราสนใจคือ จำนวนเหรียญ LP ที่โอนจาก Masterchef 👩‍🍳 มาที่ KillSwitch Smart Contract แต่สังเกตุว่าเราไม่สามารถหาว่า user คนไหนเป็นคนถอนได้จาก transfer event นี้</p><p>แต่เรารู้ transaction hash ทำให้เราสามารถนำไปหาต่อได้ว่าสุดท้ายแล้ว KillSwitch ของเราได้โอน BNB กลับไปให้ wallet ไหนนั่นเอง</p><pre>https://api.bscscan.com/api?module=account&amp;action=txlistinternal&amp;txhash=0x90126ff800bfe99efe3c8221d074fa59206345fc025ab3909504e3b24c514740&amp;apikey=API_KEY</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_o9D75yG0YJcygKI-HSAGg.png" /></figure><p>ซึ่งเราก็จะรู้ได้ว่า แต่ละ wallet มีการฝาก และ ถอน ไปเท่าไร</p><p>ถ้ามีการฝากมากกว่าถอน ทีมงานเราจะทำการคืน LP โดยการนำ LP ที่ค้างอยู่ ไป init ใหม่ให้ใน Smart Contract v0.0.1 fixed version (จะไม่ได้เป็นการ โอนเงินให้รายคน)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6lfZX8swMtsYa_xxD7aag.png" /><figcaption>รายชื่อ wallet ที่ทำการคืน LP ทั้งหมด</figcaption></figure><p>สำหรับใครที่ยังไม่ได้เอาคืนมากดเอาคืนได้นะคะ เพราะว่า ทางทีมงานจำเป็นต้อง Migrate Smart Contract เพื่อเพิ่ม feature ใน version 0.0.2 ต่อไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6Z7kRneuaSY2VxBtiHLaw.png" /><figcaption>อย่าทิ้งเอาไว้เลย ทีมงานไม่สบายใจ~~~~ หรือจะ seed fund กันแน่นะ :D</figcaption></figure><blockquote>ซึ่ง code ในการ หา Diff ของ LP นี้ ทางทีมงานก็ได้เปิดเป็น opensource ไว้ สำหรับสาย Deep tech ก็สามารถมาดูได้ที่นี่เลย อาจจะดูดิบๆ หน่อย จะพยายามคลีนให้นะคะ :D</blockquote><blockquote><a href="https://github.com/level11x/killswitch-incident-report-1">https://github.com/level11x/killswitch-incident-report-1</a></blockquote><h3>Issue #3 🍰 Cake Rewards จากการฟาร์ม คำนวนไม่ถูกต้อง</h3><p>ตรงนี้อาจจะต้องทำความเข้าใจการทำงานของ Masterchef 👩‍🍳 สักหน่อยก่อน คือ ทุกครั้งที่มีการฝากหรือถอน LP จะทำให้ rewards ทั้งหมดหลุดออกมาด้วย ซึ่ง rewards นี้เป็น rewards ที่เกิดจาก LP ที่ Smart Contract KillSwitch ฝากไปทั้งหมด ซึ่ง KillSwitch ลืม aware ข้อเท็จจริงตรงจุดนี้ ทำให้เอา rewards ที่หลุดมาทุกครั้ง มาให้กับคนสุดท้ายที่ถอนออกไป และ การ show cake rewards ในหน้า UI จะถูก reset เป็น 0</p><p>ซึ่งทีมงานจะทำการแก้ไขใน version 0.0.2 ต่อไป จะขออธิบายวิธีการคำนวน rewards ใหม่แบบละเอียดในบทความหน้าค่า</p><p><strong><em>References</em></strong></p><p><a href="https://bscscan.com/apis#accounts">https://bscscan.com/apis#accounts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be672a4896a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/killswitchofficial/killswitch-v0-0-1-incident-report-be672a4896a6">KillSwitch v0.0.1 Incident Report</a> was originally published in <a href="https://medium.com/killswitchofficial">KILLSWITCH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KillSwitch คำนวน TVL ยังไง โดยไม่ใช้ Price Oracle]]></title>
            <link>https://medium.com/killswitchofficial/killswitch-%E0%B8%84%E0%B8%B3%E0%B8%99%E0%B8%A7%E0%B8%99-tvl-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87-%E0%B9%82%E0%B8%94%E0%B8%A2%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B9%83%E0%B8%8A%E0%B9%89-price-oracle-9ae389b02a09?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ae389b02a09</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[kill-switch]]></category>
            <category><![CDATA[ltv]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[pancakeswap]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 02:27:49 GMT</pubDate>
            <atom:updated>2021-03-31T04:26:46.016Z</atom:updated>
            <content:encoded><![CDATA[<h3>คำนวน TVL แบบ KillSwitch, Fully Decentralized App โดยไม่ใช้ data จากภายนอก</h3><h4>Total Value Locked คือ มูลค่าของทรัพย์สินที่ถูก Lock อยู่ใน Platform ของเรา</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4bopJbDEvmebDQevAdEDg.png" /></figure><p>ในมุมมองของ KillSwitch นั้น ต้องบอกก่อนว่าจริงๆแล้วจะไม่ได้มี Token lock อยู่ใน Smart Contract ของตัวเอง เพราะ KillSwitch นั้นทำหน้าที่เหมือนตัวแทน(proxy) ในการฝากและถอน LP ของนั่งซิ่ง 🚀 แต่ละคน โดยการขอ approve ให้ KillSwitch Smart Contract สามารถดึง Token ใน wallet ของนักซิ่ง (High risk yield farmers) ไปฝากต่อที่ LP Contract Smart Contract แทน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zivQ_AiPo0c_T8KJ7cRrog.jpeg" /></figure><p>ซึ่งการคำนวน TVL ทำได้โดยดึงข้อมูลว่า KillSwitch Smart Contract ของเราฝาก LP Token เข้าไปทั้งหมดเท่าไร โดยการ get ค่า userInfo ผ่าน MasterChef Contract โดยมี parameter คือ เลข pool Id และ address ที่ทำการฝาก LP เข้าไป ซึ่งก็คือ KillSwitch Smart Contract ของเรานั่นเอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YFb8pHqMLtkXqHkqnIiJw.png" /></figure><p>จากตรงนี้เราจะได้ค่า amount มาทั้งหมด 64.537 LP แล้วมันมีมูลค่ากี่ 💲 หละ ซึ่งเราก็ต้องรู้ก่อนว่าถ้า LP คู่นี้ถูกเผาออกมาแล้วเนี่ยจะได้ Cake &lt;&gt; wBNB ฝั่งละเท่าไร</p><p>คู่ LP ที่เราสนใจคือ pool Id 1 ซึ่งเป็นคู่ของ cake และ wbnb วาร์ปไป <a href="https://bscscan.com/address/0xA527a61703D82139F8a06Bc30097cC9CAA2df5A6#readContract">LP Smart Contract</a> ซึ่งเราสามารถดู Smart Contract ของ cake, wbnb และ totalSupply ได้ที่นี่เลย ซึ่ง totalSupply คือจำนวน LP Token ทั้งหมดในระบบ (ทด totalSupply ไว้ก่อนจะนำไปใช้ใน step หน้า)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNuii2UjcXtCpqB056C6aA.png" /></figure><p>โดยวิธีการคือ เราจะต้องไปหา Balance ของทั้งสอง Token ก่อนว่ามี Token locked ใน Smart Contract ของ LP อยู่เท่าไร วิธีการคือเรียกใช้คำสั่ง balanceOf ของ ERC20 interface ของแต่ละ token</p><p>🍰 token0–<a href="https://bscscan.com/address/0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82#readContract">0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjyJvZbLHnyi-qk8bCzJ-w.png" /></figure><p>💲 token1–<a href="https://bscscan.com/address/0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c#readContract">0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LmK1PJ4eC1kcwSV1S-Dbg.png" /></figure><p>โดย address input ก็คือ Smart Contract ของ LP เพื่อดู Balance ของ token0 และ token1</p><p>ถึงตอนนี้เราก็จะรู้จำนวนเหรียญ LP ทั้งหมด (totalSupply) และ มูลค่าเหรียญที่อยู่ใน Smart Contract (balance0, balance1)</p><p>เพราะฉะนั้น ลองเทียบบรรญัตไตรยาง</p><p>LP ทั้งหมดมีมูลค่า balance0<br>1 LP จะมีมูลค่า balance0 / LP นั่นเองง</p><p>แต่เราต้องทำสองข้าง</p><p><em>1 LP ของ token0 จะมีมูลค่าเท่ากับ balance0 / totalSupply ( Total LP Token)<br>1 LP ของ token1 จะมีมูลค่าเท่ากับ balance1 / totalSupply ( Total LP Token)</em></p><p>เอามาคูณด้วยจำนวน LP ที่เรามี ก็จะได้เป็นสูตรเผาคู่เหรียญด้านล่างเลย</p><pre>token0 = (balance0 * LP) / totalSupply<br>token1 = (balance1 * LP) / totalSupply</pre><p>จากสูตรด้านบน ใครอยากจะเอาไปทำเป็น Smart Contract ก็ได้นะ หรือจะ get มาที่ละค่าแล้วก็คำนวนกันที่ front end ก็ตามสะดวกเลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfSpOD4uoB_MRZsNWK1E5A.png" /><figcaption>ตัวอย่าง Smart Contract ที่ใส่สูตรคำนวน token</figcaption></figure><p>แล้วเราก็สามารถเผาคู่ LP Token ให้กลับมาเป็น cake และ wbnb ได้แล้ว ทีนี้ถ้าเรารู้ว่า cake ราคาเท่าไร wbnb ราคาเท่าไร ก็ End game</p><p>ถึงจุดนี้จะบอกว่าถ้าเรารู้ราคาก็รู้ TVL ทั้งหมด</p><p>ถ้าเราสามารถดึงราคาจาก Price Oracle ได้อยู่แล้วก็คงจะไม่มีปัญหาอะไร สามารถข้ามไปตอนจบบทความได้เลย</p><p>แต่ถ้าไม่มีหละ~~~</p><p>ℹ️ Concept คือในเมื่อใน 🍰 pancake swap จะมี pool ของเหรียญที่คู่กับ stable coin อย่าง busd อยู่เสมอ เช่น wbnb &lt;&gt; busd ซึ่งเราก็ไม่ต้อง swap เหรียญจริงๆ ก็สามารถรู้อัตราส่วนว่า 1 wbnb จะได้เป็นกี่ busd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vTy8WEmeqEz4I70YTCKMg.png" /></figure><p>จาก <a href="https://bscscan.com/address/0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F#readContract">Pancake Router Smart Contract</a> ด้วย read function getAmountsOut ก็จะรู้ราคา wbnb ในหน่วย busd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDDkubSbvWtddGUSXiIQYQ.png" /></figure><p>โดย จะรับเป็นค่า path คือ Smart Contract Address ของคู่ LP (wbnb, busd) ลำดับต้องเรียงแบบนี้เลย และ amountIn เช่นเราต้องการทดสอบว่าแลก 1 bnb (1 ตามด้วย ศูนย์ 18 ตัว) จะได้ออกมากี่ busd จากราคา bnb ณ ตอนที่เทสก็ประมาณ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtMVtw2LSnPJ46wOkijvRg.png" /><figcaption><a href="https://www.coingecko.com/en/coins/binance-coin">https://www.coingecko.com/en/coins/binance-coin</a></figcaption></figure><p>จะได้ amount มาเป็น ~292.22 busd ซึ่งถือเป็น estimate ที่ใกล้เคียงเลยทีเดียว</p><p>ทีนี้เริ่มเห็นภาพแล้วใช่มั้ยทุกคนนน 🐥🐥🐥 ถ้าเรารู้ว่า cake ราคากี่ wbnb แล้ว wbnb ราคากี่ busd ก็จะได้ราคา cake ต่อ busd</p><blockquote>ขอ assume/estimate ว่า 1 busd = 1 💲 เพราะมันเป็น stable coin 👀 ถ้าใครไม่เชื่อก็อาจจะต้องไปต่อ Price Oracle นะฮะ</blockquote><p>เราก็ทำเหมือนเดิม แต่เปลี่ยนเป็นคู่ cake &lt;&gt; wbnb แทน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PS7qpQfPs_U6J6ID5tUtg.png" /></figure><p>ก็จะได้ว่า 1 cake มีค่าประมาณ 0.0587 wbnb เท่านี้เราก็จะสามารถคำนวน TVL ของ KillSwitch จาก LP token ได้แล้ว</p><pre>TVL = cake_in_busd * cake + wbnb_in_busd * wbnb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*2GaxXOYkV8paT0ECvXmUZQ.png" /><figcaption><a href="https://killswitch.finance/">https://killswitch.finance/</a></figcaption></figure><p>References</p><p><a href="https://uniswap.org/docs/v2/advanced-topics/pricing/">Uniswap | Pricing</a></p><p><a href="https://www.coingecko.com/en/coins/binance-coin">Binance Coin price, BNB price index, chart, and info | CoinGecko</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ae389b02a09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/killswitchofficial/killswitch-%E0%B8%84%E0%B8%B3%E0%B8%99%E0%B8%A7%E0%B8%99-tvl-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87-%E0%B9%82%E0%B8%94%E0%B8%A2%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B9%83%E0%B8%8A%E0%B9%89-price-oracle-9ae389b02a09">KillSwitch คำนวน TVL ยังไง โดยไม่ใช้ Price Oracle</a> was originally published in <a href="https://medium.com/killswitchofficial">KILLSWITCH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jmeter to insert batch data into Redis using Groovy script]]></title>
            <link>https://tanopwan.medium.com/jmeter-to-insert-batch-data-into-redis-using-groovy-script-89bcad6a1d84?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/89bcad6a1d84</guid>
            <category><![CDATA[batch-insert]]></category>
            <category><![CDATA[groovy]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[jmeter]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 02:21:01 GMT</pubDate>
            <atom:updated>2021-03-23T03:21:41.697Z</atom:updated>
            <content:encoded><![CDATA[<h4>My requirement is to insert batch data into Redis.</h4><p>In Jmeter, there is a plugin called RedisDataSet. After exploring this plugin, it is only for read but not write.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45tqEmAYjrzj0YIXDtYtAA.png" /></figure><p><a href="https://jmeter.apache.org/usermanual/component_reference.html#JSR223_Sampler">From the documentation</a></p><blockquote>The JSR223 Sampler allows JSR223 script code to be used to perform a sample or some computation required to create/update variables.</blockquote><blockquote>To benefit from caching and compilation, the language engine used for scripting must implement JSR223 <a href="https://docs.oracle.com/javase/8/docs/api/javax/script/Compilable.html"><strong>Compilable</strong></a> interface (Groovy is one of these, java, beanshell and javascript are not)</blockquote><p>So JSR223 allows us to write the Groovy script which we can use Java library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZrKllNX_KZLpEW09QQQ4w.png" /></figure><p>Let’s add JSR223 Sampler and add some coding</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd1dbb8f376550a151ddc17717c4eb32/href">https://medium.com/media/fd1dbb8f376550a151ddc17717c4eb32/href</a></iframe><p>We can use Java libraries as normal, so I used Jedis for a Redis client for simple set key. 😃</p><p>One more thing, as we need Jmeter to load the Jedis library by putting the jar file to /lib folder following the jmeter <a href="https://www.perfmatrix.com/jmeter-folder-structure/">folder structure</a>.</p><p>Jar can be downloaded <a href="https://jar-download.com/artifacts/redis.clients/jedis/2.8.1">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTBw0PMw3H9gGuUtMxRozg.jpeg" /></figure><blockquote>Reload your jmeter one time and Enjoy!!</blockquote><p>Reference:</p><p><a href="https://jmeter-plugins.org/wiki/RedisDataSet/">https://jmeter-plugins.org/wiki/RedisDataSet/</a></p><p><a href="https://jmeter.apache.org/usermanual/component_reference.html#JSR223_Sampler">Apache JMeter - User&#39;s Manual: Component Reference</a></p><p><a href="https://www.perfmatrix.com/jmeter-folder-structure/">https://www.perfmatrix.com/jmeter-folder-structure/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89bcad6a1d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMutableProperty0 ใน Kotlin]]></title>
            <link>https://tanopwan.medium.com/kmutableproperty0-%E0%B9%83%E0%B8%99-kotlin-911896fd58fd?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/911896fd58fd</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[pass-by-reference]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[kmutableproperty0]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 12:14:54 GMT</pubDate>
            <atom:updated>2021-02-22T12:14:54.200Z</atom:updated>
            <content:encoded><![CDATA[<h4>ใช้เมื่อเราต้องการ pass reference เข้าไปใน class หรือ function เพื่อแก้ไข object นั้นๆโดยตรง</h4><p>ปกติแล้วใน Kotlin เวลาเราเรียกใช้ function แล้วส่ง property เข้าไป จะเป็นการ <strong><em>pass-by-value</em></strong> นั่นก็คือ copy property value ไป ทำให้เวลาเรามีการแก้ไข ข้อมูลใน function จะไม่กระทบกับข้างนอกนั่นเอง</p><p>Mutable แปลว่าแก้ไขได้ <strong>KMutableProperty</strong> ก็คือทำให้ property นั้นแก้ไขได้ (อารมณ์เหมือน <strong><em>pass-by-reference</em></strong>) แต่มัน explicit คือประกาศตรงๆเลยว่าแก้ไขได้นะ</p><h4>วิธีประกาศใช้ใน class หรือ function</h4><p>วิธีใช้ก็คือเรา wrap <strong><em>KMutableProperty0</em></strong> กับ class ที่เราต้องการที่แก้ไขได้เลย ในตัวอย่าง class property ที่เราต้องการแก้ไขชื่อ RabbitTemplate</p><pre><em>class </em>Foo(<br>    <em>private val </em>rabbitTemplate: <em>KMutableProperty0</em>&lt;RabbitTemplate?&gt;<br>)</pre><p>หรือ ใน fun</p><pre>fun bar(value: KMutableProperty0&lt;RabbitTemplate?&gt;) {</pre><pre>}</pre><h4>วิธียัดตัวแปรเข้าไปใน KMutableProperty0</h4><p>ใช้ this:: เพื่อบอก scope</p><pre><em>private var </em>rabbitTemplate: RabbitTemplate? = <em>null</em></pre><pre>PublishRunnable(<em>this</em>::rabbitTemplate)</pre><p>หรือ ในกรณีที่ scope ไม่ใช่ this เช่นพวก callback ต่างๆ</p><pre><em>private var </em>rabbitTemplate: RabbitTemplate? = <em>null<br>val that = this</em></pre><pre>functionThatTakeCallback {<br>    PublishRunnable(<em>that</em>::rabbitTemplate)<br>}</pre><h4>วิธีใช้ ผ่าน .get() .set()</h4><pre>fun bar(value: KMutableProperty0&lt;RabbitTemplate?&gt;) {<br>    value.get()?.doSomething()<br>    value.set(null)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=911896fd58fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ORC Core Java 1.6 and Column Encryption with AWS KMS ]]></title>
            <link>https://medium.com/ascend-developers/orc-core-java-1-6-and-column-encryption-with-aws-kms-300c85a095e?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/300c85a095e</guid>
            <category><![CDATA[aws-kms]]></category>
            <category><![CDATA[column-encryption]]></category>
            <category><![CDATA[orc-file]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 08:47:51 GMT</pubDate>
            <atom:updated>2021-01-18T08:47:51.285Z</atom:updated>
            <content:encoded><![CDATA[<h4>In Kotlin</h4><blockquote>If you work with Hadoop, everything should be working out of the box ☑️ but if you are using Java Core, this could be helpful</blockquote><p>Continue from the previous article <a href="https://developers.ascendcorp.com/move-read-only-truemoney-transactions-from-mysql-to-s3-and-query-with-athena-39a40953e22">Move read-only TrueMoney transactions from MySQL to S3 and query with Athena</a>, we have covered on how to query data in S3 using the AWS Athena. In this blog, we will dive deeper into one feature of the ORC specifications.</p><p>As Apache has introduced the new ORC file specification version 1.6, that comes with a feature <a href="https://issues.apache.org/jira/browse/ORC-14">Column Encryption</a>. Column Encryption feature will encrypt each column with a local key per column and results in another level of security in your ORC files.</p><h3>From the specifications</h3><blockquote>Column encryption provides fine-grain column level security even when many users have access to the file itself. The encryption is transparent to the user and the writer only needs to define which columns and encryption keys to use. When reading an ORC file, if the user has access to the keys, they will get the real data. If they do not have the keys, they will get the masked data.</blockquote><blockquote>Each encrypted column in each file will have a random local key generated for it. Thus, even though all of the decryption happens locally in the reader, a malicious user that stores the key only enables access that column in that file. The local keys are encrypted by the Hadoop or Ranger Key Management Server (KMS). The encrypted local keys are stored in the file footer’s StripeInformation.</blockquote><figure><img alt="https://orc.apache.org/specification/ORCv1/" src="https://cdn-images-1.medium.com/max/580/0*HVnln9uoCgu48qj7.png" /><figcaption>Credit: <a href="https://orc.apache.org/specification/ORCv1/">https://orc.apache.org/specification/ORCv1/</a></figcaption></figure><blockquote>In conclusion, keys 🔑 to decrypt the column data are stored encrypted 🔐 in the Stripe Footer. Repeat this 3 times 😂</blockquote><p>It wouldn’t make sense if we just keep the keys <strong>unencrypted and ready to use </strong>beside our data right? 😅😅😅😅😅😅</p><p>This means, to decrypt the column data, we need to decrypt the keys first with <strong>another</strong> key 🗝 (Master key)</p><p>The specification said that keys are stored in Hadoop or Ranger Key Management Server (KMS) which in our case we have neither of them (We do have the Java Core library though). So the main purpose of this blog is to implement a Java KeyProvider interface with the AWS KMS</p><h3>Why so complicated?</h3><h4>Before starting the implementation, you should understand the concept of Envelope encryption 📩</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*Q0OcvgTqe5kUM98k.png" /></figure><p><strong>AWS KMS</strong> has the customer master key (CMK) that have the following properties</p><ul><li>Never leaves AWS</li><li>Use to encrypt/decrypt data on AWS (data has to be less than 4KB)</li></ul><p>Since the whole table cannot be sent to encrypt at AWS KMS, but the local key can.</p><blockquote>let’s do some def. here: local key = data key</blockquote><p><strong>AWS KMS</strong> has provided us developers the way to generate this data key, from the Generate Data Key function. We would get 2 keys from the result.</p><p><strong>The First Key </strong>is a plaintext data key (aka. local key 🔑 ) for encrypting a column.<br><strong>The Second Key </strong>is an encrypted data key (aka. local key 🔐 ) that will be stored in the file footer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*aTA67N1DsMuES6vo" /><figcaption>Credit: <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html">https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html</a></figcaption></figure><p>That is the <strong>specification</strong> of 1.6. How about the <strong>implementation??? </strong>After a lot of googling and reading documentations, I found that the Java Core has provided <strong><em>InMemoryKeystore</em></strong> class to provide the implementation to generate</p><p>a <strong>local key </strong>🔑 and an <strong>encrypted local key</strong> 🔐</p><p>After the ORC file writer is done using the local key 🔑 to encrypt a column, it should delete this key for security reasons and save the encrypted local key 🔐 in the footer of the ORC file.</p><p>This class is good for testing but in the real implementation we cannot store Master key 🗝 in the memory. 😅 We need a safer place to store this Master key, since AWS is our tech stack so <strong>AWS KMS</strong> is what we prefer.</p><p>🥑🥑🥑 By the time I worked on this, it could be my bad googling skill but I could not find any AWS Keystore implementations anywhere that fit the KeyProvider interface.</p><p>Fine!! Let’s implement this. After I took a look at the KeyProvider Interface and the specifications, it already has an AWS <strong>kind</strong> for the key provider enum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*eAcq46dQYVX6BsHfUEFwZg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05aa314169d5152884844d4761075d61/href">https://medium.com/media/05aa314169d5152884844d4761075d61/href</a></iframe><p>The important functions here are createLocalKey and decryptLocalKey.</p><p><strong>createLocalKey</strong> function is called when the ORC file writer wants to encrypt a column. AWS KMS is called in order to generate the data keys and return with both encrypted 🔐 and decrypted 🔑 keys.</p><p><strong>decryptLocalKey</strong> function is called when the ORC file reader wants to read a column. AWS KMS is called in order to decrypt the encrypted data key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02cd2d4c42d7bdef5627c2758ce76238/href">https://medium.com/media/02cd2d4c42d7bdef5627c2758ce76238/href</a></iframe><p>Now to use this AWSKeystore.kt we just implemented, we need to add the key to the store.</p><pre>val awsKeystore = AwsKeystore(kmsClient, &quot;KEY-ID&quot;, &quot;AES_256&quot;)<br>awsKeystore.addKey(&quot;key_name&quot;, EncryptionAlgorithm.<em>AES_CTR_256</em>)</pre><p>and call setKeyProvider in the ORC writer options</p><pre>OrcFile<br>  .writerOptions(Configuration())<br>  .setKeyProvider(awsKeystore)<br>  .encrypt(&quot;key_name:column_name&quot;)</pre><p>When we want to read the file, we do the same thing by calling KeyProvider in the ORC reader options</p><pre>OrcFile<br>  .readerOptions(Configuration())<br>  .setKeyProvider(awsKeystore)</pre><blockquote>Now your local keys are protected by AWS KMS ✅</blockquote><h4>References:</h4><p><a href="https://medium.com/better-programming/aws-key-management-service-all-you-need-to-know-8c6b0e17a2d0"><em>https://medium.com/better-programming/aws-key-management-service-all-you-need-to-know-8c6b0e17a2d0</em></a><em><br></em><a href="https://medium.com/@HTA_AWS/aws-kms-82c80a4943c8"><em>https://medium.com/@HTA_AWS/aws-kms-82c80a4943c8</em></a><em><br></em><a href="https://orc.apache.org/api/orc-core/org/apache/orc/InMemoryKeystore.html"><em>https://orc.apache.org/api/orc-core/org/apache/orc/InMemoryKeystore.html</em></a><em><br></em><a href="https://github.com/apache/orc/blob/master/java/core/src/test/org/apache/orc/TestVectorOrcFile.java"><em>https://github.com/apache/orc/blob/master/java/core/src/test/org/apache/orc/TestVectorOrcFile.java</em></a><em><br></em><a href="https://orc.apache.org/specification/ORCv1/"><em>https://orc.apache.org/specification/ORCv1/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=300c85a095e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ascend-developers/orc-core-java-1-6-and-column-encryption-with-aws-kms-300c85a095e">ORC Core Java 1.6 and Column Encryption with AWS KMS 🔐</a> was originally published in <a href="https://medium.com/ascend-developers">Ascend Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Move read-only Truemoney transactions from MySQL to S3 and query with Athena   ]]></title>
            <link>https://medium.com/ascend-developers/move-read-only-truemoney-transactions-from-mysql-to-s3-and-query-with-athena-39a40953e22?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/39a40953e22</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[orcs]]></category>
            <category><![CDATA[athena]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 15:50:36 GMT</pubDate>
            <atom:updated>2021-01-11T15:50:36.798Z</atom:updated>
            <content:encoded><![CDATA[<h3>Move read-only TrueMoney transactions from MySQL to S3 and query with Athena 🥚 🐣 🐥</h3><h4>To reduce the cost on the database size and to make the application works faster!!!</h4><p>For any running system on production, data is growing every second so our database size is increasing. For a typical relational database, it can only scale up vertically and of course more expensive 🤑 and slower.</p><p>According to regulations and customers, we have classified the transactions on how we access and modify the data as below:</p><ul><li><strong>Read/Write transaction</strong> is the transaction that still be accessed and can be updated by application</li><li><strong>Read-Only transaction</strong> is the transaction that still need to be accessed but will not be updated</li></ul><p>The <strong>read-only transactions</strong> are the transactions we would like to do housekeeping here but we still need to be able to query these transactions</p><blockquote>requirements are pain in the abdomen❣️ I know</blockquote><p>🥚 There were many choices out there but we chose to explore a bit in the field of Big Data, storing ORC files in AWS S3 and using AWS Athena to query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*1Zw__Nlfd-HaesMUu3TK8w.png" /></figure><h4>🐤 A lot of new keywords right? so Let’s do some definitions</h4><p><strong>Columnar file format</strong> is the format that data are stored in <strong>column based</strong> not in row based (<a href="https://blog.matthewrathbone.com/2019/11/21/guide-to-columnar-file-formats.html">read more</a>)</p><p>ORC is a <strong>columnar file format</strong> that has <strong>data types</strong> and designed for <strong><em>Hadoop workloads</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/57/1*aNoISD8Jr3AmGYi9BODCgw.png" /></figure><p>As above the definition, how would we use it without Hadoop? Their <a href="https://orc.apache.org/">official website</a> has stated that there are many ways to adopt ORC file format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*lvNJAHHqsrdVcRnxNxzuCA.png" /></figure><p>As we did not have any Big Data framework or environment, we chose to work with Java Core ORC.</p><p>As Apache ORC has provided us the Java Core library, Perfect!! we can create a simple JAVA application that schedule to read transactions from MySQL and convert rows based to column based and save as orc files. There is also a tutorial for it. <a href="https://www.javahelps.com/2020/08/read-and-write-orc-files-in-core-java.html">Get Started</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*3oY1jMf1QZYNevbwtXrWJQ.png" /></figure><blockquote>I assumed that the example in the tutorial went well and we have orc files uploaded to S3 🤞 🤞 Cross fingers</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yQxuVq5rDfHdajOu6uT1w.jpeg" /></figure><blockquote>They can be in any structured folders but this will give a benefit of partitioning which I will explain later. The file names are also irrelevant and only for human reading purpose</blockquote><h3>🐣 AWS Athena</h3><p>Amazon Athena is an interactive query service that makes it easy to analyse data in Amazon S3 using standard SQL.</p><h3>In Athena console</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Op9CCRxqD7GsAB66D4xexg.png" /></figure><h4>Create a Database from S3</h4><p>This will tell Athena a database to query is from S3</p><pre>CREATE DATABASE IF NOT EXISTS [DATABASE_NAME]<br>  LOCATION &#39;s3://path/to/orc/files&#39;</pre><h4>Create a Table with Schema</h4><p>This will create a table structure when reading orc file and we also specify the format as <strong>OrcSerde </strong>and the base location in S3</p><pre>CREATE EXTERNAL TABLE IF NOT EXISTS [DATABASE_NAME].[TABLE_NAME] (<br>  `id` string,<br>  `status` string,<br>  ...<br>  `created` timestamp,<br>  `updated` timestamp<br>) PARTITIONED BY (<br>  year string,<br>  month string,<br>  day string<br>)<br>ROW FORMAT SERDE &#39;org.apache.hadoop.hive.ql.io.orc.OrcSerde&#39;<br>WITH SERDEPROPERTIES (<br>  &#39;serialization.format&#39; = &#39;1&#39;<br>) LOCATION &#39;s3://path/to/orc/files/&#39;<br>TBLPROPERTIES (&#39;has_encrypted_data&#39;=&#39;false&#39;);</pre><h4>Working with Partitions</h4><p>In the table we just created we also specify the partition folders in <strong><em>PARTITIONED BY</em></strong>. Athena can understand partitioning by folder structure names. This will help reducing the cost of data scanned. 🤑</p><p>For example, /path/to/orc/files/year=2020/month=12/day=31/*.orc</p><p>Then all files under this structure can be loaded using the command</p><pre>MSCK REPAIR TABLE [TABLE_NAME];</pre><p>After running load partitions, Athena will partition the files under the partition structures</p><blockquote>Repair: Added partition to metastore [TABLE_NAME]:year=2015/month=12/day=04<br>Repair: Added partition to metastore [TABLE_NAME]=2016/month=07/day=19<br>Repair: Added partition to metastore [TABLE_NAME]=2016/month=07/day=21<br>Repair: Added partition to metastore [TABLE_NAME]=2016/month=12/day=03</blockquote><p>Now we can use normal SQL to query as we already have the database and the table with partitions 😏</p><pre>SELECT * FROM &quot;[DATABASE_NAME]&quot;.&quot;[TABLE_NAME]&quot; WHERE year=&#39;2020&#39; limit 10</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMZklLzQ8MUaPZ6jeepwbQ.jpeg" /></figure><blockquote>So now we can archive data to s3 and still able to use SQL query on archive data using AWS Athena 👌👌👌</blockquote><h3>🐥 What TrueMoney benefits from implementing this?</h3><h4>Cost Reduction ⭐️ ⭐️ ⭐️ ⭐️ ⭐️</h4><p>During Covid-19 in 2020–2021. Costs matter even more 💰 . As S3 storage is much cheaper than the SSD storage in RDS</p><ul><li>Estimate data of 20 TB on RDS will cost 2300$/mo but it will cost 460$/mo for S3 standard tier. And 20 TB on RDS will not be 20 TB on S3 as it is binary and compressed. Imagine how much we will can for a year!</li><li>This is not including the costs for database snapshots</li><li>Since the ORC file is designed for big data, it stores in <strong>protocol buffer</strong> and compressed format. The size is pretty d*rn small❣️</li></ul><h4>Application Performance and Maintenance ⭐️ ⭐️</h4><ul><li>Smaller database = easier to query and make modifications</li><li>The application will work on a small set of data that are left in main database</li><li>We had to add more disk to the database every 3–6 months, and we hope next month we don’t have to do so. We developer may rest in piece 🛏</li></ul><h4>Easy Access 📅 and Security ⭐️ ⭐️ ⭐️ ⭐️</h4><p>ORC files stored in S3 are compressed and in binary. So they are unreadable using a normal editor unlike other formats (JSON, CSV). This will give a harder way on accessing files but Yes 😁 we do have a way out of this with Athena of course❗️ Athena recently added support on OrcSerde.</p><ul><li>🆎 it gives us an ability to use normal SQL queries on these archive files</li><li>🙈 We can access with Index from ORC footer</li><li>🗄 We can use partitioning to skip data scanned</li><li>🔒 We can use<strong> column encryption</strong> to ensure some sensitive columns will not be exposed ❗️This is still new so Athena is not yet support at the time.</li><li>Even though the ORC files are stored separately in smaller files on S3. We are able to load all partitions in Athena 🎉 So in logical level, it is the same as we have another MySQL behind Athena</li></ul><blockquote>Next is to encrypt the data within ORC file using <strong>Column Encryption</strong> 🔐🔐🔐</blockquote><h4>References;</h4><p><a href="https://blog.matthewrathbone.com/2019/11/21/guide-to-columnar-file-formats.html"><em>https://blog.matthewrathbone.com/2019/11/21/guide-to-columnar-file-formats.html</em></a><em><br></em><a href="https://www.javahelps.com/2020/08/read-and-write-orc-files-in-core-java.html"><em>https://www.javahelps.com/2020/08/read-and-write-orc-files-in-core-java.html</em></a><em><br></em><a href="https://orc.apache.org/docs/core-java.html"><em>https://orc.apache.org/docs/core-java.html</em></a><em><br></em><a href="https://docs.aws.amazon.com/athena/latest/ug/create-database.html"><em>https://docs.aws.amazon.com/athena/latest/ug/create-database.html</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39a40953e22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ascend-developers/move-read-only-truemoney-transactions-from-mysql-to-s3-and-query-with-athena-39a40953e22">Move read-only Truemoney transactions from MySQL to S3 and query with Athena 🥚 🐣 🐥</a> was originally published in <a href="https://medium.com/ascend-developers">Ascend Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[วิธีรัน RabbitMQ Cluster บน MacOS ด้วย Docker]]></title>
            <link>https://tanopwan.medium.com/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B8%A3%E0%B8%B1%E0%B8%99-rabbitmq-cluster-%E0%B8%9A%E0%B8%99-macos-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-docker-d8e3bdb63bb7?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e3bdb63bb7</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[local-development]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Wed, 06 Jan 2021 10:36:30 GMT</pubDate>
            <atom:updated>2021-01-06T11:01:01.504Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>สำหรับ Development เท่านั้นนะ เพราะว่าเวลาใช้งานจริง RabbitMQ เค้า recommend ว่า ควรจะอยู่คนละเครื่องนะ</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8bsf7NftuXFf8x8OND5bA.png" /></figure><p>RabbitMQ คือ Message Broker อันนึงที่เขียนด้วย Erlang ซึ่ง support หลาย protocol เช่น MQTT, AMQP ทุกท่านสามารถศึกษาเพิ่มเติมได้จากที่นี่เลย <a href="https://www.rabbitmq.com/">https://www.rabbitmq.com</a></p><p>ในเมื่อเราจะรันด้วย Docker ก็ต้องเริ่มด้วยการหา image ที่เราต้องการก่อนเลย สามารถเข้าไปที่ docker hub ได้เลย แล้ว search หา rabbitmq image (<a href="https://hub.docker.com/_/rabbitmq">link</a>) ก็จะพบว่ามีหลาย version ให้เลือกมากมาย ก็ทดไว้ก่อนอยากได้ version ไหน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*iUM_HyV8wPhicuPIPjastQ.png" /></figure><h3>วิธีใช้ Environment Variable</h3><p>สามารถดูได้ในหน้า Docker hub ของ image นั้นๆเลย ซึ่ง ENV ที่สำคัญที่เราต้องใช้คือ RABBITMQ_ERLANG_COOKIE เอาไว้ใช้สำหรับทำ clustering นั่นเอง ง่ายๆคือ เซ็ตให้เหมือนกัน ก็จะเป็น cluster เดียวกัน ทดไว้ก่อน</p><p><strong><em>-e “RABBITMQ_ERLANG_COOKIE=ABCD1234”</em></strong></p><h3>Mount Disk</h3><p>ทีนี้เลื่อนลงมาดูวิธี mount disk เพื่อให้ rabbitmq ใช้กัน ซึ่งจากหน้า docker hub ได้บอกไว้ว่า default ที่จะเก็บไฟล์อยู่ที่ <strong><em>/var/lib/rabbitmq</em></strong> เราเลยจะ map เข้ามาที่ drive ของ machine ของเรา ซึ่งเป็นที่ไหนก็ได้ตัวอย่างเช่น</p><p><strong><em>-v /Users/tanopwan/Data/rabbit1:/var/lib/rabbitmq<br>-v /Users/tanopwan/Data/rabbit1/logs:/var/log/rabbitmq</em></strong></p><p>ตามตัวอย่างนี้จะ map ทั้ง disk สำหรับ database และ log ซึ่งจะขอทดค่านี้ไว้ก่อนเหมือนเดิม</p><h3>สร้าง Network</h3><p>ต่อไปคือ การที่จะให้ Rabbit 2 nodes มองเห็นกันได้นั้น เราต้องทำให้มันมองเห็นกันได้ในมุม network โดยการสร้าง docker network ขึ้นมา ชื่อว่า my-net</p><pre>docker network create my-net</pre><h3>สร้าง Nodes</h3><p>เรามีองค์ประกอบพร้อมแล้ว ก็สร้างได้เลย โดยในที่นี้ขอเลือก image rabbitmq:3.7.8-management เป็นตัวที่มี management plugin ด้วย</p><h4>Node แรก</h4><pre>docker run -d -h node-1.rabbit                           \<br>--name rabbit                                            \<br>-p &quot;4369:4369&quot;                                           \<br>-p &quot;5672:5672&quot;                                           \<br>-p &quot;15672:15672&quot;                                         \<br>-p &quot;25672:25672&quot;                                         \<br>-p &quot;35197:35197&quot;                                         \<br>-e &quot;RABBITMQ_USE_LONGNAME=true&quot;                          \<br>-e &quot;RABBITMQ_LOGS=/var/log/rabbitmq/rabbit.log&quot;          \<br>-e &quot;RABBITMQ_ERLANG_COOKIE=ABCD1234&quot;                     \<br>-v /Users/tanopwan/Data/rabbit1:/var/lib/rabbitmq        \<br>-v /Users/tanopwan/Data/rabbit1/logs:/var/log/rabbitmq   \<br>--network my-net \<br>rabbitmq:3.7.8-management</pre><h4>Node สอง</h4><pre>docker run -d -h node-2.rabbit                           \<br>--name rabbit2                                           \<br>-p &quot;4370:4369&quot;                                           \<br>-p &quot;5673:5672&quot;                                           \<br>-p &quot;15673:15672&quot;                                         \<br>-p &quot;25673:25672&quot;                                         \<br>-p &quot;35198:35197&quot;                                         \<br>-e &quot;RABBITMQ_USE_LONGNAME=true&quot;                          \<br>-e &quot;RABBITMQ_LOGS=/var/log/rabbitmq/rabbit.log&quot;          \<br>-e &quot;RABBITMQ_ERLANG_COOKIE=ABCD1234&quot;                     \<br>-v /Users/tanopwan/Data/rabbit2:/var/lib/rabbitmq        \<br>-v /Users/tanopwan/Data/rabbit2/logs:/var/log/rabbitmq   \<br>--network my-net \<br>rabbitmq:3.7.8-management</pre><p>สอง node นี้จะต่างกันนิดนึงตรงที่ว่า เรารัน บนเครื่องเดียวกันทำให้ เราไม่สามารถใช้ Port ในเครื่องเราซ้ำได้ Node ที่สองเลยเป็น 5673 แทน</p><p>แก้ /etc/hosts สักหน่อย โดยการเพิ่ม node-1.rabbit, node-2.rabbit ไปที่ 127.0.0.1</p><pre>127.0.0.1 localhost node-1.rabbit node-2.rabbit</pre><p>หลังจากสำรวจว่า node เรารันขึ้นทั้งสอง node โดยการเข้าไปที่ <a href="http://localhost:15672/">http://node-1.rabbit:15672</a> และ <a href="http://localhost:15673/">http://node-2.rabbit:15673</a> แล้ว โดยมี default username:password คือ guest:guest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*d9idqLGf3ySXvcCIsDbxbA.png" /></figure><p>แต่สังเกตุว่าตอนนี้จะมี node เดียวของใครของมัน วิธี join cluster ให้ stop rabbit2 ก่อนด้วยคำสั่ง stop_app หลังจากนั้น join_cluster แล้ว start_app กลับมา</p><pre>docker exec rabbit2 rabbitmqctl stop_app<br>docker exec rabbit2 rabbitmqctl join_cluster rabbit@node-1.rabbit docker exec rabbit2 rabbitmqctl start_app</pre><p>กลับมาดูที่ <a href="http://localhost:15672/">http://node-1.rabbit:15672</a> หรือ <a href="http://localhost:15673/">http://node-2.rabbit:15673</a> ก็จะเห็น node เพิ่มมาแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NF6etFadZB1sW3z7g2ok9g.png" /></figure><blockquote>เสร็จแล้ว เรียบร้อย ไม่ยาก ง่ายยย</blockquote><p><em>Ref: </em><a href="http://josuelima.github.io/docker/rabbitmq/cluster/2017/04/19/setting-up-a-rabbitmq-cluster-on-docker.html"><em>http://josuelima.github.io/docker/rabbitmq/cluster/2017/04/19/setting-up-a-rabbitmq-cluster-on-docker.html</em></a><em><br>Ref: </em><a href="https://hub.docker.com/_/rabbitmq">https://hub.docker.com/_/rabbitmq</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e3bdb63bb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang sqlx กับ postgresql กับ cockraochdb]]></title>
            <link>https://tanopwan.medium.com/golang-sqlx-%E0%B8%81%E0%B8%B1%E0%B8%9A-postgresql-%E0%B8%81%E0%B8%B1%E0%B8%9A-cockraochdb-515db24ee672?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/515db24ee672</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[cockroachdb]]></category>
            <category><![CDATA[entity]]></category>
            <category><![CDATA[sqlx]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Sat, 10 Oct 2020 14:00:57 GMT</pubDate>
            <atom:updated>2020-10-10T14:00:57.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*rLYsk8jdz7PmGjxnM4fEfw.jpeg" /></figure><p>ภาษา Go กับ Backend ยังไงก็หนีไม่พ้น Database อะนะ</p><p>ทำไมต้อง postgresql หลักๆ ก็น่าจะเพราะมัน free และ feature เยอะ ส่วนทำไม cockroachdb ก็เพราะว่า มันมี interface driver ที่เหมือนๆกับ postgresql เลย แล้วก็สามารถ scale ได้</p><p>ทั้งสอง database นี้จะมี driver ตัวเดียวกัน คือ postgres driver</p><pre>import _ &quot;github.com/lib/pq&quot;</pre><p>ส่วนตัวไม่ค่อยชอบใช้ ORM (Object-relational mapping) เท่าไร เพราะ high level เกิน ไม่รู้ว่ามันจะทำอะไรเกินไปมั้ย แต่ standard lib ที่ go มีมาให้ก็ low level เกินไปอะ scan data ตาม bytes</p><p>ก็หาทางสายกลาง คือ sqlx</p><pre>import &quot;github.com/jmoiron/sqlx&quot;</pre><pre>connStr := fmt.Sprintf(&quot;postgres://%s:%s@%s:%s/%s&quot;, user, password, host, port, database)<br>db, err := sql.Open(&quot;postgres&quot;, connStr)<br><em>if </em>err != <em>nil </em>{<br>   os.Exit(1)<br>}<br><em>defer </em>db.Close()</pre><pre>dbx := sqlx.NewDb(db, &quot;postgres&quot;)</pre><blockquote>ซึ่ง Code ข้างบน ต่อได้ทั้ง postgresql และ cockroachdb เลย 🆒 คูลมากก</blockquote><h3>เริ่มด้วย สามารถประกาศ Entity Struct ได้</h3><p>ใส่ tag ด้วยชื่อ column ที่ต้องการ map</p><pre>type UserEntity struct {<br> ID          string    `db:&quot;id&quot;`<br> Username    string    `db:&quot;username&quot;`<br> Password    string    `db:&quot;password&quot;`<br> Salt        string    `db:&quot;salt&quot;`<br> Status      string    `db:&quot;status&quot;`<br> UpdatedDate time.Time `db:&quot;updated_date&quot;`<br> CreatedDate time.Time `db:&quot;created_date&quot;`<br>}</pre><p>แล้วใช้คำสั่ง Get เพื่อ scan เข้ามาอยู่ใน entity ส่วน argument สังเกตุว่าเราจะรับเป็น $1 ซึ่งแปลว่าตัว lib ทำการ prepare statement ให้เรา ก็หายห่วงเรื่อง sql injection</p><pre>var e UserEntity // destination<br>err := dbx.Get(&amp;e, &quot;select * from app_user where username = $1&quot;, username)<br>if err != nil {<br> return err<br>}</pre><p>ถ้าอยากได้หลาย row ก็ใช้ Select เราสามารถส่ง destination entity เข้าไปเป็น []slide ได้เลย</p><pre>var resultEntity []SearchResultSparePartEntity // destination<br>err = dbx.Select(&amp;resultEntity, q)<br>if err != nil {<br>   return nil, err<br>}</pre><h3>รับ Named Entity แทน arg $1</h3><p>ในกรณีที่ Arguments เยอะ เวลา insert เราอาจจะไม่อยากเขียน $1, $2, $3, … $20 ก็ทำให้ entity เป็น arguements ได้เหมือนกัน โดยใช้คำสั่ง NamedExec</p><pre>now := time.Now()<br>e := repository.UserEntity{<br> ID:          &quot;1234&quot;,<br> Username:    &quot;username&quot;,<br> Status:      &quot;ACTIVE&quot;,<br> UpdatedDate: time.Now(),<br> CreatedDate: time.Now(),<br>}<br>q := &quot;insert into app_user (id, username, password, salt, status, updated_date, created_date) values(:id, :username, :password, :salt, :status, :updated_date, :created_date)&quot;<br>result, err := dbx.NamedExec(q, &amp;e)<br>if err != nil {<br> if pqErr, ok := err.(*pq.Error); ok {<br>  if pqErr.Code == &quot;23505&quot; {<br>   return errors.New(&quot;cannot create duplicate user&quot;)<br>  }<br> }<br> return err<br>}<br>rows, err := result.RowsAffected()<br>if err != nil {<br> return err<br>}<br>logrus.Info(rows)</pre><p>สังเกตุว่า เวลาใช้ Get/Select เราจะ map destination เข้า entity struct แล้วใส่ arguments แยกไป แต่ถ้า NamedExec จะรับ arguments เป็น entity struct แต่ return result ที่เป็นจำนวน RowsAffected ทีนี้ ถ้าอยากรวมหล่ะ</p><h3>ถ้าจะทั้งรับ ทั้งส่ง เป็น entity</h3><p>ก็ให้ PrepareNamedContext ก่อน แล้วค่อย Get/Select</p><pre>e := repository.UserEntity{<br> ID:          &quot;1234&quot;,<br> Username:    &quot;username&quot;,<br> Status:      &quot;ACTIVE&quot;,<br> UpdatedDate: time.Now(),<br> CreatedDate: time.Now(),<br>} // arguments</pre><pre>stmt, err := dbx.PrepareNamedContext(ctx, q)<br>if err != nil {<br> return nil, err<br>}</pre><pre>var resultEntity UserEntity // destination<br>err = stmt.Get(&amp;resultEntity, &amp;e)<br>if err != nil {<br> return nil, err<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=515db24ee672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[บันทึกทำ Date Picker ปี พ.ศ. เตรียม Hacktoberfest2020]]></title>
            <link>https://tanopwan.medium.com/%E0%B8%9A%E0%B8%B1%E0%B8%99%E0%B8%97%E0%B8%B6%E0%B8%81%E0%B8%97%E0%B8%B3-date-picker-%E0%B8%9B%E0%B8%B5-%E0%B8%9E-%E0%B8%A8-%E0%B9%80%E0%B8%95%E0%B8%A3%E0%B8%B5%E0%B8%A2%E0%B8%A1-hacktoberfest2020-a0e6dd0679e3?source=rss-38aa4c4b25c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e6dd0679e3</guid>
            <dc:creator><![CDATA[Tanopwan]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 11:46:04 GMT</pubDate>
            <atom:updated>2020-09-28T11:46:04.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hae14CauafJehPN46gUgfA.png" /></figure><p>Hacktoberfest คืออะไร มันก็คือ กิจกรรม ที่จัดโดย Digital Ocean ที่ให้เหล่า developers ทั่วโลกมาช่วยกัน contribute หรือ pull-request ให้ opensource นั่นเอง ซึ่งจะจัด 1 เดือนเต็ม ใครก็ตามที่สามารถ pull-request ได้ครบ 4 ครั้งภายใน 1–31 ตุลาคม 2020 (ตามชื่อเดือน October -&gt; Hacktober) ก็รับไปเลยจร้า เสื้อยืด 1 ตัว (💙 อย่างเท่ห์)</p><p>นี่มันก็เป็นครั้งแรกของเราเหมือนกัน ซึ่งปกติที่ไม่เคยทำ เพราะไม่รู้เลยว่าเราจะทำอะไรได้บ้าง (เข้าใจว่าทุกคนก็คิดแบบนี้แหละ เลยยังไม่ได้เริ่มทำสักที)</p><p>เรื่องมีอยู่ว่าต้องการ Date picker ที่เป็นปี พ.ศ. จากการที่ค้นหาใน Google อยู่สักพัก พบว่า เฮ้ยย! มันไม่มีคนทำอะ 😫 เป็นไปได้หรอ ก็หาอยู่ 2–3 วัน อย่างมากก็เจอ bootstrap-datepicker ซึ่งถ้าเราไม่อยากใช้ Bootstrap กับ jQuery ก็ไม่มีทางเลือกเลยหรอ</p><p>ก็เอาวะ ลองทำเองมั้ย ก็น่าจะประมาณว่า เอาปีมาบวกด้วย 543 หละมั้ง 😵</p><blockquote><strong>Goal</strong> คือ จะแก้ datepicker ยี่ห้อ Bulma ไม่มีเหตุผลไรมาก เพราะเราชอบ css framework ชื่อ Bulma ก็เลยตั้งเป้าว่าจะแก้ Bulma-Calendar ให้ support ปี พ.ศ. นี่แหละ</blockquote><p>ก็เริ่มไล่ code เลย (จริงๆ อย่างแรกที่เราต้องดูก่อนเลยคือ ความ active ของ maintainers ซึ่งเราไม่ได้ดู ทำให้น้ำตาตกในสุดๆ เดี๋ยวจะเล่า 😢 😰 😢 ) ก็พบว่า มันก็​ support locale นะ แล้ว Bulma-Calendar เค้าใช้ lib date-fns ในการ parse/format date</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grlvZjzPUbgYv09G-sxVFA.png" /></figure><p>จินตนาการในหัวคือ ถ้าเราแก้ lib date-fns ได้ ทุกอย่างก็จบ /// กำลังโลกสวย 💙</p><p>เลยมาลองสำรวจ date-fns repository บ้าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHrzy6ovRu3vq7nM-nSx0w.png" /></figure><p>เฮ้ย!! มีคนเปิด issue ไว้ ว่าอยากได้ Buddhist calendar ด้วย แต่ status เป็น <strong>Open </strong>อยู่เลยอะ จะรออะไรหละ! ก็ fork มาก่อน</p><p>โชคดีก่อนจะไปเจอโชคร้าย date-fns มี Test และ document ที่ดีงาม ถือว่าทำงานง่ายเลย ใช้เวลา 2–3 ชั่วโมงก็สามารถแก้ได้ สวยๆ</p><p>เทสก็มีนะ กะว่า contribute กลับเต็มที่ (ปล เวอร์ชันนี้เขียนคำว่า buddhist ผิดอะ อย่างเขิล มันจะอยู่บน git ตลอดไป ไป ไป ไป ….)</p><p><a href="https://github.com/tanopwan/date-fns/commit/35c091cdd58938776a190e1854eda92ecf5c17cf">Add logic to support buddhist year aka. Thai year · tanopwan/date-fns@35c091c</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmuexTRFWAUngZ3gwkQubw.png" /></figure><p>ตอนนี้หัวใจพองโตมาก ชั้นจะมี ปี พ.ศ. ใช้แล้ววว ก็จัดการมา update lib ที่ Bulma-Calendar เลย คิดว่าแค่ เพิ่ม options ชิวๆ <strong>แต่ พังกระจายจร้า!!! 🔥 🚒</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcE3w6FsMZQm2QQDa9zWYg.png" /></figure><p>ดูไปดูมาคือ date-fns มี breaking change!!! ซึ่ง Bulma-Calendar lib ไม่ได้ update มานานมาก เศร้าไป 1 วันอะ 😅 พูดจริงนะ ความโลกสวยหายไปเลย 555+</p><h3>1 วันผ่านไป มานั่งคิด เรามีทางเลือก 3 ทาง</h3><ol><li>แก้แค่ lib date-fns ได้ก็ โอเครละมั้ง</li><li>กลับไปแก้ lib date-fns ที่ version เก่า</li><li>เอาวะ! ลุยแก้ Bulma-Calendar เลย</li></ol><p>สรุปเลือกข้อ 3 คือ ลุย! แก้อยู่หลายชั่วโมง มีน้ำตาบ้าง มีเดินพักบ้าง ก็ไม่มีอะไรแชร์มาก นอกจากถึกทน ทำไป 😢 ปะ ปุ กันไป ตรงนึงขึ้น อีกตรงนึงสีหาย 555+ จนในที่สุด Date picker แบบปี พ.ศ. ก็คลอดจร้า</p><p>แต่จริงๆ Bulma-Calendar มี feature อีกเยอะซึ่งสารภาพเลย ยังไม่ได้เทสจร้า เอาแค่ที่อยากใช้ก่อนละกัน (อันนี้ ไม่น่าจะ contribute กลับได้) ใครสนใจเข้ามาดู​ใน github ได้เลยจ้า <a href="https://github.com/tanopwan/bulma-calendar">https://github.com/tanopwan/bulma-calendar</a> ใครสนใจก็มาช่วยกันทำต่อได้นะ ฮะ ได้เสื้อนะ 😍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxKiUdxBAk461Vgrny7JSA.png" /></figure><h3>มา join Hacktoberfest กันนะทุกคนนนน</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e6dd0679e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>