📜 [專欄新文章] Gas Efficient Card Drawing in Solidity
✍️ Ping Chen
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
Assign random numbers as the index of newly minted NFTs
Scenario
The fun of generative art NFT projects depends on randomness. The industry standard is “blind box”, where both the images’ serial number and the NFTs’ index are predetermined but will be shifted randomly when the selling period ends. (They call it “reveal”) This approach effectively solves the randomness issue. However, it also requires buyers to wait until the campaign terminates. What if buyers want to know the exact card right away? We’ll need a reliable onchain card drawing solution.
The creator of Astrogator🐊 isn’t a fan of blind boxes; instead, it thinks unpacking cards right after purchase is more interesting.
Spec
When initializing this NFT contract, the creator will determine the total supply of it. And there will be an iterable function that is randomly picking a number from the remaining pool. The number must be in range and must not collide with any existing ones.
Our top priority is accessibility/gas efficiency. Given that gas cost on Ethereum is damn high nowadays, we need an elegant algorithm to control gas expanse at an acceptable range.
Achieving robust randomness isn’t the primary goal here. We assume there’s no strong financial incentive to cheat, so the RNG isn’t specified. Implementers can bring their own source of randomness that they think is good enough.
Implementation
Overview
The implementation is pretty short and straightforward. Imagine there’s an array that contains all remaining(unsold) cards. When drawIndex() is called, it generates a (uniform) random seed to draw a card from the array, shortens the array, and returns the selected card.
Algorithm
Drawing X cards from a deck with the same X amount of cards is equal to shuffling the deck and dealing them sequentially. It’s not a surprise that our algorithm is similar to random shuffling, and the only difference is turning that classic algo into an interactive version.
A typical random shuffle looks like this: for an array with N elements, you randomly pick a number i in (0,N), swap array[0] and array[i], then choose another number i in (1,N), swap array[1] and array[i], and so on. Eventually, you’ll get a mathematically random array in O(N) time.
So, the concept of our random card dealing is the same. When a user mints a new card, the smart contract picks a number in the array as NFT index, then grabs a number from the tail to fill the vacancy, in order to keep the array continuous.
Tweak
Furthermore, as long as the space of the NFT index is known, we don’t need to declare/initialize an array(which is super gas-intensive). Instead, assume there’s such an array that the n-th element is n, we don’t actually initialize it (so it is an array only contains “0”) until the rule is broken.
For the convenience of explanation, let’s call that mapping cache. If cache[i] is empty, it should be interpreted as i instead of 0. On the other hand, when a number is chosen and used, we’ll need to fill it up with another unused number. An intuitive method is to pick a number from the end of the array, since the length of the array is going to decrease by 1.
By doing so, the gas cost in the worst-case scenario is bound to be constant.
Performance and limitation
Comparing with the normal ascending index NFT minting, our random NFT implementation requires two extra SSTORE and one extra SLOAD, which cost 12600 ~ 27600 (5000+20000+2600) excess gas per token minted.
Theoretically, any instantly generated onchain random number is vulnerable. We can restrict contract interaction to mitigate risk. The mitigation is far from perfect, but it is the tradeoff that we have to accept.
ping.eth
Gas Efficient Card Drawing in Solidity was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
risk mitigation 在 Khairy Jamaluddin Facebook 的最佳解答
MAJLIS HIGH TECH NATION KETENGAHKAN TEKNOLOGI MASA HADAPAN
Semalam saya telah mempengerusikan Mesyuarat Majlis High-Tech Nation yang bertujuan merangka hala tuju teknologi sedia ada dan masa hadapan yang berpotensi untuk dibangunkan di Malaysia. Majlis ini juga akan melaporkan sebarang perkembangan secara terus kepada Majlis Sains Negara yang dipengerusikan oleh Perdana Menteri.
Program dan dasar yang akan dibentuk di bawah majlis ini adalah berpandukan kepada kerangka MySTIE 10-10 serta Dasar Sains, Teknologi dan Inovasi (DSTIN) 2021-2030 yang telah saya lancarkan minggu lalu. Sebanyak 30 bidang keutamaan telah dikenal pasti menerusi rangka kerja ini dan majlis ini akan merapatkan jurang yang wujud bagi memastikan ia dapat memberi kesan maksimum kepada setiap bidang keutamaan.
Majlis ini juga akan mengambil peranan secara proaktif dalam mengetengahkan teknologi masa hadapan yang akan melonjakkan kedudukan negara sebagai peneraju teknologi.
Saya juga telah memilih untuk mengutamakan beberapa program, hala tuju dan dasar agar sesuai dengan keperluan masa kini yang mendesak.
Antara cadangan yang telah dibentangkan semalam adalah berkenaan perubatan kepersisan (precision medicine) daripada Kementerian Kesihatan Malaysia (KKM). Perubatan kepersisan berasaskan teknologi data raya ini berupaya mendiagnos serta merancang perubatan yang berkualiti dan terjamin bagi seseorang pesakit.
Selain itu, Institut Penyelidikan Hidraulik Kebangsaan Malaysia (NAHRIM) juga telah membentangkan Hala Tuju Inovasi Air Negara yang akan menjamin keselamatan air. Menerusi hala tuju ini, sebanyak lima program telah dikenal pasti iaitu sungai yang bersih, rizab margin air, sistem air pintar, pengurangan risiko bencana dan pembiayaan air.
Kementerian Sains, Teknologi dan Inovasi (MOSTI) pula telah membentangkan 9 hala tuju yang sedang dibangunkan oleh agensi-agensi di bawah kementerian. Kesemua hala tuju yang akan dibentangkan pada pertengahan 2021 ini akan memacu kerajaan untuk merangka pelaburan serta memformulasi dasar terbaik dalam pembangunan teknologi-teknologi tersebut. Pelan itu antara lain akan merangkumi: blok rantai (blockchain); nanoteknologi; robotik; hidrogen; kecerdasan buatan (AI); litar bersepadu dan bahan termaju (advanced materials)
Akademi Sains Malaysia telah membentangkan cadangan untuk menginstitusikan sebuah badan pemecut pengkomersialan teknologi (Tech-Commercialisation Accelerator) bagi mengetuai dan mengkoordinasi usaha-usaha penyelidikan beradasarkan perniagaan serta ekonomi. Penyelidikan dan pembangunan (R&D) serta sistem penyampaian ini akan dibuat berasaskan permintaan serta keperluan pasaran untuk inovasi-inovasi penganggu (disruptive innovations). Saya akan mengumumkan lebih lanjut mengenai perkara ini sedikit masa lagi.
Institut Penyelidikan Keselamatan Jalan Raya Malaysia (MIROS) telah membentangkan kertas kerja ‘Teknologi Motosikal: Penyelesaian Kepada Dilema Kemajuan Ekonomi-Keselamatan’ dan menjelaskan bahawa 66 peratus daripada kematian di jalan raya melibatkan kemalangan motosikal. Kami berharap untuk memberi insentif dalam pembangunan, pengaplikasian dan penggunaan teknologi sedia ada serta akan datang bagi memperbaiki kebolehcapaian kesemua aspek keselamatan jalan raya. Bidang yang berpotensi untuk dibangunkan termasuklah teknologi pengujian serta verifikasi, teknologi penghindaran kemalangan, teknologi mengurangkan kecederaan (dalam kemalangan), teknologi pemaduan kembali sosial (social reintegration technology-merujuk kepada teknologi respons pintar awal dan pemulihan) serta teknologi pengurusan dan perancangan strategik.
Kementerian Alam Sekitar dan Air pula telah membentangkan Hala Tuju Inovasi Teknologi Hijau Kebangsaan yang mensasarkan penggunaan teknologi hijau menjelang 2030 bagi memastikan kemampanan alam sekitar negara. Inovasi-inovasi sektoral di bawah pelan ini termasuk perolehan hijau kerajaan, teknologi grid pintar, proses perindustrian hijau, pengawasan sungai melalui Internet Segala Benda (IoT), skim Waste to Energy (WTE) and wealth, pengaplikasian bangunan hijau dan pintar, kenderaan cekap tenaga dan kenderaan elektrik, pertanian bandar serta IoT pengawasan hutan.
Akhir sekali, dalam kita mengadaptasi perubahan tingkah laku akibat COVID-19, saya telah meminta MOSTI menyediakan satu kertas kerja mengenai Inisiatif Infrastruktur dan Ekonomi Sentuhan Rendah. Ini memerlukan anjakan paradigma bukan sahaja dalam cara kita berinteraksi sesama sendiri, malahan dengan dunia secara keseluruhan. Antaranya termasuklah penggosok lantai berautonomi, robot pembantu (membawa barangan) dan sistem pengurusan sisa pintar di pasar-pasar awam. MOSTI juga telah melancarkan penggunaan robot di hospital dengan kerjasama KKM serta memulakan modul robotik, dron serta AI di ladang-ladang bersama FELDA. Beberapa inisiatif ini akan direalisasikan di bawah Sandbox Teknologi dan Inovasi Nasional (NTIS).
Kebanyakan progam, hala tuju dan dasar sedia ada selama ini telah dimajukan secara berasingan atau bersendirian oleh pelbagai kementerian dan agensi. Majlis High Tech Nation adalah permulaan baharu kepada cara kita membangun dan mengaplikasi teknologi dalam negara bagi memastikan segalanya selaras dan koheren dengan keperluan nasional.
KHAIRY JAMALUDDIN
MENTERI SAINS, TEKNOLOGI DAN INOVASI
18 DECEMBER 2020
-----------------------------------------------------------------
HIGH-TECH NATION COUNCIL WILL CHAMPION UPCOMING TECHNOLOGIES
Yesterday, I chaired the first High-Tech Nation Council meeting, which aims to give strategic direction regarding existing and upcoming technology that has the potential to be developed in Malaysia. The High-Tech Nation Council will report directly to the National Science Council, which is chaired by the Prime Minister.
The programmes, roadmaps and policies under the High-Tech Nation Council are driven by the mySTIE 10-10 and National Science, Technology and Innovation Policy 2021-2030 that I launched last week. 30 niche areas were identified under this framework, and the High-Tech Nation Council will aim to fill in any gaps we have identified to make sure that there is maximum impact in these areas.
This Council will be proactive and champion upcoming technologies that we need to embark on as a nation to position us at the forefront of what is current and what is cutting-edge.
I have chosen to prioritise some of the programmes, roadmaps and policies in line with pressing national needs.
Some of the papers presented yesterday include the Ministry of Health’s paper on precision medicine, which takes a personalised, predictive, preventive and participatory approach to medicine. This will be layered together with big-data analytics to give personalised recommendations to each person.
National Hydraulic Research Institute of Malaysia (NAHRIM) presented on the National Water Innovation Roadmap, to guarantee national water security. This involves five programmes; Clean River, Reserve Margin, Smart Water, Disaster Risk Reduction, and Water Financing.
The Ministry of Science, Technology and Innovation presented nine roadmaps that are currently being developed under our agencies. All of these roadmaps will be unveiled by the middle of 2021. These roadmaps will guide our investments and policy direction in rolling out these technologies. They will cover: blockchain, nanotechnology, robotics, hydrogen, artificial intelligence, integrated circuits and advanced materials among others.
The Academy of Sciences presented on institutionalising a Tech-Commercialisation Accelerator, to spearhead and coordinate economic-oriented research in the form of demand-driven R&D and market-driven delivery systems for disruptive innovations. I will be announcing this in due course.
The Malaysian Institute of Road Safety Research (MIROS) also presented on Motorcycle Technology: Solving a Dilemma between Economic Development and Safety. 66% of the fatalities on the road involve motorcycles. We hope to incentive the development, application and deployment of existing and future technologies to improve accessibility and all aspects of road safety. Potential areas we are looking at include testing and verification technology, crash avoidance technology, injury mitigation technology (in event of crash), social reintegration technology (which refers to smart first response and rehabilitation technology), and management and strategic planning technology.
The Ministry of Environment and Water presented the National Green Technology Innovation Roadmap, which aims to leverage green technology innovation for an environmentally sustainable Malaysia by 2030. Sectoral innovations under this roadmap include government green procurement, smart grid technology, green industrial process, IoT river monitoring, Waste to Energy and Wealth schemes, application of smart and green buildings, energy efficiency vehicles & electric vehicles, vertical & urban farming, and IoT forest monitoring.
Lastly, but not least, in line with behavioural changes due to COVID-19, I asked MOSTI to prepare a paper on Low-Touch Infrastructure and Economic Initiatives. These will require a paradigm shift in how we look interact both with each other and the world around us. Some of the low-touch initiatives we have quickly identified include autonomous floor scrubbers, autonomous power assist robots (to carry your goods) and smart waste management systems in public markets. We’ve also launched robotics in hospitals together with MOH, and robotics, drones and artificial intelligence modules in plantations together with FELDA. Some of these initiatives will be realised via the National Technology & Innovation Sandbox.
Many of these programmes, roadmaps, and policies have existed and been implemented in silos by different ministries and agencies. This is just the start of how we relook at the development and application of technology in this country, to ensure everything is in line with our national needs and part of a coherent whole.
KHAIRY JAMALUDDIN
MINISTER OF SCIENCE, TECHNOLOGY AND INNOVATION
18 DECEMBER 2020
risk mitigation 在 Roger Chung 鍾一諾 Facebook 的最讚貼文
今早為Asian Medical Students Association Hong Kong (AMSAHK)的新一屆執行委員會就職典禮作致詞分享嘉賓,題目為「疫情中的健康不公平」。
感謝他們的熱情款待以及為整段致詞拍了影片。以下我附上致詞的英文原稿:
It's been my honor to be invited to give the closing remarks for the Inauguration Ceremony for the incoming executive committee of the Asian Medical Students' Association Hong Kong (AMSAHK) this morning. A video has been taken for the remarks I made regarding health inequalities during the COVID-19 pandemic (big thanks to the student who withstood the soreness of her arm for holding the camera up for 15 minutes straight), and here's the transcript of the main body of the speech that goes with this video:
//The coronavirus disease 2019 (COVID-19) pandemic, caused by the SARS-CoV-2 virus, continues to be rampant around the world since early 2020, resulting in more than 55 million cases and 1.3 million deaths worldwide as of today. (So no! It’s not a hoax for those conspiracy theorists out there!) A higher rate of incidence and deaths, as well as worse health-related quality of life have been widely observed in the socially disadvantaged groups, including people of lower socioeconomic position, older persons, migrants, ethnic minority and communities of color, etc. While epidemiologists and scientists around the world are dedicated in gathering scientific evidence on the specific causes and determinants of the health inequalities observed in different countries and regions, we can apply the Social Determinants of Health Conceptual Framework developed by the World Health Organization team led by the eminent Prof Sir Michael Marmot, world’s leading social epidemiologist, to understand and delineate these social determinants of health inequalities related to the COVID-19 pandemic.
According to this framework, social determinants of health can be largely categorized into two types – 1) the lower stream, intermediary determinants, and 2) the upper stream, structural and macro-environmental determinants. For the COVID-19 pandemic, we realized that the lower stream factors may include material circumstances, such as people’s living and working conditions. For instance, the nature of the occupations of these people of lower socioeconomic position tends to require them to travel outside to work, i.e., they cannot work from home, which is a luxury for people who can afford to do it. This lack of choice in the location of occupation may expose them to greater risk of infection through more transportation and interactions with strangers. We have also seen infection clusters among crowded places like elderly homes, public housing estates, and boarding houses for foreign domestic helpers. Moreover, these socially disadvantaged people tend to have lower financial and social capital – it can be observed that they were more likely to be deprived of personal protective equipment like face masks and hand sanitizers, especially during the earlier days of the pandemic. On the other hand, the upper stream, structural determinants of health may include policies related to public health, education, macroeconomics, social protection and welfare, as well as our governance… and last, but not least, our culture and values. If the socioeconomic and political contexts are not favorable to the socially disadvantaged, their health and well-being will be disproportionately affected by the pandemic. Therefore, if we, as a society, espouse to address and reduce the problem of health inequalities, social determinants of health cannot be overlooked in devising and designing any public health-related strategies, measures and policies.
Although a higher rate of incidence and deaths have been widely observed in the socially disadvantaged groups, especially in countries with severe COVID-19 outbreaks, this phenomenon seems to be less discussed and less covered by media in Hong Kong, where the disease incidence is relatively low when compared with other countries around the world. Before the resurgence of local cases in early July, local spread of COVID-19 was sporadic and most cases were imported. In the earlier days of the pandemic, most cases were primarily imported by travelers and return-students studying overseas, leading to a minor surge between mid-March and mid-April of 874 new cases. Most of these cases during Spring were people who could afford to travel and study abroad, and thus tended to be more well-off. Therefore, some would say the expected social gradient in health impact did not seem to exist in Hong Kong, but may I remind you that, it is only the case when we focus on COVID-19-specific incidence and mortality alone. But can we really deduce from this that COVID-19-related health inequality does not exist in Hong Kong? According to the Social Determinants of Health Framework mentioned earlier, the obvious answer is “No, of course not.” And here’s why…
In addition to the direct disease burden, the COVID-19 outbreak and its associated containment measures (such as economic lockdown, mandatory social distancing, and change of work arrangements) could have unequal wider socioeconomic impacts on the general population, especially in regions with pervasive existing social inequalities. Given the limited resources and capacity of the socioeconomically disadvantaged to respond to emergency and adverse events, their general health and well-being are likely to be unduly and inordinately affected by the abrupt changes in their daily economic and social conditions, like job loss and insecurity, brought about by the COVID-19 outbreak and the corresponding containment and mitigation measures of which the main purpose was supposedly disease prevention and health protection at the first place. As such, focusing only on COVID-19 incidence or mortality as the outcomes of concern to address health inequalities may leave out important aspects of life that contributes significantly to people’s health. Recently, my research team and I collaborated with Sir Michael Marmot in a Hong Kong study, and found that the poor people in Hong Kong fared worse in every aspects of life than their richer counterparts in terms of economic activity, personal protective equipment, personal hygiene practice, as well as well-being and health after the COVID-19 outbreak. We also found that part of the observed health inequality can be attributed to the pandemic and its related containment measures via people’s concerns over their own and their families’ livelihood and economic activity. In other words, health inequalities were contributed by the pandemic even in a city where incidence is relatively low through other social determinants of health that directly concerned the livelihood and economic activity of the people. So in this study, we confirmed that focusing only on the incident and death cases as the outcomes of concern to address health inequalities is like a story half-told, and would severely truncate and distort the reality.
Truth be told, health inequality does not only appear after the pandemic outbreak of COVID-19, it is a pre-existing condition in countries and regions around the world, including Hong Kong. My research over the years have consistently shown that people in lower socioeconomic position tend to have worse physical and mental health status. Nevertheless, precisely because health inequality is nothing new, there are always voices in our society trying to dismiss the problem, arguing that it is only natural to have wealth inequality in any capitalistic society. However, in reckoning with health inequalities, we need to go beyond just figuring out the disparities or differences in health status between the poor and the rich, and we need to raise an ethically relevant question: are these inequalities, disparities and differences remediable? Can they be fixed? Can we do something about them? If they are remediable, and we can do something about them but we haven’t, then we’d say these inequalities are ultimately unjust and unfair. In other words, a society that prides itself in pursuing justice must, and I say must, strive to address and reduce these unfair health inequalities. Borrowing the words from famed sociologist Judith Butler, “the virus alone does not discriminate,” but “social and economic inequality will make sure that it does.” With COVID-19, we learn that it is not only the individuals who are sick, but our society. And it’s time we do something about it.
Thank you very much!//
Please join me in congratulating the incoming executive committee of AMSAHK and giving them the best wishes for their future endeavor!
Roger Chung, PhD
Assistant Professor, CUHK JC School of Public Health and Primary Care, @CUHK Medicine, The Chinese University of Hong Kong 香港中文大學 - CUHK
Associate Director, CUHK Institute of Health Equity
risk mitigation 在 Risk Mitigation Planning, Implementation, and Progress ... 的相關結果
Risk Mitigation Planning, Implementation, and Progress Monitoring · Definition: Risk mitigation planning is the process of developing options and actions to ... ... <看更多>
risk mitigation 在 What is Risk Mitigation? - Reciprocity 的相關結果
Risk mitigation involves taking action to reduce an organization's exposure to potential risks and reduce the likelihood that those risks ... ... <看更多>
risk mitigation 在 What is Risk Mitigation? Definition, Strategies and Planning 的相關結果
Risk mitigation is a strategy to prepare for and lessen the effects of threats faced by a business. Comparable to risk reduction, risk mitigation takes ... ... <看更多>